C++ 删除vector<string>容器中重复的字符串
时间: 2023-12-16 13:04:59 浏览: 36
可以使用STL算法库中的`std::unique`函数来删除vector<string>容器中的重复元素。
具体步骤如下:
1. 首先对vector容器进行排序,以便后续去重操作。
2. 然后使用`std::unique`函数对容器进行去重操作,并返回去重后的尾部迭代器。
3. 最后使用vector容器的`erase`函数将去重后的元素从容器中删除。
下面是示例代码:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<string> vec{"hello", "world", "hello", "cpp", "world"};
sort(vec.begin(), vec.end()); // 对vector容器进行排序
auto end_unique = unique(vec.begin(), vec.end()); // 去重操作,并返回去重后的尾部迭代器
vec.erase(end_unique, vec.end()); // 删除重复的元素
for(auto& str : vec)
cout << str << " ";
cout << endl;
return 0;
}
```
输出结果为:`cpp hello world`
相关问题
C++ 统计vector<string>a容器中某个字符串出现的次数
可以使用STL中的`count`函数来统计某个字符串在vector中出现的次数。示例如下:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<std::string> a = {"hello", "world", "hello", "world", "welcome", "hello"};
std::string target = "hello";
int count = std::count(a.begin(), a.end(), target);
std::cout << "The count of " << target << " is " << count << std::endl;
return 0;
}
```
输出结果为:
```
The count of hello is 3
```
其中,`count`函数的第一个参数是容器的起始迭代器,第二个参数是容器的结束迭代器,第三个参数是要统计的字符串。`count`函数返回的是统计结果。
C++ 查找vector<string>中的数组
如果你想在 `vector<string>` 中查找一个特定的字符串,可以使用 `std::find` 算法。以下是一个示例代码,它在 `vector<string>` 中查找字符串 `"hello"`:
```C++
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<std::string> vec = { "hello", "world", "foo", "bar" };
auto it = std::find(vec.begin(), vec.end(), "hello");
if (it != vec.end())
{
std::cout << "Found string: " << *it << std::endl;
}
else
{
std::cout << "String not found" << std::endl;
}
return 0;
}
```
如果你想查找多个字符串,可以使用循环来反复调用 `std::find`。如果你想查找符合某些特定条件的字符串,可以使用 `std::find_if` 算法。