开发者

for_each but for setting each element to a value in C++

I have the following code to assign a value to all the elements of a vector:

x = 100;

for 开发者_JS百科(int i=0;i<vect.size();i++)
{
    vect[i] = x;
}

It's straightforward enough, but I'm wondering if there is a function in the STL that does the same thing; something like for_each, but for assignment.


Use std::fill:

std::fill(vect.begin(), vect.end(), 100);

Note if you want to initialize a vector to have all the same value, you can use the appropriate constructor:

std::vector<int> v(5, 100); // 5 elements set to 100

assign can be used to "reset the vector", but if you're just making the vector, use the constructor.


vect.assign(n, x);

n is the number of elements.

x is the value to fill with.

The difference from std::fill is that you supply the length for this. std::fill would use the previous length of the vector. (Actually, it would use whatever segment of the vector that you tell it to, but using vect.begin() and vect.end() as in the above example would use the previous length.) Depending on the situation, you will want to use one or the other.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜