I have created a vector of vectors and I would like to sort them based on parameters that I define. Here, the sort()
function takes the variable dataset defined as vector<vector<int>>
to be just a vector<int>
. Could someone explain what is going wrong?
Moreover, even after the above said problem is sorted out, compare()
function would work only for hard coded indices. How should I go about it, if I would like to sort it based on different indices. Is there a method that I can mention to do so?
#include <iostream>
#include <vector>
#include <algorithm>
//void check_function(std::vector <std::vector <int> > *dataset)
//{
// std::cout<<(*dataset)[0].size()<<std::endl;
//}
bool compare(const std::vector <std::vector <int> > &a, const std::vector <std::vector <int> > &b)
{
return a[1] < b[1];
}
/* This works, but this sorts based on the first parameter of the vector rather than what I mention.
bool compare(const std::vector <int> &a, const std::vector <int> &b)
{
return a < b;
}
*/
int main()
{
std::vector <int> data;
std::vector <int> data2;
std::vector <std::vector <int> > dataset;
data.push_back(5);
data.push_back(10);
dataset.push_back(data);
data2.push_back(5);
data2.push_back(20);
dataset.push_back(data2);
// check_function(&dataset);
std::sort(dataset.begin(), dataset.end(), compare);
std::cout<< dataset[0][0]<<std::endl;
return 0;
}