std::vector > v.erase(&v[1]);未找到

std::vector > v.erase(&v[1]); not found

要从向量中删除元素,我们可以使用

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

我在本站的一些帖子中也发现了如下一句话(SO)(例如this)。

v.erase(&v[1]); 

但是,当我尝试使用第二句时,编译器提示“错误:没有匹配的函数用于调用 std::vector)...

http://ideone.com/UZJaEK

第2句是否只能在某些有限的环境下使用?

cplusplus.com 开始,vector::erase 没有这样的重载。

也许您正在寻找 std::remove

引用:

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.

erase() 采用迭代器,而不是指针。

对于std::vector,碰巧指针是实现其迭代器的有效方式,因此第二种形式可能会在使用指针作为迭代器的实现中编译。当然,这样的用途是完全不可移植的。

现代实现通常为迭代器使用单独的类型,在这种情况下,第二个版本将无法编译。使用单独的类型允许更好的错误检查,无论是在编译时(例如,捕获 std::string 的迭代器和 std::vector<char> 的意外混淆),还是在 运行 时间(用于调试模式)。