C++ 程序在 STL 中实现映射
映射是一个关联容器,以映射方式存储元素。每个元素都有键值和映射的值。没有两个映射值可以具有相同的键值。
这里使用的函数
m::find() – 如果发现,则返回映射中键值为“b”的元素的迭代器;否则,返回迭代器以结束。
m::erase() – 从映射中删除键值。
m:: equal_range() – 返回对的迭代器。该对引用包含容器中所有与键等效的元素的范围的边界。
m insert() – 在映射容器中插入元素。
m size() – 返回映射容器中的元素数量。
m count() – 返回映射中键值为“a”或“f”的元素的匹配数。
示例代码
#include<iostream> #include <map> #include <string> using namespace std; int main () { map<char, int> m; map<char, int>::iterator it; m.insert (pair<char, int>('a', 10)); m.insert (pair<char, int>('b', 20)); m.insert (pair<char, int>('c', 30)); m.insert (pair<char, int>('d', 40)); cout<<"Size of the map: "<< m.size() <<endl; cout << "map contains:\n"; for (it = m.begin(); it != m.end(); ++it) cout << (*it).first << " => " << (*it).second << '\n'; for (char c = 'a'; c <= 'd'; c++) { cout << "There are " << m.count(c) << " element(s) with key " << c << ":"; map<char, int>::iterator it; for (it = m.equal_range(c).first; it != m.equal_range(c).second; ++it) cout << ' ' << (*it).second; cout << endl; } if (m.count('a')) cout << "The key a is present\n"; else cout << "The key a is not present\n"; if (m.count('f')) cout << "The key f is present\n"; else cout << "The key f is not present\n"; it = m.find('b'); m.erase (it); cout<<"Size of the map: "<<m.size()<<endl; cout << "map contains:\n"; for (it = m.begin(); it != m.end(); ++it) cout << (*it).first << " => " << (*it).second << '\n'; return 0; }
输出
Size of the map: 4 map contains: a => 10 b => 20 c => 30 d => 40 There are 1 element(s) with key a: 10 There are 1 element(s) with key b: 20 There are 1 element(s) with key c: 30 There are 1 element(s) with key d: 40 The key a is present The key f is not present Size of the map: 3 map contains: a => 10 c => 30 d => 40
广告