Re: vector<>.erase(where) vs vector<>.erase(from, to)
On 17 Okt., 02:38, eric <e...@bakkerspees.nl> wrote:
JoshuaMaur...@gmail.com wrote:
If you could post a complete code sample, I might be better able to
help.
OK, here goes:
#include <iostream>
#include <vector>
#include <algorithm>
using std::cout;
using std::vector;
using std::remove;
template <class T>
void print(const T& t)
{
for (typename T::const_iterator it = t.begin(); it != t.end(); ++it)
cout << *it << ' ';
cout << '\n';
}
You almost have code to do the above in the standard library: use
std::copy with an ostreamiterator.
int main(int, char**)
{
int k[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
vector<int> v(k, k + 8);
print(v);
int to_be_found = 0;
vector<int>::iterator it = remove(v.begin(), v.end(), to_be_found);
if (it == v.end())
cout << to_be_found << " not found\n";
// Single iterator version of erase cannot be used if iterator
//points to end, becaue the Windows version erases the last element
//and the Linux version crashes
v.erase(it); // This exhibits undefined (?) behaviour
Yes. it is v.end(), and so does not point to an element of v.
//v.erase(it, it); // This always works
Because the range specified in erase in half-open. Therefore, nothing
is erased.
<snip>
/Peter
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]