首页 > 解决方案 > How do I get my templated bubbleSort() function to display a sorted vector?

问题描述

The bubblesort() function I have for my vector, fails to return a sorted version of the vector; there are times where if I do compile and execute the code in VS it gives me a runtime error when the function is called:

Expression: vector subscript out of range

I've double checked the range, and it seems alright to me; I'm unsure what the issue is: I did make sure the vector was passed by reference.

#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>

template <class T>
void fillVector(std::vector<T>& vobj, int n);

template <class T>
void displayVector(std::vector<T>& vobj);

template <class T>
void bubbleSort(std::vector<T>& vobj);
template <class T>
void fillVector(std::vector<T>& vobj, int n)
{
    srand((unsigned int)time(NULL));
    for (int i=0; i<n; ++i)
    {
        vobj.push_back(rand());
    }
}

template <class T>
void displayVector(std::vector<T>& vobj)
{
    const unsigned displayLimit = 10;
    if (vobj.size()>displayLimit)
    {
        for (unsigned i=0; i<displayLimit; ++i)
        {
            std::cout << "  " << vobj[i];
        }
        std::cout << "  ..." << std::endl;
    }
    else
    {
        for (unsigned i = 0; i < vobj.size(); ++i)
        {
            std::cout << vobj[i] << " ";
        }
    }
}
template <class T>
void bubbleSort(std::vector<T>& vobj)
{
    bool swapped = true;
    for (unsigned i=0; swapped && i<vobj.size()-1; ++i)
    {
        swapped = false;
        for (unsigned j=0; j<vobj.size()-1-i; ++j)
        {
            if (vobj[j]>vobj[j++])
            {
                swapped = true;
                std::swap(vobj[j],vobj[j++]);
            }
        }
    }
}

int main()
{
    std::vector<int> vobj;

    std::cout << "Enter # of objects you'd like to store in the vector object: ";
    int n;
    std::cin >> n;
    std::cout << "\n*** Calling fillVector(...) ***" << std::endl;
    fillVector(vobj,n);
    std::cout << "\n*** Calling displayVector(...) ***" << std::endl;
    std::cout << "Vector object contains " << n << " value(s) which are" << std::endl;
    displayVector(vobj);

    std::cout << "\n*** Calling bubbleSort(...) ***" << std::endl;
    bubbleSort(vobj);
    displayVector(vobj);
}

标签: c++arrayssortingvector

解决方案


在您的bubbleSort例程中,您将j变量增加 3 次!你不觉得那是两倍多吗?

if (vobj[j]>vobj[j++]) 

应该

if (vobj[j]>vobj[j+1]) 

std::swap(vobj[j],vobj[j++]); 

应该

std::swap(vobj[j],vobj[j+1]); 

增加一个变量与增加一个变量是不同的。


推荐阅读