473,388 Members | 1,346 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,388 software developers and data experts.

Initialization of vectors in c++

Experimenting at home with visual c++, I see that int main()
{std::vector<doublevect(5);} creates a vector whose 5 initial
values are all 0. Is this standard or might the five initial values
be different from 0? I'm a bit surprised by this as I would expect
vect to consist of five uninitialized doubles. Why is it that double
x; introduces a double which is uninitialized and yet the above vect
is initialized? Or is this just a matter of the definition of the c++
language which should just be accepted, and can't be derived from some
other principle?

Thank you,

Paul Epstein
Jun 27 '08 #1
12 3280
On Apr 13, 11:10 pm, pauldepst...@att.net wrote:
Experimenting at home with visual c++, I see that int main()
{std::vector<doublevect(5);} creates a vector whose 5 initial
values are all 0. Is this standard or might the five initial values
be different from 0? I'm a bit surprised by this as I would expect
vect to consist of five uninitialized doubles. Why is it that double
x; introduces a double which is uninitialized and yet the above vect
is initialized? Or is this just a matter of the definition of the c++
language which should just be accepted, and can't be derived from some
other principle?
Here you actually called

explicit vector(size_type n, const T& value = T(),
const Allocator& = Allocator());

so the question becomes what T() equals to.

8.5

7
An object whose initializer is an empty set of parentheses, i.e., (),
shall be value-initialized.

5
To zero-initialize an object of type T means:
-- if T is a scalar type (3.9), the object is set to the value of 0
(zero) converted to T;
....

To default-initialize an object of type T means:
-- if T is a non-POD class type (clause 9), the default constructor for
T is called
(and the initialization is ill-formed if T has no accessible default
constructor);
-- if T is an array type, each element is default-initialized;
-- otherwise, the object is zero-initialized.

so with T==int, int() == 0

Jun 27 '08 #2
In article <03277800-7557-456d-96b8-
d4**********@s39g2000prd.googlegroups.com>, pa**********@att.net says...
Experimenting at home with visual c++, I see that int main()
{std::vector<doublevect(5);} creates a vector whose 5 initial
values are all 0. Is this standard or might the five initial values
be different from 0? I'm a bit surprised by this as I would expect
vect to consist of five uninitialized doubles. Why is it that double
x; introduces a double which is uninitialized and yet the above vect
is initialized? Or is this just a matter of the definition of the c++
language which should just be accepted, and can't be derived from some
other principle?
As others have pointed out, the value is guaranteed to be zero.

What they haven't pointed out (directly) is that you can specify another
value if you prefer. E.g.:

std::vector<doublevect(5, 15.0);

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 27 '08 #3
Jerry Coffin wrote:
As others have pointed out, the value is guaranteed to be zero.
Sometimes I feel this is counter-productive speedwise.

If I want to allocate a large array of, for example, integers and I
don't need for them to be initialized to anything (eg. because right
after the allocation I initialize them manually to some values), the
std::vector will uselessly go through the allocated array, initializing
every value with 0, right after which I go again through the vector and
initialize the values to something else. This is wasted time.

If I allocate the array with 'new', it won't do anything to it and it
will be much faster.
Jun 27 '08 #4

"Juha Nieminen" <no****@thanks.invalidwrote in message Jerry Coffin
wrote:
>As others have pointed out, the value is guaranteed to be zero.

Sometimes I feel this is counter-productive speedwise.

If I want to allocate a large array of, for example, integers and I
don't need for them to be initialized to anything (eg. because right
after the allocation I initialize them manually to some values), the
std::vector will uselessly go through the allocated array, initializing
every value with 0, right after which I go again through the vector and
initialize the values to something else. This is wasted time.

If I allocate the array with 'new', it won't do anything to it and it
will be much faster.
I think any statement without doing any actual measurements may not be true
here. Also it would be a QoI issue.

--
http://techytalk.googlepages.com
Jun 27 '08 #5
Juha Nieminen wrote:
Jerry Coffin wrote:
>As others have pointed out, the value is guaranteed to be zero.

Sometimes I feel this is counter-productive speedwise.

If I want to allocate a large array of, for example, integers and I
don't need for them to be initialized to anything (eg. because right
after the allocation I initialize them manually to some values), the
std::vector will uselessly go through the allocated array, initializing
every value with 0, right after which I go again through the vector and
initialize the values to something else. This is wasted time.

If I allocate the array with 'new', it won't do anything to it and it
will be much faster.
In the case of value types, yes, it can be a waste of time. However in
the general object case you must call *some* constructor for each
object, and the container expects this.

To follow from Vladislav's post: to reserve() the space, then
initialise each one as you go, is most efficient.

Andy
Jun 27 '08 #6
Andy Champ wrote:
To follow from Vladislav's post: to reserve() the space, then
initialise each one as you go, is most efficient.
Yes, reserve() plus initializing with push_back() may be an
improvement to the situation. However, I wonder if push_back() is as
fast as a direct "array[index] = value;".
Jun 27 '08 #7
Juha Nieminen wrote:
Andy Champ wrote:
>To follow from Vladislav's post: to reserve() the space, then
initialise each one as you go, is most efficient.

Yes, reserve() plus initializing with push_back() may be an
improvement to the situation. However, I wonder if push_back() is as
fast as a direct "array[index] = value;".
The difference is that 'push_back' copy-constructs using placement
'new', whereas the other way would default-construct and then assign.
Basically, the total difference would be the final 'size()' times the
difference between {def-construct + assign} vs {copy-construct}.

But it would have to be measured, not calculated.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 27 '08 #8
Victor Bazarov schrieb:
Juha Nieminen wrote:
>Andy Champ wrote:
>>To follow from Vladislav's post: to reserve() the space, then
initialise each one as you go, is most efficient.
Yes, reserve() plus initializing with push_back() may be an
improvement to the situation. However, I wonder if push_back() is as
fast as a direct "array[index] = value;".

The difference is that 'push_back' copy-constructs using placement
'new', whereas the other way would default-construct and then assign.
Basically, the total difference would be the final 'size()' times the
difference between {def-construct + assign} vs {copy-construct}.
push_back() has to test the need for reallocation on each call, that makes
it hard to unroll the loop and is a mess for the instruction pipeline etc...
>
But it would have to be measured, not calculated.
Thats the only way.

--
Thomas
http://www.netmeister.org/news/learn2quote.html
"Some folks are wise, and some otherwise."
Jun 27 '08 #9
Thomas J. Gritzan wrote:
push_back() has to test the need for reallocation on each call, that
makes it hard to unroll the loop and is a mess for the instruction
pipeline etc...
And if we are using something like OpenMP, push_backs cannot be
performed in parallel (while direct array initializations can, given
that the values do not depend on each other).
Jun 27 '08 #10
On Apr 13, 8:57 pm, Juha Nieminen <nos...@thanks.invalidwrote:
Jerry Coffin wrote:
As others have pointed out, the value is guaranteed to be zero.
Sometimes I feel this is counter-productive speedwise.
You mean you've actually had cases where an application wasn't
fast enough because of it?
If I want to allocate a large array of, for example, integers and I
don't need for them to be initialized to anything (eg. because right
after the allocation I initialize them manually to some values), the
std::vector will uselessly go through the allocated array, initializing
every value with 0, right after which I go again through the vector and
initialize the values to something else. This is wasted time.
You mean you've actually had an application which wasn't fast
enough because of this?

Of course, it's really very rare to initialize a vector like
this unless you actually want all of the values to have the same
value. Usually, you'll provide two iterators which generate the
correct values. And yes, I know, it would be a lot easier and a
lot more natural if only one were necessary, but Boost iterator
can take a lot of the pain out of it.
If I allocate the array with 'new', it won't do anything to it
and it will be much faster.
Using uninitialized memory to generate random results is
probably faster than anything you can do with std::vector, yes.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jun 27 '08 #11
On Apr 15, 12:01 am, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
Juha Nieminen wrote:
Andy Champ wrote:
To follow from Vladislav's post: to reserve() the space,
then initialise each one as you go, is most efficient.
Yes, reserve() plus initializing with push_back() may be an
improvement to the situation. However, I wonder if
push_back() is as fast as a direct "array[index] = value;".
The difference is that 'push_back' copy-constructs using
placement 'new', whereas the other way would default-construct
and then assign. Basically, the total difference would be the
final 'size()' times the difference between {def-construct +
assign} vs {copy-construct}.
But it would have to be measured, not calculated.
The one time I measured, creating a vector< double with all of
the elements, then assigning, was faster than using puch_back.
On my particular implementation. (I forget now whether I did
the measurement on a Sparc under Solaris or a PC under Linux.)

If speed is critical, use the two iterators constructor, and
make sure it's a random access iterator. It's a little more
work, but the case probably comes up so rarely that that's not
an issue.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #12
In article <48***********************@news.tdc.fi>,
no****@thanks.invalid says...
Jerry Coffin wrote:
As others have pointed out, the value is guaranteed to be zero.

Sometimes I feel this is counter-productive speedwise.
At least in theory, it is. OTOH, from a practical viewpoint, I've never
run into a situation where it caused any problem at all.
If I want to allocate a large array of, for example, integers and I
don't need for them to be initialized to anything (eg. because right
after the allocation I initialize them manually to some values), the
std::vector will uselessly go through the allocated array, initializing
every value with 0, right after which I go again through the vector and
initialize the values to something else. This is wasted time.
If you're going to initialize the values to some other values, why not
supply those values when you create the vector? One of vector's ctors
allows you to supply a couple of iterators to specify the values to use
for initialization.

If you know the number of values but not (yet) the values themselves,
reserve the space but leave the vector empty, then put the values in
when they're available.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 27 '08 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Pratyush | last post by:
Hi, Suppose there is a vector of objects of class A, i.e., std::vector<A> vec_A(N); The class A satisifies all the STL vector requirements. Now I wish to add some attributes for each of the...
4
by: Russell Silva | last post by:
I have a class A with a member variable type vector<foo> which is initialized upon construction (no standard () constructor): class A { protected: vector<foo> foo_vector; public: A(const...
5
by: Computer Whizz | last post by:
I was reading through Accelerated C++ at work when I read through the first mention of Vectors, giving us certain functions etc. Is there any benefit of Arrays over Vectors? Since all Vectors...
3
by: Amit | last post by:
Hello. I am having some problem organizing a set of vectors. The vectors itself, could contain a pointer( say integer pointer) or could contain another object MyClass. 1>So, first of all, is...
3
by: jut_bit_zx | last post by:
class A { public: A(); virtual ~A(){} .... private: int m_iarray; }
6
by: giulianodammando | last post by:
In the development of a simple numerical simulation software i need to read some initialization parameters from a file that looks like: # Global Setup species = 1; \begin{specie}<1>...
5
by: madhu | last post by:
http://msdn2.microsoft.com/en-us/library/fs5a18ce(VS.80).aspx vector <intv1; v1.push_back( 10 ); //adds 10 to the tail v1.push_back( 20 ); //adds 20 to the tail cout << "The size of v1 is " <<...
4
by: Jess | last post by:
Hello, I tried several books to find out the details of object initialization. Unfortunately, I'm still confused by two specific concepts, namely default-initialization and...
1
by: Rob | last post by:
How would I do this? I want to be able to handle vectors of many different types of data and vectors that can contain any number of other vectors of data. Currently, I have a templated...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.