unordered_map的find方法
时间: 2023-12-02 21:43:14 浏览: 167
unordered_map是C++ STL中的一个关联容器,它提供了一种将键映射到值的方法。unordered_map的find方法用于在容器中查找指定键的元素,其函数形式为:unordered_map变量名.find(要查找的键值)。如果找到了指定键的元素,则返回指向该元素的迭代器;否则,返回指向unordered_map尾部的迭代器end()。下面是一个例子:
假设我们有一个unordered_map<int, string> map,其中包含以下键值对:{1: "one", 2: "two", 3: "three"}。我们可以使用find方法查找键为2的元素:
```c++
unordered_map<int, string> map = {{1, "one"}, {2, "two"}, {3, "three"}};
auto it = map.find(2);
if (it != map.end()) {
cout << "Found element with key " << it->first << " and value " << it->second << endl;
} else {
cout << "Element not found" << endl;
}
```
输出结果为:
```
Found element with key 2 and value two
```
相关问题
unordered_map find
unordered_map is a container in C++ that stores elements in an unordered manner based on a hash function. To find an element in an unordered_map, you can use the find() function. Here's an example:
```cpp
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, std::string> map = {{1, "apple"}, {2, "banana"}, {3, "orange"}};
auto it = map.find(2);
if (it != map.end()) {
std::cout << "Key found! Value is: " << it->second << std::endl;
} else {
std::cout << "Key not found! << std::endl;
}
return 0;
}
```
In this example, we create an unordered_map called `map` with integer keys and string values. We then use the find() function to search for the key 2. If the key is found, it returns an iterator pointing to the key-value pair, and we can access the value using `it->second`. If the key is not found, it returns `map.end()`.
Hope this helps! Let me know if you have any more questions.
C++ unordered_map find
unordered_map 是 C++ STL 中的一个关联容器,用于存储键值对。可以使用 find() 函数在 unordered_map 中查找指定键是否存在。如果存在,则返回指向该键值对的迭代器;否则返回 unordered_map::end()。
示例代码:
```
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
unordered_map<string, int> mymap = {{"apple", 1}, {"banana", 2}, {"orange", 3}};
auto it = mymap.find("banana");
if (it != mymap.end()) {
cout << "banana is found, value is " << it->second << endl;
} else {
cout << "banana is not found" << endl;
}
return 0;
}
```
输出结果:
```
banana is found, value is 2
```
阅读全文