How to assign a value to the first n elements of a

2019-07-29 05:17发布

问题:

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)