assign all values of a vector c++ code example

Example: how to assign all elements of vector in c++

#include <iostream>
#include <vector>
using namespace std;

// program to illustrate use of std::vector::assign()

int main()
{
	int vec_size, new_val;
	cin >> vec_size >> new_val;
	vector<int> vec(vec_size);

	for (int x : vec)
		cout << x << " ";

	cout << endl;

	// vec.assign(n, val) assigns all n elements of vec new value = val
	vec.assign(vec_size, new_val);
	for (int x : vec)
		cout << x << " ";
}

Tags:

Cpp Example