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

For each in c++ and assigning values to std::vector

本文关键字:分配 std vector c++ 对于      更新时间:2023-10-16

如何使用"for each"指令为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

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算法有什么好的用途。它一定有好处,因为它被放入了库中,但我在C++编程的10多年里从未需要过它。在我看来,那个不是特别有用。