Can I assign safely an array to vector?

R

Ram Laxman

Hi all,
Can I assign an array to a vector if both(array and vector)
holds same data type?
 
J

Jeff Schwab

Ram said:
Hi all,
Can I assign an array to a vector if both(array and vector)
holds same data type?

Yes, but maybe not using the syntax you expect.


#include <vector>

int main( )
{
std::vector<int> vector;
int array[ ] = { 1, 2, 3 };

vector.assign( array, array + 3 );
}
 
T

Thomas Tutone

Jeff Schwab said:
Ram said:
Hi all,
Can I assign an array to a vector if both(array and vector)
holds same data type?

Yes, but maybe not using the syntax you expect.


#include <vector>

int main( )
{
std::vector<int> vector;
int array[ ] = { 1, 2, 3 };

vector.assign( array, array + 3 );
}

Or just:

#include <vector>

int main()
{
int array[] = { 1, 2, 3 };
std::vector<int> vec(array, array + sizeof(array));
}

Best regards,

Tom
 
K

Kevin Goodsell

Thomas said:
Or just:

#include <vector>

int main()
{
int array[] = { 1, 2, 3 };
std::vector<int> vec(array, array + sizeof(array));

This will probably not work correctly. You wanted the number of elements
in the array, not the number of bytes used to store the array.

int array[] = { 1, 2, 3 };
int size = sizeof array / sizeof *array;
std::vector<int> vec(array, array + size);

-Kevin
 
J

Jeff Schwab

Thomas said:
Jeff Schwab said:
Ram said:
Hi all,
Can I assign an array to a vector if both(array and vector)
holds same data type?

Yes, but maybe not using the syntax you expect.


#include <vector>

int main( )
{
std::vector<int> vector;
int array[ ] = { 1, 2, 3 };

vector.assign( array, array + 3 );
}


Or just:

#include <vector>

int main()
{
int array[] = { 1, 2, 3 };
std::vector<int> vec(array, array + sizeof(array));
}

That's not assignment, it's initialization.
 
T

Thomas Tutone

Kevin Goodsell said:
#include <vector>

int main()
{
int array[] = { 1, 2, 3 };
std::vector<int> vec(array, array + sizeof(array));

This will probably not work correctly. You wanted the number of elements
in the array, not the number of bytes used to store the array.

Oops. Absolutely right.

Best regards,

Tom
 

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
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top