-1

I have a specific list with vectors. i want to add a value to a vector. How can I do this?

Here is my code:

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

Now I want to add values to the vectors in the list... I tried for this:

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

I thought that this would work. So I could iterate over all vectors and insert the values that I want. But it does not work. Here the output of the compiler:

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");
Shibumi
  • 635
  • 6
  • 17
  • 1
    Try `push_back` instead. – phantom Apr 29 '15 at 20:22
  • It is called `push_back`. – juanchopanza Apr 29 '15 at 20:23
  • push_back does not work too: `example.cpp:147:50: error: passing ‘const std::vector >’ as ‘this’ argument of ‘void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::basic_string; _Alloc = std::allocator >; std::vector<_Tp, _Alloc>::value_type = std::basic_string]’ discards qualifiers [-fpermissive] (*it).push_back("test"); ` – Shibumi Apr 29 '15 at 20:24
  • 1
    Use an `iterator`, not a `const_iterator`. – Beta Apr 29 '15 at 20:28
  • If one of the questions bellow were useful to you, please remember to mark them as answer. – Dzyann Apr 30 '15 at 13:32

2 Answers2

4

Because you have declared it as a const_iterator you have made it such that what it references cannot be edited. When you call push_back you are attempting to edit the vector that it points to. You need to replace:

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

with

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

Read up on general constness here and there is more specific information on const_iterator here.

Community
  • 1
  • 1
Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175
0

Use simply an iterator. Also you can use it -> push_back instead of (*it).push_back.

This is an example:

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