-1

To remove an elements from a vector, we can use

v.erase(v.begin() + 1); // remove 2nd 

Also I found a sentence as follows in some posts on this site (SO) (e.g this).

v.erase(&v[1]); 

However, when I try to use the 2nd sentence, the compiler says "error: no matching function for call to std::vector)...

http://ideone.com/UZJaEK

Is the 2nd sentence usable only on some limited environment?

Community
  • 1
  • 1
sevenOfNine
  • 1,509
  • 16
  • 37
  • 1
    `erase()` takes an iterator. `v.erase(&v[1]);` isn't valid unless the vector's iterator happens to be a pointer. Where did you find it? – T.C. Mar 03 '15 at 01:17
  • 1
    The actual question is probably: why is pointer to element not implicitly converted to iterator to element here? – Emil Laine Mar 03 '15 at 01:19
  • @zenith Catching misuses of this sort is reason enough, IMO. – T.C. Mar 03 '15 at 01:21
  • @T.C. I found it at http://stackoverflow.com/questions/875103/how-to-erase-element-from-stdvector-by-index – sevenOfNine Mar 03 '15 at 01:47

2 Answers2

5

erase() takes an iterator, not a pointer.

For std::vector, it happens that a pointer is a valid way to implement its iterator, so the second form may compile in an implementation that uses a pointer as the iterator. Such uses would be utterly unportable, of course.

Modern implementations usually use a separate type for iterators, in which case the second version will not compile. Using a separate type permits better error-checking, both at compile time (e.g., catching an accidental mix-up of a std::string's iterator and a std::vector<char>'s), and at run time (for debug mode).

T.C.
  • 133,968
  • 17
  • 288
  • 421
  • FWIW, there's a ton of code out there written with Visual Studio 6.0 that uses the pointer instead of the iterator. – PaulMcKenzie Mar 03 '15 at 01:35
0

From cplusplus.com, there is no such overload for vector::erase.

Perhaps, you were looking for std::remove instead.

Quoted :

Transforms the range [first,last) into a range with all the elements that compare equal to val removed, and returns an iterator to the new end of that range.

Telokis
  • 3,399
  • 14
  • 36