我有
vector<vector<int>> vec
在我的C++应用程序中。
"big"向量的每个整数向量作为一个元素,有4个int值。我想基于其内容int向量的第三个值(我指的是每个“内部”向量的第三个元素)对vec进行排序 - 这是可能的吗?
编辑
假设我有一个函数
COST(vector<int>)
根据我的向量值计算出某个值,那我能不能也将它用作比较参数呢?这会对我非常有帮助。
当然可以。 std::sort
可以接受第三个参数,这个参数是在排序时使用的比较函数。例如,您可以使用 lambda 函数:
std::vector<std::vector<int>> vec;
// Fill it
std::sort(vec.begin(), vec.end(),
[](const std::vector<int>& a, const std::vector<int>& b) {
return a[2] < b[2];
});
或者,您可以传递任何具有签名bool(const std::vector<int>&, const std::vector<int>&)
的可调用对象,例如函数对象或函数指针。
编辑响应:只需将您的COST
函数应用于a
和b
:
std::sort(vec.begin(), vec.end(),
[](const std::vector<int>& a, const std::vector<int>& b) {
return COST(a) < COST(b);
});
如果你想通过成本比较这两个向量,请尝试以下方法:
bool predicate(const std::vector<int>& a, const std::vector<int>& b)
{
return COST(a) < COST(b);
}
注:
sort(vec.begin(), vec.end(), comp);
其中comp
是:
static bool comp(const vector<int>& vec1, const vector<int>& vec2){
return vec1[2] < vec2[2];
}
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <ctime>
using namespace std;
// This makes the sort be according to column 2 and ascending
bool sortFunc( const vector<int>& p1,
const vector<int>& p2 ) {
return p1[1] < p2[1];
}
int main() {
srand(time(NULL));
// Creates and initializes 10 x 4 vector
vector< vector<int> > vec;
for( int i=0; i<10; i++ ) {
vector<int> tmpVec;
for( int j=0; j<2; j++ ) {
tmpVec.push_back( rand()%10 );
}
vec.push_back( tmpVec );
}
// Print out the pre-sorted vector
cout << "Pre-sorting state:" << endl;
for( int i=0; i<vec.size(); i++ ) {
for( int j=0; j<vec[i].size(); j++ ) {
cout << vec[i][j] << " ";
}
cout << endl;
}
cout << endl;
// Do the sorting according to column 2
sort(vec.begin(), vec.end(), sortFunc);
// Print out the post-sorted vector
cout << "Post-sorting state:" << endl;
for( int i=0; i<vec.size(); i++ ) {
for( int j=0; j<vec[i].size(); j++ ) {
cout << vec[i][j] << " ";
}
cout << endl;
}
return 0;
}
来源:https://shihho.wordpress.com/2012/11/28/sort_with_vectors/
cost(a) < cost(b)
。 - RiaD