map排序问题
map<int,struct A>
map排序只能对key_type排序吗?如果对data_type排序是不是很麻烦?
key_compare key_comp() const { return _M_t.key_comp(); }
value_compare value_comp() const { return value_compare(_M_t.key_comp()); }
allocator_type get_allocator() const { return _M_t.get_allocator(); }
typedef pair<const _Kty, _Ty> value_type;
...
class value_compare
: public binary_function<value_type, value_type, bool>
{// functor for comparing two element values
friend class _Tmap_traits<_Kty, _Ty, _Pr, _Alloc, _Mfl>;
public:
bool operator()(const value_type& _Left,
const value_type& _Right) const
{// test if _Left precedes _Right by comparing just keys
return (comp(_Left.first, _Right.first));
}
value_compare(key_compare _Pred)
: comp(_Pred)
{// construct with specified predicate
}
protected:
key_compare comp;// the comparator predicate for keys
};
return (comp(_Left.first, _Right.first));
}
value_compare(key_compare _Pred)
: comp(_Pred)
{ // construct with specified predicate
}
protected:
key_compare comp; // the comparator predicate for keys
};
[其他解释]
map就是按key排序的,不过存储形式是key-value的pair而已,实际比较的还是pair.first,即key的比较。
楼主可以让data_type当做key,key当做data,不就得了?
[其他解释]
动态的吧
[其他解释]
如果决定用map了,但是还需要按value排序,那八成是数据结构设计有问题,建议再review一下设计 。
[其他解释]
没这么排过 等待高人。。。
[其他解释]
建2个map
map<int,struct A>
map<struct A,int>
一个查,一个排序
不就行了
[其他解释]
这个,这个C++里面的map没实现compare()方法么?
记得map本来就是有序键值对嘛~~
[其他解释]
map按value排序的方法,给个例子吧:
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm> //使用STL的sort函数
using namespace std;
typedef pair<string, double> MyPair;
//比较函数
bool compare(const MyPair& x, const MyPair& y)
{
return x.second > y.second;
}
int main()
{
map<string, double> myMap;
myMap.insert(pair<string, double>("238",0.2785));
myMap.insert(pair<string, double>("154",0.7461));
myMap.insert(pair<string, double>("192",0.2479));
myMap.insert(pair<string, double>("30",0.3902));
myMap.insert(pair<string, double>("232",0.2717));
myMap.insert(pair<string, double>("220",0.2803));
//逐个pair插入到vector
vector<MyPair> myVector;
for(map<string, double>::iterator mIter = myMap.begin(); mIter != myMap.end(); mIter++)
{
MyPair tmpPair(mIter->first, mIter->second);
myVector.push_back(tmpPair);
}
//STL的sort函数
sort(myVector.begin(), myVector.end(), compare);
//输出排序后的数据
for(vector<MyPair>::iterator vIter = myVector.begin(); vIter != myVector.end(); vIter++)
cout<<vIter->first<<"\t"<<vIter->second<<endl;
//输出nodes
return 0;
}
执行结果:
154 0.7461
30 0.3902
220 0.2803
238 0.2785
232 0.2717
192 0.2479
请按任意键继续. . .