Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialize a vector to zeros C++/C++11

Tags:

c++

c++11

I know in C++11 they added the feature to initialize a variable to zero as such

double number = {}; // number = 0
int data{};  // data = 0

Is there a similar way to initialize a std::vector of a fixed length to all zero's?

like image 864
pyCthon Avatar asked Oct 18 '22 20:10

pyCthon


People also ask

How do you initialize a vector with zeros?

A vector can be initialized with all zeros in three principal ways: A) use the initializer_list, B) use the assign() vector member function to an empty vector (or push_back()), or C) use int or float as the template parameter specialization for a vector of initially only default values.

How do you declare a vector with all elements to zero in C++?

You can use: std::vector<int> v(100); // 100 is the number of elements. // The elements are initialized with zero values.

What is vector in C++ 11?

1) std::vector is a sequence container that encapsulates dynamic size arrays. 2) std::pmr::vector is an alias template that uses a polymorphic allocator. The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets to regular pointers to elements.

What is the correct way to initialize vector in C?

Begin Declare v of vector type. Call push_back() function to insert values into vector v.


1 Answers

You don't need initialization lists for that:

std::vector<int> vector1(length, 0);
std::vector<double> vector2(length, 0.0);
like image 315
ronag Avatar answered Oct 23 '22 21:10

ronag