与 const std::string 的向量关联的编译失败
Compilation failure associated with vector of const std::string
请有人解释为什么以下代码不能使用 clang 3.5 编译。
报错是'No viable overloaded '='in algorithm.'
std::vector<const std::string> m_messages;
std::vector<const std::string>::iterator iter;
...
if (iter != m_messages.end())
{
m_messages.erase(iter); // compilation error
}
如果我将 m_messages
声明为:std::vector<std::string> m_messages;
则编译正常。
还有,有什么区别:
std::vector<const std::string> m_messages;
和
std::vector<std::string> m_messages;
TIA。
要擦除元素,必须重新定位右侧元素(向左移动)。
由于您的字符串是 const
,旧元素无法被覆盖(通过 =
运算符)因此出现错误。
这是否意味着如果可以删除元素,则拥有 const 字符串向量没有意义? Yes at least what the standard says
23.3.7.5 矢量修饰符[vector.modifiers]
iterator erase(const_iterator position); iterator erase(const_iterator
first, const_iterator last);
Effects: Invalidates iterators and references at or after the point of the erase.
Complexity: The destructor of T is called the number of times equal to the number of the elements erased, but the move assignment operator of T is called the number of times equal to the number of elements in the vector after the erased elements.
Throws: Nothing unless an exception is thrown by the copy constructor, move constructor, assignment operator, or move assignment operator of T.
请有人解释为什么以下代码不能使用 clang 3.5 编译。
报错是'No viable overloaded '='in algorithm.'
std::vector<const std::string> m_messages;
std::vector<const std::string>::iterator iter;
...
if (iter != m_messages.end())
{
m_messages.erase(iter); // compilation error
}
如果我将 m_messages
声明为:std::vector<std::string> m_messages;
则编译正常。
还有,有什么区别:
std::vector<const std::string> m_messages;
和
std::vector<std::string> m_messages;
TIA。
要擦除元素,必须重新定位右侧元素(向左移动)。
由于您的字符串是 const
,旧元素无法被覆盖(通过 =
运算符)因此出现错误。
这是否意味着如果可以删除元素,则拥有 const 字符串向量没有意义? Yes at least what the standard says
23.3.7.5 矢量修饰符[vector.modifiers]
iterator erase(const_iterator position); iterator erase(const_iterator first, const_iterator last);
Effects: Invalidates iterators and references at or after the point of the erase.
Complexity: The destructor of T is called the number of times equal to the number of the elements erased, but the move assignment operator of T is called the number of times equal to the number of elements in the vector after the erased elements.
Throws: Nothing unless an exception is thrown by the copy constructor, move constructor, assignment operator, or move assignment operator of T.