Search code examples
c++stringvectorcstring

Traversing nested vectors of strings


There's an issue in my code with nested vectors of strings. It is not printing the strings.

void foo(vector<vector<char const *> > const & vcp){
   vector<vector<char const *> >::const_iterator i(vcp.begin());
   vector<vector<char const *> >::const_iterator e(vcp.end());

   for(; i != e; ++i){
      vector<char const *>::const_iterator ci(i->begin());
      vector<char const *>::const_iterator ce(i->end());
      for(; ci != ce; ++ci) 
         cout<<*ci<<endl; //Not printing
   } 
}

int main(){
  std::vector<vector<char const *> > vvcp(3);
  std::vector<char const *> vcp(3);
  vcp.push_back(string("abcd").c_str());
  vcp.push_back(string("efgh").c_str());
  vcp.push_back(string("ijkl").c_str());

  vvcp.push_back(vcp);
  vvcp.push_back(vcp);
  foo(vvcp);
  return EXIT_SUCCESS;
}

Solution

  • This has nothing to do with the vectors.

    You are creating temporary std::string objects, getting pointers to their underlying data, and trying to use those pointers after the strings no longer exist. That is not allowed.

    (Also, feeding '*x' to std::cout, where 'x' is a char const*, would print only the first character of the C-string.)

    Just store the strings in the vectors. That's how you're meant to use them. .c_str() really only exists so you can work with legacy C code.