I want to get numbers from vector SrcVec, and store in a new vector DestVec,
but if the remove the duplicated numbers.
like SrvVec: 1,2,3,4,5,2,3
And the DestVec should like this: 1,2,3,4,5
How to implement this by using STL?
Thanks!
Here is what I did:
1 2 3 4 5 6 7 8
for (vector<int>::iterator it = inputNumbers.begin(); it != inputNumbers.end(); it++)
{
vector<int>::iterator it2 = find(targertNumbers.begin(), targertNumbers.end(), *it);
if (it2 == targertNumbers.end())
{
targertNumbers.push_back(*it);
}
}
Also, please wrap your code in code tags (highlight it and use the <> format button), it makes it more readable. For the record, !std::count() and std::find == vector.end() are the same, but I prefer count because it is shorter and doesn't require an entire comparison statement.
For the record, !std::count() and std::find == vector.end() are the same, but I prefer count because it is shorter and doesn't require an entire comparison statement.
The disadvantage of using std::count is that it always has to search the whole vector.
#include <iostream>
#include <vector>
#include <unordered_set>
int main()
{
const std::vector<int> srce { 1, 4, 1, 3, 5, 4, 2, 3, 1, 2, 3 } ;
std::vector<int> dest ;
{
// retain the order of non-duplicated elements: try inserting each number in srce into a set
// if successful (the number was not seen earlier) append it to dest
std::unordered_set<int> set ;
for( int v : srce ) if( set.insert(v).second ) dest.push_back(v) ;
}
for( int v : dest ) std::cout << v << ' ' ;
std::cout << '\n' ;
}
There are other ways, such as using an std::set or various other, fairly large functions, but I'd say they're overkill, though if you want to look into them, just google c++ remove duplicates from vector, there are a lot of posts on forums like stack overflow about it. And as Peter87 said, while count and find have approximately the same performance when the object you're looking for doesn't exist, find is faster when it does, so I'd stick to using find, although there's no need to create an iterator to store the result and then check it, rather than just checking the result in the if statement itself.
> while count and find have approximately the same performance
> when the object you're looking for doesn't exist, find is faster when it does
I got curious about this, and got interesting results: while both take quadratic time, std::count may be faster than std::find for this (because of loop vectorisation?)
Hi JLBorges,
You modify [&, targetNumbers](int i) to [&](int i),then the lambda expression can use targetNumbers freely.
And you still add const before const std::vector<int>& inputNumbers.
Then what's the difference between [&, targetNumbers](int i) and [&](int i),
Does [&, targetNumbers](int i) pass targetNumbers like const targetNumbers ?
I am confused about this.
Thanks!