繁体   English   中英

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

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

我是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 这将具有独特的设计元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM