I have created a 2D vector in C++ as
vector< vector<float> *> mvector
mvector.push_back( new vector<float>(2,0.0))
Each vector element contains a pointer to a vector of size 2 . I want to sort the vector on the basis of second element using pre-puilt sort function in C++.
My code is :
#include<iostream>
#include<vector>
#include<cmath>
#include<algorithm>
using std::cout;
using std::cin;
using std::endl;
using std::vector;
using std::sort;
int mycomp( vector<float> *a , vector<float > *b)
{
//return ((vector< vector<float> > *)a)[0][1] - (( vector< vector<float> > *)b)[0][1];
//return (vector < vector<float> *>*)a[0][1] - (vector< vector<float> *>*)b[0][1];
return a->at(1) - b->at(1);
}
int main(void)
{
vector< vector<float> * > mvector ;
int i;
for(i=0;i<2;i++)
{
mvector.push_back( new vector<float>(2,0.0) ) ;
cin >> mvector.back()->at(0) ;
mvector.back()->at(1) = sin(mvector.at(i)->at(0));
}
sort(mvector.begin() , mvector.end() , mycomp);
for(i=0;i<2;i++)
{
cout << mvector.at(i)->at(0) << " : " << mvector.at(i)->at(1) << endl;
}
return 0;
}
But sort function is not working , i think i am doing mistake in passing the reference of the 2D vector in sort function . Any one can correct it ?
vector< vector<float> > mvector;
sort(mvector.begin(), mvector.end(), [](const vector<float>& left, const vector<float>& right)
{
return left.at(1) < right.at(1);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.