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

C++C++11

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

You don't need initialization lists for that:

std::vector<int> vector1(length, 0);
std::vector<double> vector2(length, 0.0);

Solution 2 - C++

Initializing a vector having struct, class or Union can be done this way

std::vector<SomeStruct> someStructVect(length);
memset(someStructVect.data(), 0, sizeof(SomeStruct)*length);

Solution 3 - C++

With recent versions of c++ you can go with std::fill.

I noticed someone mentioned it as comment. But should be an answer and encourage to use standard library algorithms which are mentioned by experts, very well tested and proven.

    std::vector<int> vecOfInts;
	vecOfInts.resize(10);

	std::fill(vecOfInts.begin(), vecOfInts.end(), 0);

	for (auto const& intVal : vecOfInts)
	{
		std::cout << intVal << " ";
	}

Solution 4 - C++

For c++: Let's say that the vector has a maximum of 100 int elements. You can initialize it this way:

int vector[100]={0};

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpyCthonView Question on Stackoverflow
Solution 1 - C++ronagView Answer on Stackoverflow
Solution 2 - C++PeterView Answer on Stackoverflow
Solution 3 - C++Pavan ChandakaView Answer on Stackoverflow
Solution 4 - C++a random guyView Answer on Stackoverflow