1、对于<set><multiset><map>和<multimap>如果准则不同,准则本身也会被赋值(assigned)或交换(swapped)。
2、在<map><multimap>中,所有的元素的key都被视为常数。元素的实质型别是pair<const key ,T >(确保不会因为变更元素的value而破坏已排好的元素次序)。
注:如果你一定要改变元素的key,只有一条路:以一个"value相同"的新元素替换旧元素。(即删除旧元素,插入一个新元素,只是旧和新元素的value值相同。)
map提供一个种简便方法:
//insert new element with value of old element
coll["new_key"] = coll["old_key"];
//remove old element
coll.erase("old_key");
3.移除"拥有某个value(而非某个key)"的元素的代码如下(P205):
typedef std::map<std::string,float> StringFloatMap;
StringFloatMap coll;
StringFloatMap::iterator pos;
...
// remove all elements having a certain value
for(pos = coll.begin(); pos != coll.end();){
if(pos->second == value) {
coll.erase(pos++);
}
else{
++pos;
}
}
4。示例:
/**
*反映股票行情
*/
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
typedef map<string,float> StringFloatMap;
StringFloatMap stocks;
stocks["BASF"] = 369.50;
stocks["VW"] = 413.50;
stocks["Daimler"]=819.00;
stocks["BMW"] = 834.00;
stocks["Siemens"]=842.20;
StringFloatMap::iterator pos;
for(pos=stocks.begin();pos!=stocks.end();++pos){
cout<<"stock: "<<pos->first<<"\t"
<<"price: "<<pos->second<<endl;
}
cout<<endl;
for(pos=stocks.begin();pos!=stocks.end();++pos){
pos->second*=2;
}
for(pos=stocks.begin();pos!=stocks.end();++pos){
cout<<"stock: "<<pos->first<<"\t"
<<"price: "<<pos->second<<endl;
}
cout<<endl;
stocks["Volkswagen"]=stocks["VW"];
stocks.erase("VW");
for(pos=stocks.begin();pos!=stocks.end();++pos){
cout<<"stock: "<<pos->first<<"\t"
<<"price: "<<pos->second<<endl;
}
return 0;
}
/**
*1.如何使用maps
*2.如何撰写和使用仿函数(functor)
*3.如何在执行期定义排序算法
*4.如何在“不在乎大小写”的情况下比较字符串(strings)
*/
#include <iostream>
#include <map>
#include <string>
#include <iomanip>
#include <algorithm>
using namespace std;
class RuntimeStringCmp{
public:
enum cmp_mode{normal,nocase};
private:
const cmp_mode mode;
static bool nocase_compare(char c1,char c2)
{
return toupper(c1)<toupper(c2);
}
public:
RuntimeStringCmp(cmp_mode m=normal):mode(m){
}
bool operator()(const string& s1,const string& s2)const{
if(mode==normal){
return s1<s2;
}
else{
return lexicographical_compare(s1.begin(),s1.end(),
s2.begin(),s2.end(),nocase_compare);//用于按字典序比较两个序列。
}
}
};
typedef map<string,string,RuntimeStringCmp> StringStringMap;
void fillAndPrint(StringStringMap& coll);
int main()
{
StringStringMap coll1;
fillAndPrint(coll1);
RuntimeStringCmp ignorecase(RuntimeStringCmp::nocase);
StringStringMap coll2(ignorecase);
fillAndPrint(coll2);
return 0;
}
void fillAndPrint(StringStringMap& coll)
{
coll["Deutschlan"]="Germany";
coll["deutsch"]="German";
coll["Haken"]="snag";
coll["arbeiten"]="work";
coll["Hund"]="dog";
coll["gehen"]="go";
coll["Unternehmen"]="enterprise";
coll["unternehmen"]="undertake";
coll["gehen"]="walk";
coll["Bestatter"]="undertaker";
StringStringMap::iterator pos;
cout.setf(ios::left,ios::adjustfield);
for(pos=coll.begin();pos!=coll.end();++pos){
cout<<setw(15)<<pos->first.c_str()<<" "
<<pos->second<<endl;
}
cout<<endl;
}