c++ - 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);
}
解决方案
在您的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]);
增加一个变量与增加一个变量是不同的。
推荐阅读
- javascript - 将 jQuery UI 滑块与复选框事件绑定的问题
- laravel - Laravel 用户无法登录,只有管理员可以登录
- c++ - 使用 Jetbrains CLion 找不到此 cpp 项目的正确编译器
- python - Python断言重复
- python-3.x - mypy 调用错误:类不能在石墨烯上子类化“ObjectType”(具有“Any”类型)
- python - curs.execute 抛出为语句指定的无效长度
- postgresql - 错误:关系“用户”的“用户名”列不存在
- flutter - 如何在颤动中为小部件添加阴影?
- c# - 变量更改时文本框不更新
- firefox - Firefox 的 devtools 中未打印此错误