mister
mister

Reputation: 3433

Multi-dimensional Vector Pointer

I have the following multi-dimensional vector

int main()
{
    vector< vector<string> > tempVec;

    someFunction(&tempVec);
}

void someFunction(vector< vector<string> > *temp)
{
    //this does not work
    temp[0]->push_back("hello");
}

How do i push data into the vector when i have a vector pointer? The below code does not work.

    temp[0]->push_back("hello");

Upvotes: 0

Views: 1531

Answers (1)

Fred Foo
Fred Foo

Reputation: 363507

You need

(*temp)[0].push_back("hello")

That's:

  • dereference temp to get a vector<vector<string> > &
  • get first element, a vector<string> &
  • use . instead of -> because you're no longer handling pointers

That said, it would be easier if someFunction took a vector< vector<string> >& instead of a pointer: temp[0].push_back("hello"). References do not allow pointer arithmetic or null pointers, so they make it harder to screw up and are more suggestive of the actual kind of input required (a single vector, not an optional one or an array of them).

Upvotes: 1

Related Questions