【发布时间】:2014-05-13 19:49:40
【问题描述】:
我正在尝试让选择排序与向量一起使用。我运行程序,它执行了未排序的第一部分,但随后显示表达式:向量下标超出范围。不知道是什么原因造成的。
#include <iostream>
#include <vector>
using namespace std;
template<typename Comparable>
void selectionSort(vector<Comparable> & toSort)
{
int pos, min, i;
for( pos = 0; pos < 30; ++pos)
{
min = toSort[pos];
for( i = toSort[pos + 1]; i < toSort[30]; ++i)
{
if( i < min)
{
min = i;
}
}
if( min != pos)
{
std::swap(toSort.at(min), toSort.at(pos));
}
}
}
int main(int argc, const char * argv[])
{
const int NUM_ITEMS = 5;
int array[NUM_ITEMS] = { 16, 271, 77, 40, 120 };
vector<int> sortingVector;
for(int i=0;i<NUM_ITEMS;i++) {
sortingVector.push_back(array[i]);
}
cout << "Before sort \n";
for(int i=0;i<NUM_ITEMS;i++) {
cout << sortingVector[i] << "\n";
}
selectionSort(sortingVector);
cout << "After sort \n";
for(int i=0;i<NUM_ITEMS;i++) {
cout << sortingVector[i] << "\n";
}
system("pause");
return 0;
}
【问题讨论】:
-
您的向量大小为 5,您将其视为大小为 31。
-
你是说你没看到这个?
for( pos = 0; pos < 30; ++pos),然后你正在访问tosort[30]? -
参见this Q&A 了解使用迭代器的 STL 风格
selection_sort -
嗯,我不知道我是怎么把 30 放在那里的。我觉得自己像个白痴。感谢您指出我的愚蠢事故
-
很好的问题:“当它说 X 时,编译器/运行时是什么意思?”很好的问题:“为什么这个(非常非常短;即 10 行或更少)专门为 SO 编写的代码示例会生成错误 X?”非常糟糕的问题:“我在这乱七八糟的代码中遇到运行时错误 X,请帮我调试一下”
标签: c++ sorting vector selection-sort