initalizing vectors

J

Joe Laughlin

Is there any way to initialize a vector with a bunch of values at once,
instead of doing a bunch of push_back()'s?

Thanks,
Joe
 
V

Victor Bazarov

Joe Laughlin said:
Is there any way to initialize a vector with a bunch of values at once,
instead of doing a bunch of push_back()'s?

Yes, if you don't mind having those values in an array:

int array[] = { 1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6 };
std::vector<int> vi(array, array + (sizeof array / sizeof array[0]));

V
 
G

Gianni Mariani

Joe said:
Is there any way to initialize a vector with a bunch of values at once,
instead of doing a bunch of push_back()'s?

template<typename T, unsigned N>
std::vector<T> Initialize( const T (&i_v)[N] )
{
return std::vector<T>( &(i_v[0]), &(i_v[N]) );
}

int foo()
{
float a[] = { 1.2, 2.3 };

std::vector<float> v = Initialize( a );
}

- or look at :

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

G
 
S

Siemel Naran

Joe Laughlin said:
Is there any way to initialize a vector with a bunch of values at once,
instead of doing a bunch of push_back()'s?

If you want to initialize all elements to the same value:

vector<int> v(10, -1);

Other posts talk about initializing from an array, also very useful.
 

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,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top