Sign in to follow this  
alex_and_his_towel

.

Recommended Posts

pi_equals_3    517
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.

Share this post


Link to post
Share on other sites
SiCrane    11839
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 *));

Share this post


Link to post
Share on other sites
pi_equals_3    517
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.

Share this post


Link to post
Share on other sites
helix    301
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.

Share this post


Link to post
Share on other sites
SiCrane    11839
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.

Share this post


Link to post
Share on other sites
Enigma    1410
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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this