multimap<vector<int> > ,char> 怎么排序呢?

multimap<vector<int> > ,char> how to sort it?

这是代码,可以编译,但是不能运行,为什么?:

#include <iostream>
#include <map>
#include <vector>
using namespace std;
int main() {
    typedef multimap<vector< int >, char> mmap;

    mmap foo;
    vector<int> v;
    v.push_back(15);
    v.push_back(14);
    foo.insert(pair<vector< int >, char> (v, 'b'));
    v.clear();
    v.push_back(15);
    v.push_back(80);
    foo.insert(pair<vector< int >, char> (v, 'c'));
    v.clear();
    v.push_back(9);
    v.push_back(17);
    foo.insert(pair<vector< int >, char> (v, 'a'));
    v.clear();

    mmap::iterator iter;

    for (int i = 0; i < iter->first.size(); ++i) {
        wcout << iter->first[i] << " ";
        for (iter = foo.begin(); iter != foo.end(); ++iter) {
            wcout << iter->second << " ";
        }
        wcout << endl;
    }
}

输出:

15 80 度

15 14 b

9 17 个

我想加上整数,然后排序: (将数字从大到小排序

80+15>15+14>9+17

怎么做?

您需要使用自定义比较 function/functor 来帮助您。

struct Compare
{
   bool operator()(std::vector<int> const& lhs, std::vector<int> const& rhs) const
   {
      int sum1 = std::accumulate(lhs.begin(), lhs.end(), 0);
      int sum2 = std::accumulate(rhs.begin(), rhs.end(), 0);
      return (sum1 > sum2); // Not sum1 < sum2, if I understood your question
   }
};

并使用:

typedef multimap<vector< int >, char, Compare> mmap;

您还必须修复打印 foo 内容的代码。

mmap::iterator iter = foo.begin();
for ( ; iter != foo.end(); ++iter )
{
   for ( size_t i = 0 ; i < iter->first.size() ; ++i ) {
      wcout << iter->first[i] << " " ;
   }
   wcout << iter->second << " " ;
   wcout << endl ;
}

您在内部 for 循环中初始化了 iter:

for ( iter = foo.begin() ; iter != foo.end() ; ++iter )

但是,您尝试在它指向任何内容的外部 for 循环中访问:

for ( int i = 0 ; i < iter->first.size() ; ++i )