对于c ++中的每一个,并将值赋给std :: vector

时间:2014-04-11 18:41:43

标签: c++ foreach

如何使用"为每个"分配std::vector元素的值?指令? 我试着做这样的事情:

std::vector<int> A(5);
for each(auto& a in A)
    a = 4;

但后来我收到以下错误:

error C3892 : 'a' : you cannot assign to a variable that is const

1 个答案:

答案 0 :(得分:4)

for_each算法似乎不适合这类问题。如果我误解了这个问题,请告诉我。

    // You can set each value to the same during construction
    std::vector<int> A(10, 4);  // 10 elements all equal to 4

    // post construction, you can use std::fill
    std::fill(A.begin(), A.end(), 4);

    // or if you need different values via a predicate function or functor
    std::generate(A.begin(), A.end(), predicate);

    // if you really want to loop, you can do that too if your compiler 
    // supports it VS2010 does not yet support this way but the above 
    // options have been part of the STL for many years.

    for (int &i : A) i = 4;

就个人而言,我还没有找到一个很好用的for_each算法。它必须对某些东西有好处,因为它被放入了库中,但我从未在超过10年的C ++编程中使用它。在我看来,这个并不是特别有用。