<分区>
我创建了一个 vector vector ,我想根据我定义的参数对它们进行排序。在这里,sort()
函数采用定义为 vector<vector<int>>
的变量数据集只是一个vector<int>
.谁能解释一下出了什么问题?
此外,即使解决了上述问题,compare()
函数仅适用于硬编码索引。如果我想根据不同的索引对其进行排序,我应该怎么做。有没有我可以提及的方法?
#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;
}