对向量进行排序不起作用
sort on a vector doesn't work
为什么排序函数在下面的示例中不起作用?我没有任何警告,也没有编译器错误。这正常吗?我该怎么修?提前感谢
#include <iostream>
#include <cmath>
#include <boost/shared_ptr.hpp>
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <iterator>
int main (){
typedef std::vector<double> VecDoub;
VecDoub a;
a.push_back(2.01);
a.push_back(1.01);
a.push_back(0.01);
a.push_back(4.01);
VecDoub::iterator it = a.begin();
while (it != a.end()){
std::cout << *it << std::endl;
++it;
}
std::sort(a.begin(), a.end());
while (it != a.end()){
std::cout << *it << std::endl;
++it;
}
}
您忘记在第二个while
之前将it
重置为a.begin()
。
在第一个循环之后,迭代器it
等于a.end().
。因此,不执行第二个while循环。
当局部变量的范围过大时,这是一个常见的错误。:)您可以将while循环用于具有变量it的循环,该变量具有每个循环的作用域。
for ( VecDoub::iterator it = a.begin(); it != a.end(); ++it; ){
std::cout << *it << std::endl;
}
或者,使用基于范围的for循环会更好。例如
for ( auto x : a ) std::cout << x << std::endl;
您的排序函数对容器进行了正确的"排序",但是您的控件没有进入第二个while循环来显示结果,因为它的中断条件是有效的:it == a.end
。所以你认为它没有排序,事实上你只是没有看到它。
这应该有效:
it = a.begin(); // reset or declare new
while (it != a.end()) {
std::cout << *it << std::endl;
++it;
}
相关文章:
- 尝试使用C++中的模板进行BST排序,但在使用随机字符串进行测试时不起作用
- 我的C++合并排序代码不起作用。我在这里错过了什么?
- 使用选择排序对数组数据结构进行排序,但它不起作用
- c++ 选择排序在特定情况下不起作用
- 排序不起作用 c++
- 在 C++ 中使用 10 个随机整数的数组进行气泡排序不起作用
- 插入排序不起作用
- 分而治之合并排序不起作用
- C 排序字符串的动态阵列 - 排序不起作用
- 为什么tha std :: list ::排序不起作用
- C++向量<Struct>排序不起作用
- 快速排序不起作用(分段错误)
- 使用qsort对字符串进行排序不起作用
- 自定义结构排序不起作用
- 为什么我的快速排序不起作用
- 简单std::排序不起作用
- 为什么泡沫排序不起作用
- std::矢量排序不起作用
- 对向量进行排序不起作用
- 为什么这个基数排序不起作用