How to assign a value to the first n elements of a vector? c++

有些话、适合烂在心里 提交于 2019-12-11 05:06:27

问题


How to assign a value to the first n elements of a vector? Say, I want to assign 1 to a vector from index 0 to index 4.

I already have a vector with size 11. Now I want to put 1 to the first 5 elements.


回答1:


You can use std::fill or std::fill_n:

std::fill(v.begin(), std::next(v.begin(), 5), 1);
std::fill_n(v.begin(), 5, 1);

Note: std::next is C++11. In this case it can be replaced by v.begin() + 5.




回答2:


If you want to construct a vector filled like that, use the suitable constructor:

std::vector<int> v(5,1);

This creates 5 ints with value 1.




回答3:


You can use std::fill

According to the documentation:

template< class ForwardIt, class T >
void fill(ForwardIt first, ForwardIt last, const T& value)
{
    for (; first != last; ++first) {
        *first = value;
    }
 }

You can do:

 std::fill(v.begin(), v.begin() +5, 1) ;//assume you fill 1 from index 0 to 4(included)


来源:https://stackoverflow.com/questions/17972966/how-to-assign-a-value-to-the-first-n-elements-of-a-vector-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!