Vlad the Impala
Vlad the Impala

Reputation: 15872

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 (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.

Upvotes: 6

Views: 1004

Answers (2)

GManNickG
GManNickG

Reputation: 503873

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.

Upvotes: 11

Zifre
Zifre

Reputation: 26998

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.

Upvotes: 7

Related Questions