I have a std::list<int>
and a std::vector<int>
. I want to remove even elements from them, and duplicate odd element in them.
I've two different functions for both of them:
Vector:
std::vector<int> vec_remove_even_duplicate_odd(std::vector<int> target) {
std::vector<int>::iterator begin = target.begin();
while (begin != target.end()) {
if (*begin % 2 == 0) {
begin = target.erase(begin);
} else {
begin = target.insert(begin, *begin);
begin += 2;
}
}
return target;
}
This works fine. But the same function for std::list<int>
shows error at the line begin += 2
:
error: no match for ‘operator+=’ (operand types are ‘std::list<int>::iterator {aka std::_List_iterator<int>}’ and ‘int’)
If I change it to:
begin = begin + 2
it shows the following note:
note: mismatched types ‘const std::reverse_iterator<_Iterator>’ and ‘int’
But, if I change that line to:
++begin;
++begin;
It works fine for list
too. So what is it with this behaviour, that I might have missed while reading about containers.
Why is the +=
operator not defined for std::list<T>::iterator
? And why that message for simple +
operator? I haven't even created a reverse_iterator
?
I'm aware that a vector
is a contiguous structure, while a list
is not. But how will that matter, given that post-increment is applicable?
Is this issue specific to list
only, or some other container also have this issue?