The question is
Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.
For example:
uniqueInOrder("AAAABBBCCDAABBB") == {'A', 'B', 'C', 'D', 'A', 'B'}
uniqueInOrder("ABBCcAD") == {'A', 'B', 'C', 'c', 'A', 'D'}
uniqueInOrder([1,2,2,3,3]) == {1,2,3}
Now my solution is
template <typename T>
std::vector<T> uniqueInOrder(const std::vector<T>& iterable){
std::vector<T> unique_set;
T last = 0;
for(auto & element : iterable) {
if(element != last) {
unique_set.push_back(element);
}
last = element;
}
return unique_set;
}
std::vector<char> uniqueInOrder(const std::string& iterable){
std::vector<char> unique_set;
char last = 0;
for(auto & element : iterable) {
if(element != last) {
unique_set.push_back(element);
}
last = element;
}
return unique_set;
}
The problem is that sometimes the first element is 0. What can I assign last that will never match an input? I tried using NULL but I think that just compiled to 0 anyway.
Aucun commentaire:
Enregistrer un commentaire