Vector Elements

B

Brett Irving

Hi people, was curious if there was a way to change all the elements
in a vector without having to loop through and access every one and
then change them.

for example. I have a vector that is 10 000 elements, and one value
that I want to copy them all to. Can I do it without looping?

Any advice is appreciated.
 
J

John Harrison

Brett Irving said:
Hi people, was curious if there was a way to change all the elements
in a vector without having to loop through and access every one and
then change them.

for example. I have a vector that is 10 000 elements, and one value
that I want to copy them all to. Can I do it without looping?

Any advice is appreciated.

Of course

vec.assign(vec.size( ), some_value);

Suggest you familiarise yourself with some standard library documentation.
This site is good, http://www.dinkumware.com/refxcpp.html

john
 
R

Ron Natalie

Brett said:
Hi people, was curious if there was a way to change all the elements
in a vector without having to loop through and access every one and
then change them.
erase them all and the resize them with the new value as fill. There
is an oft-forgotten defaulted argument to the vector constructor and
resize function that specifies what the

vector<int> foo(10000); // 10000 elements of zero.
foo.clear();
foo.resize(10000, 5); // 10000 elements of 5;

Of course, the other way is to use fill
fill(foo.begin(), foo.end(), 5);
 
C

Catalin Pitis

Ron Natalie said:
erase them all and the resize them with the new value as fill. There
is an oft-forgotten defaulted argument to the vector constructor and
resize function that specifies what the

vector<int> foo(10000); // 10000 elements of zero.
foo.clear();
foo.resize(10000, 5); // 10000 elements of 5;

Of course, the other way is to use fill
fill(foo.begin(), foo.end(), 5);

I think using fill is much better approach in this case, from performance
point of view. I don't know if resizing implies reallocation of memory even
for new size smaller than or equal to the old one.

br,
Catalin
 

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

Forum statistics

Threads
474,183
Messages
2,570,965
Members
47,512
Latest member
FinleyNick

Latest Threads

Top