map::insert, map::find, 和 map::end
在 Visual C++ 演示如何使用 映射:: 插入,映射:: 查找, 和 映射:: 结束 标准 (STL)模板库函数。
iterator map::end( );
iterator map::find(
const Key& Key
);
pair<iterator, bool>
map::insert(
const value_type& x
);
备注
说明 |
---|
类/参数名在原型不匹配版本在头文件。修改某些提高可读性。 |
结束 函数返回一点通过顺序的末尾的迭代器。查找 返回指定第一个元素排序关键字等号 键的迭代器。如果不存在这样的元素,迭代器等于 结束。如果注册表项不存在, 插入 将添加到该序列并返回 pairAMP_LT迭代器, trueAMP_GT。如果此键已存在, 插入 不将其添加到个序列并不返回 pair AMP_LT迭代器, 错误AMP_GT。下面的示例创建 int的映射到 字符串s。在这种情况下,映射是以数字按它们的字符串等效项 (1 个 (AMP_GT “one”, 2 位 AMP_GT “two”,等等)。程序读取用户的数字,查看单词等效项。每个数字 (使用映射) 和打印该数字为一系列运行。例如,在中,如果用户输入 25463,程序响应与:两个四个三。
示例
// map_insert_find_end.cpp
// compile with: /EHsc
#pragma warning(disable:4786)
#include <iostream>
#include <string>
#include <map>
using namespace std;
typedef map<int, string, less<int> > INT2STRING;
int main()
{
// 1. Create a map of ints to strings
INT2STRING theMap;
INT2STRING::iterator theIterator;
string theString = "";
unsigned int index;
// Fill it with the digits 0 - 9, each mapped to its string counterpart
// Note: value_type is a pair for maps...
theMap.insert(INT2STRING::value_type(0,"Zero"));
theMap.insert(INT2STRING::value_type(1,"One"));
theMap.insert(INT2STRING::value_type(2,"Two"));
theMap.insert(INT2STRING::value_type(3,"Three"));
theMap.insert(INT2STRING::value_type(4,"Four"));
theMap.insert(INT2STRING::value_type(5,"Five"));
theMap.insert(INT2STRING::value_type(6,"Six"));
theMap.insert(INT2STRING::value_type(7,"Seven"));
theMap.insert(INT2STRING::value_type(8,"Eight"));
theMap.insert(INT2STRING::value_type(9,"Nine"));
// Read a Number from the user and print it back as words
for( ; ; )
{
cout << "Enter \"q\" to quit, or enter a Number: ";
cin >> theString;
if (theString == "q")
break;
// extract each digit from the string, find its corresponding
// entry in the map (the word equivalent) and print it
for (index = 0; index < theString.length(); index++)
{
theIterator = theMap.find(theString[index] - '0');
if (theIterator != theMap.end() ) // is 0 - 9
cout << (*theIterator).second << " ";
else // some character other than 0 - 9
cout << "[err] ";
}
cout << endl;
}
}
输入
12
q
示例输出
Enter "q" to quit, or enter a Number: 12
One Two
Enter "q" to quit, or enter a Number: q
要求
**标题:**map