源自: http://support.microsoft.com/kb/157159/zh-cn
如何在 Visual C++ 中使用的 map::end、 map::find、 map::insert、 map::iterator 和 map::value_type 標準模板庫 (STL) 函數
本頁
概要
更多信息
所需的頭文件
<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 返回一個迭代器,指定的排序關鍵字的第一個元素等於鍵。如果沒有這樣的元素存在,則迭代器等於 end()。
如果該項不存在,插入將添加到序列並返回對 < 迭代器,真 >。如果此鍵已存在,則插入不會添加到序列中的並返回對 < 迭代器,假 >。
下面的示例創建一個映射的爲字符串的整數。在這種情況下,該映射是從數字爲對應的字符串 (1->"One",2 >"2",等等。)。
程序讀取用戶的數量、 查找單詞等效的 (使用地圖),每一位並打印爲詞的一系列數字的背後。例如,如果用戶輸入 25463,該程序使用響應: 兩個五四個六三。
示例代碼
////////////////////////////////////////////////////////////////////// // // Compile options needed: None // // <filename> : main.cpp // // Functions: // // end // find // insert // // Written by Rick Troemel // 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::find 和 map::insert 相同的信息,請訪問下面的 MSDN Web 站點:
http://msdn.microsoft.com/en-us/library/wwcahb6y.aspx