byrass byrass - 9 days ago 7
C++ Question

Initializing an array of empty vectors

I'm trying to create an array of empty string vectors, but I can't manage to initialize the vectors to be able to push values into them:

vector <string> v[500];
// vector initializing code
v[0].push_back("hello"); // should work now


Error message is:

'v' does not name a type


How should I initialize so that v[0].push_back() works?

Answer

As pointed in all the comments on your question, your error occurs because you wrote your code out of a main function. Each C++ program must have it.

By the way, here are good practices for free (found also in comments).

  • Use std::array instead of C-array if you know the size at compile-time (and I believe you do).
  • Avoid using namespace std; because it's bad.
  • Be sure that you do well all your includes : #include <string>, #include <vector> and #include <array> if using-so.
  • If you're a C++ beginner, I suggest C++ Primer, updated for C++11. If your a complete beginner, Programming: Principles and Practice Using C++.