stl map
map 中怎么设置多个key值进行排序以及它们的优先级(例子解释)
[解决办法]
封装多个key,自己实现比较函数.
struct Key
{
KEY1
KEY2
...
bool operator<(const Key&);
};;...
[解决办法]
multimap才能存储相同的key。
[解决办法]
对,multimap和multiset这两个才能存key重复的吧。
[解决办法]
一楼给出的方法是可行的。
你可以将两个key:k1, k2放到一个struct中,然后在用这个struct的实例作为map的key。
在比较的时候,你可以先比较k1,如果k1是相等的话,就比较k2
[解决办法]
参考下面的代码,应该满足楼主的要求
#include <iostream>#include <string>#include <map>using namespace std; class key{public: int k1; int k2; key(int x, int y):k1(x), k2(y) { } friend bool operator < (const key&, const key&);};bool operator < (const key& key1, const key& key2){ // 按k1升序 + k2升序排列 //if(key1.k1 != key2.k1) return (key1.k1 < key2.k1); //else return (key1.k2 < key2.k2); // 按k1降序 + k2升序降序 //if(key1.k1 != key2.k1) return (key1.k1 > key2.k1); //else return (key1.k2 > key2.k2); // 按k1升序 + k2降序排列 //if(key1.k1 != key2.k1) return (key1.k1 < key2.k1); //else return (key1.k2 > key2.k2); // 按k1降序 + k2升序排列 if(key1.k1 != key2.k1) return (key1.k1 > key2.k1); else return (key1.k2 < key2.k2);}int main(int argc, char** argv){ map<key, string> str_map; str_map.insert(make_pair(key(2, 1), "hello")); str_map.insert(make_pair(key(2, 2), "world")); str_map.insert(make_pair(key(1, 2), "HELLO")); str_map.insert(make_pair(key(1, 1), "WORLD")); map<key, string>::iterator iter; for(iter = str_map.begin(); iter != str_map.end(); ++iter) { cout << iter->first.k1 << "\t" << iter->first.k2 << "\t" << iter->second << endl; } //vector<key> vec; //vec.push_back(key(1, 1)); //vec.push_back(key(1, 2)); //vec.push_back(key(2, 1)); //vec.push_back(key(2, 2)); //sort(vec.begin(), vec.end(), comparer); //vector<key>::iterator iter; //for(iter = vec.begin(); iter != vec.end(); ++iter) //{ // cout << (*iter).k1 << "\t" << (*iter).k2 << endl; //} return 0;}