问题
I'm new to C++. I was wondering how I can find duplicate strings in a vector and print out ONE copy of the string. For example, if I had <"cat", "dog", "dog", "bird",> it would print out cat, dog, bird. I have sorted my vector and am using the adjacent_find function and iterating through the vector (since I have to find if any word is duplicated). My code detects duplicates, but it only prints out the non-duplicates. I would like to alter it to print out all the non-duplicates and also just ONE of the duplicates, so all strings in the vector are printed out. Here is the code I have so far:
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
}
回答1:
You can use the STL algorithms std::unique()
or std::unique_copy()
. They work with any STL container, not just vectors.
A simple example to print the vector to the standard output:
#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, " "));
}
If you want to perform this operation in-place instead, you can use std::unique()
. It is important to keep in mind that this function does not physically remove the redundant elements, but it returns the iterator to the new logical end of the collection:
#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 << " "; });
}
回答2:
Try std::unique
, which removes all but the first element from every consecutive group of identical elements (more examples + information here). Since your vector is sorted, this sounds like what you'd like.
回答3:
If your vector is already sorted, you can use std::unique to remove consecutive duplicates.
Another alternative is to construct an std::set from the vector. That will have unique elements by design.
来源:https://stackoverflow.com/questions/14552633/c-how-to-detect-duplicates-in-vectorstring-and-print-one-copy