我們知道,在向map中插入數(shù)據(jù)對時候,map中的元素將按照一定的順序被插入到對應的節(jié)點上,換句話說,從map的頭開始順序地讀取數(shù)據(jù),其數(shù)據(jù)的順序?qū)⒉煌谀悴迦霑r候的順序, 例子如下:
std::map<double,int> dnMap;
dnMap[10.0] = 1;
dnMap[2.9] = 2;
dnMap[20.4] = 3;
std::map<double,int>::iterator it = dnMap.begin();
for(; it != dnMap.end();++it)
{
std::pair<double,int> _p = *it;
std::cout <<"Key =" <<_p.first<<" Value = "<< _p.second<< endl;
}
輸出的順序?qū)⑹牵?/p>
Key = Value =
2.9 2
10.0 1
20.4 3
如果map的鍵是用戶自定義的類型T,那么你還必須在T中實現(xiàn)比較運算符,至于具體的細節(jié)這里就不說了。
但是如果你覺得map對你很合適,但是就是希望插入map中的數(shù)據(jù)保持最初插入時候的順序,這時候怎么辦?
讓我們來看看stl中map的 聲明形式 (http://www.sgi.com/tech/stl/Map.html)
map<Key, Data, Compare, Alloc>
注意第三個參數(shù)
Compare : The key comparison function, a Strict Weak Ordering whose argument type is key_type; it returns true if its first argument is less than its second argument, and false otherwise. This is also defined as map::key_compare.
其作用就是比較Key的大小,按照一定的順序確定map節(jié)點的順序,我們當然就可以定制這個函數(shù)對象以實現(xiàn)我們想要的的排序規(guī)則。
好了,廢話說了不少,我的做法是
template<class T>
struct DisableCompare :public std::binary_function<T,T,bool>
{
bool operator()(T lhs,T rhs) const
{
return true;
}
};
這樣來使用定制化的map :
std::map<double,int,DisableCompare<double> > sMap;
sMap[10.9] = 1;
sMap[3.5] = 2;
sMap[30.0] = 3;
sMap[2.4] = 4;
就可以保持數(shù)據(jù)插入時候的順序了。
結(jié)論:這種方法只適合int,double數(shù)值為Key的情況,字符串的情況不行,最后用Vector解決,方法如下:
typedef std::pair <WE::String, WE::String> SqlPair;
typedef std::vector<std::pair<WE::String, WE::String > > SqlBaseVector;
class SqlVector : public SqlBaseVector
{
public:
void push_back (const SqlPair& sqlPair);
void push_back (const WE::String& sql, const WE::String& tableName);
SqlVector(){};
~SqlVector(){};
};
class SqlMap : public SqlVector
{
public:
const WE::String& get_element(const WE::String& key);
void set_element(const WE::String& key, const WE::String& value);
SqlMap(){};
~SqlMap(){};
};