• Advertisement
Sign in to follow this  

.

This topic is 4467 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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
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
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
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
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
Sign in to follow this  

  • Advertisement