【发布时间】:2015-07-09 07:58:21
【问题描述】:
我有一个带有向量的特定列表。我想为向量添加一个值。我该怎么做?
这是我的代码:
//creating the list with vectors
std::list< vector<string> > adjacencylist;
//adding some vectors to the list...
adjacencylist.push_back(std::vector<std::string>(1, "String"));
adjacencylist.push_back(std::vector<std::string>(1, "String"));
adjacencylist.push_back(std::vector<std::string>(1, "String"));
现在我想向列表中的向量添加值... 我为此尝试过:
std::list< vector<string> >::const_iterator it = adjacencylist.begin();
(*it).push_back("Some more String");
我认为这会奏效。所以我可以遍历所有向量并插入我想要的值。但它不起作用。这里是编译器的输出:
example.cpp: In function ‘int main(int, char**)’:
example.cpp:148:31: error: passing ‘const std::vector<std::basic_string<char> >’ as ‘this’ argument of ‘void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::basic_string<char>; _Alloc = std::allocator<std::basic_string<char> >; std::vector<_Tp, _Alloc>::value_type = std::basic_string<char>]’ discards qualifiers [-fpermissive]
(*it).push_back("test");
【问题讨论】:
-
改用
push_back。 -
它被称为
push_back。 -
push_back 也不起作用:
example.cpp:147:50: error: passing ‘const std::vector<std::basic_string<char> >’ as ‘this’ argument of ‘void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::basic_string<char>; _Alloc = std::allocator<std::basic_string<char> >; std::vector<_Tp, _Alloc>::value_type = std::basic_string<char>]’ discards qualifiers [-fpermissive] (*it).push_back("test"); -
使用
iterator,而不是const_iterator。 -
@beta 谢谢!这解决了问题