您的位置:首页 > 编程语言 > C语言/C++

[C++] STL Map的简单用法

2013-11-25 12:40 274 查看
#include <cstdlib>
#include <iostream>
#include <map>

using namespace std;

int main(int argc, char *argv[])
{
// Construct
map<string, string> m1, m2;
map<string, string>::iterator iter;

// Insert
m1.insert(pair<string, string>("1", "hello"));
m1.insert(pair<string, string>("2", "world"));
m2["3"] = "test";
m2["4"] = "swap";

// Swap
swap(m1, m2);

// Traverse
for (iter = m1.begin(); iter != m1.end(); iter++)
{
cout << iter->second << endl;
}
cout << endl;

// Clear
// Check if empty
m2.clear();
if (m2.empty())
cout << "m2 is empty" << endl << endl;

// Erase
// .erase() erases all the values of certain key, has no effect if no key matches
m1.erase("3");
m1.erase("3");
m1.erase("H");

// Find certain key
// returns the corresponding iterator, returns .end() if no key matches
iter = m1.find("4");
if (iter != m1.end())
cout << iter->first << " is in m1, and the value is "
<< iter->second << endl << endl;
else
cout << "cannot find the key" << endl << endl;

// Count the number of values of certain key
cout << "m1 has " << m1.count("4") << " value(s) with the key 4" << endl << endl;

system("PAUSE");
return EXIT_SUCCESS;
}

相应输出结果:

test

swap

m2 is empty

4 is in m1, and the value is swap

m1 has 1 value(s) with the key 4

请按任意键继续. . .
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: