What is the usage of the assign function in vectors in C++?
In C++, the assign function for vectors is used to assign new values to the vector, and it can be used in several ways.
- a quantity having both magnitude and direction
std::vector<int> vec = {1, 2, 3, 4, 5};
vec.assign(3, 0); // 将vec的元素替换为3个值为0的元素
- a quantity that has magnitude and direction
std::vector<int> vec1 = {1, 2, 3};
std::vector<int> vec2 = {4, 5, 6};
vec1.assign(vec2.begin(), vec2.end()); // 将vec1的元素替换为vec2的元素
- a quantity that has both magnitude and direction
std::vector<int> vec = {1, 2, 3};
vec.assign({4, 5, 6}); // 将vec的元素替换为初始化列表中的元素
The assign function allows us to easily add or replace elements in a vector, improving the code’s readability and usability.