unordered_map 实现字符串查重
时间: 2024-01-29 15:10:33 浏览: 22
unordered_map可以用来实现字符串的查重功能。下面是一个示例代码:
```cpp
#include <iostream>
#include <unordered_map>
#include <string>
int main() {
std::unordered_map<std::string, int> countMap;
std::string str = "abcaabbc";
// 统计字符串中每个字符出现的次数
for (char c : str) {
countMap[c]++;
}
// 输出重复字符及其出现次数
for (auto pair : countMap) {
if (pair.second > 1) {
std::cout << "Character '" << pair.first << "' appears " << pair.second << " times." << std::endl;
}
}
return 0;
}
```
运行以上代码,输出结果为:
```
Character 'a' appears 3 times.
Character 'b' appears 3 times.
```
相关问题
unordered_map 实现字符串数组查重
unordered_map可以用于实现字符串数组的查重。下面是一个示例代码:
```cpp
#include <iostream>
#include <unordered_map>
#include <vector>
#include <string>
int main() {
std::vector<std::string> strVec = {"apple", "banana", "orange", "apple", "grape", "banana"};
std::unordered_map<std::string, int> hashMap;
int n = 1;
for (const std::string& str : strVec) {
auto it = hashMap.find(str);
if (it != hashMap.end()) {
std::cout << str << "是第" << it->second << "个重复的数据" << std::endl;
++(it->second);
} else {
hashMap[str] = n;
++n;
}
}
return 0;
}
```
这段代码首先定义了一个字符串数组`strVec`,其中包含了一些重复的字符串。然后,创建了一个`unordered_map`对象`hashMap`,用于记录字符串的重复次数。接下来,遍历字符串数组,对于每个字符串,通过在`hashMap`中查找是否存在该字符串的键,如果存在,则输出该字符串是第几个重复的数据,并更新重复次数;如果不存在,则将该字符串作为键插入到`hashMap`中,并将重复次数初始化为1。
运行以上代码,输出结果如下:
```
apple是第1个重复的数据
banana是第1个重复的数据
```
unordered_map实现
好的,我知道了。unordered_map是C++ STL中的一个关联容器,用于存储键值对。它的实现基于哈希表,可以实现快速的查找、插入和删除操作。
在unordered_map中,每个键值对被称为一个元素,其中键是唯一的,值可以重复。元素的插入顺序与元素在容器中的位置无关。
unordered_map的使用方法与其他STL容器类似,可以通过insert()、erase()、find()等函数来操作元素。同时,也可以使用迭代器来遍历容器中的元素。
下面是一个简单的unordered_map示例:
```c++
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> myMap;
myMap.insert({"apple", 3});
myMap.insert({"banana", 2});
myMap.insert({"orange", 4});
std::cout << "The value of apple is " << myMap["apple"] << std::endl;
auto it = myMap.find("banana");
if (it != myMap.end()) {
std::cout << "The value of banana is " << it->second << std::endl;
}
return 0;
}
```
输出结果为:
```
The value of apple is 3
The value of banana is 2
```