.

Started by
5 comments, last by Enigma 18 years, 4 months ago
[Edited by - alex_and_his_towel on December 1, 2005 6:16:03 PM]
Advertisement
That's because you can't push anything into the vector outside of a programming block. Anything outside of main is for declarations only.

If you want to initialize your global vector, you need to either do it at the beginning of your main function, or put all your initialization code into an Init function and call that from main.
There's another way to initialize a global vector.
const char * initializers[] = { "foo", "bar", "narf" };std::vector<std::string> test_vector(initializers, initializers + sizeof(initializers)/sizeof(const char *));
Quote:Original post by alex_and_his_towel
Guess I'll have to stick the vector in the main() function and pass it to other functions. Only a few functions use it anyway.

Alex.


Well, passing the vector to other functions may turn out to be the best way, but you can still declare it globally. Just keep vector<string> testVector where it is, and just move the push_back functions into main.

Or, you can do what SiCrane said. That's usually a good idea [grin]

Edit: Looks like you beat me to my reply.
Quote:Original post by SiCrane
There's another way to initialize a global vector.
const char * initializers[] = { "foo", "bar", "narf" };std::vector<std::string> test_vector(initializers, initializers + sizeof(initializers)/sizeof(const char *));


Nice, I didn't think that could be done. I've wanted to do this a number of times. I don't think it's the best looking code but it is effective.
There's a proposal for the next revision of the C++ standard that's supposed to make code like that more palettable. Within the current version, you can also change things around to make it easier to look at.
Ex:
const char * initializers[] = { "foo", "bar", "narf" };std::vector<std::string> test_vector(initializers, initializers + 3);

Of course that hard codes the number of initializers.
I quite like MaulingMonkey's (I think they were his anyway) free function templates begin and end for situations like that:
const char * initializers[] = { "foo", "bar", "narf" };std::vector<std::string> test_vector(begin(initializers), end(initializers));

Enigma

This topic is closed to new replies.

Advertisement