I have a vector of vector containing elements of type long as follows:
vector< vector<long> > Data(N,vector<long>(M));
I have to sort these vectors based on their values i.e. For Two vectors
Data[i] & Data[j]
if for some k Data[i][k]< Data[j][k]
and Data[i][t]==Data[j][t] for all 0<=t<=(k-1),
then Data[i] should come before Data[j] in the final vector
Not for the above task I wrote the following code:
sort(Data.begin(),Data.end(),myfunc);
where
bool myfunc(vector<long> vec1,vector<long> vec2){
int i=0;
while(i<vec1.size()){
if(vec1[i]<vec2[i]){
return false;
}
else if(vec1[i]>vec2[i]){
return true;
}
i++;
}
return false;
}
However, I am not getting the desired output. In fact the input and output vectors are the same. Where did I go wrong?? Am I missing something??
You have a couple mistakes, but not all are evident to you (yet).
bool myfunc(const vector<long>& vec1, const vector<long>& vec2){
for(size_t i = 0; i < vec1.size() && i < vec2.size(); i++){
if(vec1[i] > vec2[i]){
return false;
} else if(vec1[i] < vec2[i]){
return true;
}
}
return false;
}
I took the liberty of using a for loop and size_t, which are better practices here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With