gpt4 book ai didi

C++ : How to detect duplicates in vector and print ONE copy?

转载 作者:太空狗 更新时间:2023-10-29 19:59:14 25 4
gpt4 key购买 nike

我是 C++ 新手。我想知道如何在 vector 中找到重复的字符串并打印出该字符串的一个拷贝。例如,如果我有 <"cat", "dog", "dog", "bird",> 它会打印出 cat, dog, bird。我已经对我的 vector 进行排序并使用 adjacent_find 函数并遍历 vector (因为我必须查找是否有重复的单词)。我的代码检测到重复项,但它只打印出非重复项。我想更改它以打印出所有非重复项以及其中一个重复项,因此 vector 中的所有字符串都被打印出来。这是我到目前为止的代码:

public: void print(vector<string> in) // print method for printing a vector and it's key
{

sort(in.begin(), in.end()); // sort the vector alphabetically first

vector<string>::iterator it;

for( it = in.begin(); it != in.end(); it++ ) // iterate through it


if(adjacent_find(in.begin(), in.end()) == in.end()) // don't print duplicates


cout << *it<<endl; // and print out each string in the vector
}

最佳答案

您可以使用 STL 算法 std::unique()std::unique_copy()。它们适用于任何 STL 容器,而不仅仅是 vector 。

将 vector 打印到标准输出的简单示例:

#include <iostream>
#include <algorithm>
#include <iterator>

using namespace std;

int main()
{
vector<string> v = { "hello", "hello", "world" };
unique_copy(begin(v), end(v), ostream_iterator<string>(cout, " "));
}

如果您想就地执行此操作,您可以使用 std::unique()。重要的是要记住,这个函数并没有物理地删除冗余元素,而是将迭代器返回到集合的新逻辑端:

#include <iostream>
#include <algorithm>
#include <iterator>

using namespace std;

int main()
{
vector<string> v = { "hello", "hello", "world" };
auto newEnd = unique(begin(v), end(v));
for_each(begin(v), newEnd, [] (string const& s) { cout << s << " "; });
}

关于C++ : How to detect duplicates in vector<string> and print ONE copy?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14552633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com