Vector Initialization Syntax

C

cppaddict

Is it possible to avoid using push_back repeatedly when initializing a
vector? That is, is there a vector syntax that would be analogous to
the following array initialization syntax:

MyClass myArray[] = {
MyClass("Stan"),
MyClass("Julie")
};

Thanks for any ideas,
cpp
 
V

Victor Bazarov

cppaddict said:
Is it possible to avoid using push_back repeatedly when initializing a
vector? That is, is there a vector syntax that would be analogous to
the following array initialization syntax:

MyClass myArray[] = {
MyClass("Stan"),
MyClass("Julie")
};

No. But you should be able to declare an array of pointers to char
and then create your vector from it, like this:

char const* theNames[] = { "Stan", "Julie" };
std::vector<MyClass> myVector(theNames, theNames + 2);

(assuming your 'MyClass' class has a constructor that accepts a pointer
to const char)

If your MyClass requires a 'string' to be passed to the c-tor, you need
to construct an array of strings, and then your vector from it.

Victor
 
H

Howard Hinnant

cppaddict said:
Is it possible to avoid using push_back repeatedly when initializing a
vector? That is, is there a vector syntax that would be analogous to
the following array initialization syntax:

MyClass myArray[] = {
MyClass("Stan"),
MyClass("Julie")
};

Thanks for any ideas,
cpp

You can get somewhat close with:

MyClass myArray[] = {
MyClass("Stan"),
MyClass("Julie")
};
std::vector<MyClass> v(myArray,
myArray+sizeof(myArray)/sizeof(myArray[0]));

which unfortunately involves an extra copy of the data. There is
discussion of a language supported superior alternative on the committee
for C++0X, but no firm proposals I'm aware of (so it isn't even close to
a sure thing).

-Howard
 
G

Gianni Mariani

cppaddict said:
Is it possible to avoid using push_back repeatedly when initializing a
vector? That is, is there a vector syntax that would be analogous to
the following array initialization syntax:

MyClass myArray[] = {
MyClass("Stan"),
MyClass("Julie")
};

Thanks for any ideas,
cpp

Leor Zolman's initialization library might be useful !

http://www.bdsoft.com/tools/initutil.html
 
A

Alex Vinokur

cppaddict said:
Is it possible to avoid using push_back repeatedly when initializing a
vector? That is, is there a vector syntax that would be analogous to
the following array initialization syntax:

MyClass myArray[] = {
MyClass("Stan"),
MyClass("Julie")
};
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,775
Messages
2,569,601
Members
45,182
Latest member
BettinaPol

Latest Threads

Top