C++:如何检测向量中的重复项并打印一份?
Posted
技术标签:
【中文标题】C++:如何检测向量中的重复项并打印一份?【英文标题】:C++ : How to detect duplicates in vector<string> and print ONE copy? 【发布时间】:2013-01-27 21:41:48 【问题描述】:我是 C++ 新手。我想知道如何在向量中找到重复的字符串并打印出字符串的一个副本。例如,如果我有 它将打印出 cat, dog, bird。我已经对我的向量进行了排序,并且正在使用相邻查找函数并遍历向量(因为我必须查找是否有重复的单词)。我的代码检测到重复项,但它只打印出非重复项。我想更改它以打印出所有非重复项以及其中一个重复项,以便打印出向量中的所有字符串。这是我到目前为止的代码:
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
【问题讨论】:
确定你不想要一开始就不会存储欺骗的东西吗?如果没有,您可以使用std::unique_copy
将它们复制到输出。
跟进 chris 的回答,例如 std::set<>
【参考方案1】:
您可以使用 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 << " "; );
【讨论】:
如果您要使矢量在适当的位置独一无二,我会使用擦除删除成语而不是存储我自己的结束位置。 @chris:我想在这里做笼统的陈述是有风险的,这取决于你之后必须做什么样的处理。但是,是的,常识表明你更有可能想打电话给erase()
是的,我估计以后会用得更多。
非常感谢!!这正是我想要的。【参考方案2】:
试试std::unique
,它会从每组相同元素的连续组中删除除第一个元素之外的所有元素(更多示例+信息here)。由于您的矢量已排序,这听起来像是您想要的。
【讨论】:
【参考方案3】:如果您的向量已经排序,您可以使用std::unique
删除连续的重复项。
另一种选择是从向量构造一个std::set
。这将具有独特的设计元素。
【讨论】:
以上是关于C++:如何检测向量中的重复项并打印一份?的主要内容,如果未能解决你的问题,请参考以下文章
查找列表的“最佳”项并在python中打印第一个实例的索引位置[重复]