Know your Standard Library
#Know your Standard Library
TheThe standard unique
algorithm performs exactly this task (and is available in C++03). If we take the argument by value, we can modify it in place, and use the erase-remove idiom:
#include <algorithm>
#include <vector>
template<class T>
std::vector<T> remove_duplicate(std::vector<T> vec) {
vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
return vec;
}
Note that the result vector has the same capacity as the input vector. If this is likely to be a problem, then std::unique_copy()
could be used to copy values into a new vector, or a move to C++11 would gain the shrink_to_fit()
method on your vector.
#Know your Standard Library
The standard unique
algorithm performs exactly this task (and is available in C++03). If we take the argument by value, we can modify it in place, and use the erase-remove idiom:
#include <algorithm>
#include <vector>
template<class T>
std::vector<T> remove_duplicate(std::vector<T> vec) {
vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
return vec;
}
Note that the result vector has the same capacity as the input vector. If this is likely to be a problem, then std::unique_copy()
could be used to copy values into a new vector, or a move to C++11 would gain the shrink_to_fit()
method on your vector.
Know your Standard Library
The standard unique
algorithm performs exactly this task (and is available in C++03). If we take the argument by value, we can modify it in place, and use the erase-remove idiom:
#include <algorithm>
#include <vector>
template<class T>
std::vector<T> remove_duplicate(std::vector<T> vec) {
vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
return vec;
}
Note that the result vector has the same capacity as the input vector. If this is likely to be a problem, then std::unique_copy()
could be used to copy values into a new vector, or a move to C++11 would gain the shrink_to_fit()
method on your vector.
#Know your Standard Library
The standard unique
algorithm performs exactly this task (and is available in C++03). If we take the argument by value, we can modify it in place, and use the erase-remove idiom:
#include <algorithm>
#include <vector>
template<class T>
std::vector<T> remove_duplicate(std::vector<T> vec) {
vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
return vec;
}
Note that the result vector has the same capacity as the input vector. If this is likely to be a problem, then std::unique_copy()
could be used to copy values into a new vector, or a move to C++11 would gain the shrink_to_fit()
method on your vector.