我想使用另一個向量v2對向量v1進行排序。而這段代碼運行使用函數對象的向量上的C++排序
terminate called after throwing an instance of '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