map::find
傳回參考對應中之項目 (具有相當於指定索引鍵的索引鍵) 位置的迭代器。
iterator find(const Key& key); const_iterator find(const Key& key) const;
參數
- key
要搜尋之對應中,項目之排序索引鍵所要比對的索引鍵值。
傳回值
參考具有指定索引鍵之項目位置,或找不到相符的索引鍵時,對應中 (map::end()) 接在最後一個項目後之位置的迭代器。
備註
成員函式會傳回參考對應 (其排序索引鍵相當於二進位述詞下的引數索引鍵,而該二進位述詞會根據較低的可比較關聯性引進順序) 中之項目位置的迭代器。
若將傳回值 find 指派給 const_iterator,對應物件無法修改。 若將傳回值 find 指派給 iterator,對應物件可以修改。
範例
// compile with: /EHsc /W4 /MTd
#include <map>
#include <iostream>
#include <vector>
#include <string>
#include <utility> // make_pair()
using namespace std;
template <typename A, typename B> void print_elem(const pair<A, B>& p) {
cout << "(" << p.first << ", " << p.second << ") ";
}
template <typename T> void print_collection(const T& t) {
cout << t.size() << " elements: ";
for (const auto& p : t) {
print_elem(p);
}
cout << endl;
}
template <typename C, class T> void findit(const C& c, T val) {
cout << "Trying find() on value " << val << endl;
auto result = c.find(val);
if (result != c.end()) {
cout << "Element found: "; print_elem(*result); cout << endl;
} else {
cout << "Element not found." << endl;
}
}
int main()
{
map<int, string> m1({ { 40, "Zr" }, { 45, "Rh" } });
cout << "The starting map m1 is (key, value):" << endl;
print_collection(m1);
vector<pair<int, string>> v;
v.push_back(make_pair(43, "Tc"));
v.push_back(make_pair(41, "Nb"));
v.push_back(make_pair(46, "Pd"));
v.push_back(make_pair(42, "Mo"));
v.push_back(make_pair(44, "Ru"));
v.push_back(make_pair(44, "Ru")); // attempt a duplicate
cout << "Inserting the following vector data into m1:" << endl;
print_collection(v);
m1.insert(v.begin(), v.end());
cout << "The modified map m1 is (key, value):" << endl;
print_collection(m1);
cout << endl;
findit(m1, 45);
findit(m1, 6);
}
輸出
需求
標頭:<map>
命名空間: std