-1

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?

15
  • What isn't working for you at the moment? Your current problem description is unclear. EDIT: Your code works as is. Demo: here. Commented Nov 29, 2016 at 15:19
  • 1
    Or better, if size is known at compime-time : std::array<std::vector<string>, 500> v; Commented Nov 29, 2016 at 15:22
  • 2
    Also, while you're at it, remove that using namespace std;. It's a horribly bad practice. Commented Nov 29, 2016 at 15:27
  • 1
    @byrass is v[0].push_back("hello"); written inside a main function? Commented Nov 29, 2016 at 15:27
  • 2
    @byrass So, that's your problem. You cannot have executable code outside of functions. If you are having these sorts of problems, I suggest you read a book on C++. Commented Nov 29, 2016 at 15:31

1 Answer 1

1

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++.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.