本文說明如何在 Visual C++中使用 map::end、 map::find、 map::insert、 map::iterator和 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() 傳回反覆運算器,指向序列結尾的一個。
Find 會傳回反覆運算器,其選擇排序索引鍵等於 key的第一個專案。 如果不存在這類項目,反覆運算器會 end()等於 。
如果索引鍵尚未存在, insert 則會將它新增至序列並傳回 pair<iterator, true>。 如果索引鍵已經存在, insert 則不會將它新增至序列,並傳 pair <iterator, false>回 。
下列範例會建立 int 到字串的對應。 在此情況下,對應會從數位到其字串對等專案 (1 -> One、 2 -> Two 等等)。
程式會從使用者讀取數位、尋找每個數位相等的字組(使用地圖),並將數位列印回一系列單字。 例如,如果使用者輸入 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::end相同資訊,請流覽 map::insert、map::find 和 map::end。map::insertmap::find