Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector elements initializing

Tags:

c++

vector

std::vector<int> v1(1000);
std::vector<std::vector<int>> v2(1000);
std::vector<std::vector<int>::const_iterator> v3(1000);

How elements of these 3 vectors initialized?

About int, I test it and I saw that all elements become 0. Is this standard? I believed that primitives remain undefined. I create a vector with 300000000 elements, give non-zero values, delete it and recreate it, to avoid OS memory clear for data safety. Elements of recreated vector were 0 too.

What about iterator? Is there a initial value (0) for default constructor or initial value remains undefined? When I check this, iterators point to 0, but this can be OS

When I create a special object to track constructors, I saw that for first object, vector run the default constructor and for all others it run the copy constructor. Is this standard?

Is there a way to completely avoid initialization of elements? Or I must create my own vector? (Oh my God, I always say NOT ANOTHER VECTOR IMPLEMENTATION) I ask because I use ultra huge sparse matrices with parallel processing, so I cannot use push_back() and of course I don't want useless initialization, when later I will change the value.

like image 847
Chameleon Avatar asked Jun 05 '12 22:06

Chameleon


1 Answers

You are using this constructor (for std::vector<>):

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

Which has the following documentation:

Repetitive sequence constructor: Initializes the vector with its content set to a repetition, n times, of copies of value.

Since you do not specify the value it takes the default-value of the parameter, T(), which is int in your case, so all elements will be 0

like image 191
Attila Avatar answered Oct 15 '22 21:10

Attila