C++ : 如何检测矢量中的重复项<string>并打印一份副本?

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

本文关键字:gt string lt 副本 一份 打印 检测 何检测 C++      更新时间:2023-10-16

我是C++新手。我想知道如何在矢量中找到重复的字符串并打印出字符串的一个副本。例如,如果我有<"猫","狗","狗","鸟",>它会打印出猫,狗,鸟。我已经对我的向量进行了排序,并且正在使用 adjacent_find 函数并遍历向量(因为我必须找到是否有任何单词重复)。我的代码检测到重复项,但它只打印出非重复项。我想更改它以打印出所有非重复项,也只打印出其中一个重复项,因此打印出矢量中的所有字符串。这是我到目前为止的代码:

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 容器,而不仅仅是向量。

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

#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 << " "; });
}

尝试 std::unique ,这会从每个连续的相同元素组中删除除第一个元素之外的所有元素(更多示例 + 信息在这里)。由于您的向量已排序,这听起来像您想要的。

如果向量已排序,则可以使用 std::unique 删除连续的重复项。

另一种选择是从向量构造std::set。这将在设计上具有独特的元素。