这是代码,它可以编译,但它无法运行,为什么?:
#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 c
15 14 b
9 17 a
我想加上整数,然后对它进行排序: (将数字从最大到最小排序
80 + 15→15 + 14 - 9 + 17
怎么做?
答案 0 :(得分:5)
您需要使用自定义比较功能/仿函数来帮助您。
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 ;
}
答案 1 :(得分:2)
你在内部for循环中初始化了iter:
for ( iter = foo.begin() ; iter != foo.end() ; ++iter )
但是,您尝试在外部for循环中访问它所指向的内容:
for ( int i = 0 ; i < iter->first.size() ; ++i )