我正在尝试使用另一个向量v2对向量v1进行排序。我无法理解这个错误:
终止调用后抛出了“std::out_of_range”的实例
what(): vector::_M_range_check
Abort trap
当运行以下代码时:
终止调用后抛出了“std::out_of_range”的实例
what(): vector::_M_range_check
Abort trap
当运行以下代码时:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Comp
{
public:
Comp(vector<double>& inVec): _V(inVec) {}
bool operator()(int i, int j) {return (_V.at(i)<_V.at(j));}
private:
vector<double> _V;
};
int main(int argc, char** argv)
{
double x1[] = {90.0, 100.0, 80.0};
double x2[] = {9.0, 3.0, 1.0};
vector<double> v1(x1,x1+3);
vector<double> v2(x2,x2+3);
sort(v1.begin(), v1.end(), Comp(v2)); // sort v1 according to v2
for(unsigned int i=0; i<v1.size(); i++)
{
cout << v1.at(i) << " " << v2.at(i) << endl;
}
return 0;
}
v1
和v2
的大小相同,为什么会出现out_of_range
错误?
非常感谢您提供的任何指导。
Comp
类应该持有对向量的引用,而不是复制它。 - Tim