将值插入列表中的向量

Insert value into vector in a list

我有一个特定的矢量列表。我想为向量添加一个值。我该怎么做?

这是我的代码:

//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");

因为您已将 it 声明为 const_iterator,所以您已将其设为无法编辑 it 引用。当您调用 push_back 时,您正试图编辑 it 指向的 vector。您需要更换:

std::list< vector<string> >::const_iterator it = adjacencylist.begin();
(*it).push_back("Some more String"); 

std::list< vector<string> >::iterator it = adjacencylist.begin();
(*it).push_back("Some more String");

阅读一般知识 constness here and there is more specific information on const_iterator here

只使用一个迭代器。您也可以使用 it -> push_back 而不是 (*it).push_back.

这是一个例子:

for (list< vector<string> > it = adjacencylist.begin(); it != adjacencylist.end(); ++it)
{
    it -> push_back("Your std::string");
}