本文演示如何在 Visual C++中使用map::end
标准map::iterator
map::find
map::insert
map::value_type
模板库 (STL) 符号。
原始产品版本: Visual C++
原始 KB 数: 157159
必需的标头
<map>
原型
iterator map::end();
// Key is the data type of template argument #1 for map
iterator map::find(const Key& key);
pair<iterator, bool> map::insert(const value_type& x);
注意
原型中的类/参数名称可能与头文件中的版本不匹配。 一些已修改以提高可读性。
说明
该 end()
函数返回一个迭代器,该迭代器指向序列末尾的一个。
查找返回一个迭代器,该迭代器选择其排序键等于 key
的第一个元素。 如果不存在此类元素,迭代器等于 end()
。
如果该键尚不存在, insert
则将它添加到序列并返回 pair<iterator, true>
。 如果该键已存在, insert
则不会将其添加到序列并返回 pair <iterator, false>
。
以下示例创建 ints 到字符串的映射。 在这种情况下,映射是从数字到其字符串等效项(1 - 一、> 2 -> 两等)。
程序从用户读取数字,查找每个数字(使用地图)等效的单词,并将数字打印回一系列单词。 例如,如果用户输入 25463,程序将响应: “二五四六三”。
代码示例
//////////////////////////////////////////////////////////////////////
// Compile options needed: None
// <filename> : main.cpp
// Functions:
// end
// find
// insert
// of Microsoft Product Support Services,
// Copyright (c) 1996 Microsoft Corporation. All rights reserved.
//////////////////////////////////////////////////////////////////////
// disable warning C4018: '<' : signed/unsigned mismatch
// okay to ignore
#pragma warning(disable: 4018)
#pragma warning(disable:4786)
#include <iostream>
#include <string>
#include <map>
using namespace std;
typedef map<int, string, less<int>, allocator<string> > INT2STRING;
void main()
{
// 1. Create a map of ints to strings
INT2STRING theMap;
INT2STRING::iterator theIterator;
string theString = "";
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;
}
}
程序输出:
Enter "q" to quit, or enter a Number: 22
Two Two
Enter "q" to quit, or enter a Number: 33
Three Three
Enter "q" to quit, or enter a Number: 456
Four Five Six
Enter "q" to quit, or enter a Number: q
参考
有关和map::find
访问 map::insert、map::find 和 map::end 的相同信息map::end
。map::insert