remo
remo

Reputation: 898

how can I initialize a vector of lists in C++?

I want to initialize a vector of list<int> . I used fill function, but my compiler shows error. Please help me in this direction.

std::vector<std::list<int>> neighbors(NRecords);
std::fill(neighbors.begin,neighbors.end,&std::vector<int>(NNeighbors)); // ERROR

ERROR: Error 2 error C3867: 'std::vector<_Ty>::begin': function call missing argument list; use '&std::vector<_Ty>::begin' to create a pointer to member ...

Upvotes: 2

Views: 24680

Answers (4)

Thomas Frederics
Thomas Frederics

Reputation: 1

If I read your code correctly you simply want to declare a vector of lists. I have gotten this to work in my main file but can not figure out how to do so as a private member of a class.....

vector< list < string >> hashTable(1373);

Upvotes: 0

Qaz
Qaz

Reputation: 61950

From what I can deduce from the code, it seems you simply want this:

std::vector<std::list<int>> neighbors(NRecords, std::list<int>(NNeighbors));

This uses a constructor (#2 in link) that is similar to the following:

vector(size_type count, value_type value);

In the above call, NRecords is the number of elements the vector will contain and the second argument, a list that is initialized the same way (it starts with NNeighbors as its size) is used for the value of each of the vector's elements. This saves having to create the vector with the size and then fill it separately.

For completeness, you have a couple things wrong with your std::fill call:

  • First off, begin and end are functions, so you need parentheses (begin()).
  • Secondly, you're filling it with std::vectors when you specified earlier that it contains std::lists.
  • Next, you're passing a pointer to the value instead of the value itself.
  • Finally, you're taking the address of a temporary container you create on the fly in there, which is not allowed. You shouldn't be taking the address in the first place, though.

Corrected, it can be written as:

std::fill(neighbours.begin(), neighbours.end(), std::list<int>(NNeighbors));

Upvotes: 5

P0W
P0W

Reputation: 47814

Use std::vector's constructor as per Chris's post

or else:

std::fill(neighbors.begin(),neighbors.end(),std::list<int>(NNeighbors));

Upvotes: 1

fatihk
fatihk

Reputation: 7919

neighbors.begin should be neighbors.begin()

neighbors.end should be neighbors.end()

std::fill(neighbors.begin(),neighbors.end(),std::list<int>(NNeighbors)); 

Upvotes: 2

Related Questions