stl map键都是唯一的

来源:互联网 发布:北京谷歌seo 编辑:程序博客网 时间:2024/06/05 07:29


stl::map<unsigned int, string> Student;
//stl::map键都是唯一的,如果插入相同的key, mapObj.insert不会覆盖原来的键值,mapObj[]会覆盖键值。
// 需要不唯一的key用multimap。


//insert和pair插入
Student.insert(pair<unsigned int, string>(1, "CJY"));


//value_type插入
Student.insert(map<unsigned int, string>::value_type(3, "LL"));


map提供了两种方式,查看是否包含key,m.count(key),m.find(key)

m.count(key):由于map不包含重复的key,因此m.count(key)取值为0,或者1,表示是否包含


1 iter = m.find(key);2 if(iter!=m.end())3 {4     return iter->second;5 }6 return null;

multimap的特点为key是可以重复的,而普通map中的key是不可以重复的。  处理多个关联值

lower_bound(k) 查找第一个与键 k 关联的值,而 upper_bound(k) 是查找第一个键值比 k 大的元素。

            // 插入有相同键的多个值
dns.insert(make_pair("219.108.96.70","pythonzone.com"));
dns.insert(make_pair("219.108.96.70","python-zone.com"));
// 获得第一个值的迭代指针
CIT cit=dns.upper_bound("213.108.96.7");
// 输出: pythonzone.com,python-zone.com
while(cit!=dns.end())
{
   cout<<cit->second<<endl;
   ++cit;
}


About set

// set::begin/end#include <iostream>#include <set>int main (){  int myints[] = {75,23,65,42,13};  std::set<int> myset (myints,myints+5);  std::cout << "myset contains:";  for (std::set<int>::iterator it=myset.begin(); it!=myset.end(); ++it)    std::cout << ' ' << *it;  std::cout << '\n';  return 0;}

output: 13 23 42 65 75


Example

// multimap::equal_range#include <iostream>#include <map>int main (){  std::multimap<char,int> mymm;  mymm.insert(std::pair<char,int>('a',10));  mymm.insert(std::pair<char,int>('b',20));  mymm.insert(std::pair<char,int>('b',30));  mymm.insert(std::pair<char,int>('b',40));  mymm.insert(std::pair<char,int>('c',50));  mymm.insert(std::pair<char,int>('c',60));  mymm.insert(std::pair<char,int>('d',60));  std::cout << "mymm contains:\n";  for (char ch='a'; ch<='d'; ch++)  {    std::pair <std::multimap<char,int>::iterator, std::multimap<char,int>::iterator> ret;    ret = mymm.equal_range(ch);    std::cout << ch << " =>";    for (std::multimap<char,int>::iterator it=ret.first; it!=ret.second; ++it)      std::cout << ' ' << it->second;    std::cout << '\n';  }  return 0;}

mymm contains:a => 10b => 20 30 40c => 50 60d => 60

Return value

The function returns a pair, whose member pair::first is the lower bound of the range (the same as lower_bound), and pair::second is the upper bound (the same as upper_bound).














原创粉丝点击