c++ 哈希表的end()
时间: 2024-06-13 11:09:16 浏览: 12
C++中,哈希表的`end()`函数返回一个迭代器,指向哈希表中最后一个元素的下一个位置。如果哈希表为空,则`end()`函数返回的迭代器等同于`begin()`函数返回的迭代器。`end()`函数的返回值可以用于遍历哈希表中的元素,通常与`begin()`函数一起使用。以下是一个简单的例子:
```c++
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> myMap = {{"apple", 1}, {"banana", 2}, {"orange", 3}};
// 遍历哈希表
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << it->first << " : " << it->second << std::endl;
}
return 0;
}
```
输出结果为:
```
orange : 3
banana : 2
apple : 1
```
相关问题
c++ 哈希表map
哈希表map是一种数据结构,用于存储键值对。在引用中提供的代码中,UnorderedMap是一个封装了哈希表实现的map结构。它使用了模板类,可以根据需求存储不同类型的键和值。UnorderedMap中的键值对以pair<K, V>的形式存储,其中K是键的类型,V是值的类型。UnorderedMap使用了HashFunc作为默认的哈希函数,用于计算键的哈希值。UnorderedMap提供了一些常用的操作,比如插入键值对、查找键、删除键等。你可以使用UnorderedMap的insert函数来插入一个键值对,使用find函数来查找一个键,使用erase函数来删除一个键。此外,UnorderedMap还提供了begin和end函数,用于遍历整个map。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [【C++】通过哈希表实现map和set](https://blog.csdn.net/weixin_61508423/article/details/128043581)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
c++哈希表查询方法
C++中哈希表的查询方法主要有以下两种:
1.使用find()函数进行查询
```c++
// 查找key所在的元素
// 找到:返回元素的迭代器。通过迭代器的first和second属性获取值
// 没找到:返回unordered_map::end
unordered_map<string, double> mymap;
string input = "mom";
unordered_map<string, double>::const_iterator got = mymap.find(input);
if(got == mymap.end())
cout << "not found";
else
cout << got->first << " is " << got->second;
```
2.使用[]运算符进行查询
```c++
// 查找key所在的元素
// 找到:返回元素的值
// 没找到:插入一个新元素,值为默认值,返回新元素的值
unordered_map<string, double> mymap;
string input = "mom";
double value = mymap[input];
if(value == 0)
cout << "not found";
else
cout << input << " is " << value;
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)