对向量进行排序不起作用

sort on a vector doesn't work

本文关键字:排序 不起作用 向量      更新时间:2023-10-16

为什么排序函数在下面的示例中不起作用?我没有任何警告,也没有编译器错误。这正常吗?我该怎么修?提前感谢

#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;
}