对向量的向量进行排序

22

我有

    vector<vector<int>> vec 

在我的C++应用程序中。

"big"向量的每个整数向量作为一个元素,有4个int值。我想基于其内容int向量的第三个值(我指的是每个“内部”向量的第三个元素)对vec进行排序 - 这是可能的吗?

编辑

假设我有一个函数

COST(vector<int>)

根据我的向量值计算出某个值,那我能不能也将它用作比较参数呢?这会对我非常有帮助。


1
只需定义自己的比较运算符,使用第三个元素的值即可。详情请参见此处:https://dev59.com/xHM_5IYBdhLWcg3wcCnc - thang
1
请记住,Lambda表达式也是一种选择。 - chris
嗯,你所有的内部“向量”都包含4个“int”,每个“int”都有特殊的含义?听起来你更想在那个向量中放置一个类的对象? - lethal-guitar
在你的比较器中返回 cost(a) < cost(b) - RiaD
4个回答

53

当然可以。 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函数应用于ab

std::sort(vec.begin(), vec.end(),
          [](const std::vector<int>& a, const std::vector<int>& b) {
  return COST(a) < COST(b);
});

2
请注意,第三个参数是一个严格弱排序函数,如果第一个参数应该放在第二个参数之前,则返回true。这相当于小于号(即a < b)。这是为了在需要按降序排序时使用。 - thang
1
当向量的向量中只有一个元素时,我会遇到错误,因为'b'将为空,而'b [2]'将抛出'reference binding to null pointer of type 'int''。 有什么解决方法吗? - Dane

4

如果你想通过成本比较这两个向量,请尝试以下方法:

bool predicate(const std::vector<int>& a, const std::vector<int>& b)
{
    return COST(a) < COST(b);
}

注:

  • 上述方法也适用于C++98,但我不确定C++11的使用范围是否广泛,以及您是否有符合标准的编译器。否则,您当然也可以使用Lambda表达式,就像sftrabbit建议的那样。
  • 您没有说明COST()返回什么,我只是假设它返回了一些可排序的值,比如float或long。
  • 希望您在将vector传递给COST()时不要复制它,那样效率会非常低下。
  • COST()建议使用宏,就像所有大写字母名称一样。不要使用宏。不要使用宏名称作为函数名。

3

sort(vec.begin(), vec.end(), comp);

其中comp是:

static bool comp(const vector<int>& vec1, const vector<int>& vec2){
    return vec1[2] < vec2[2];
}

1
#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/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接