简体   繁体   中英

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

How can I assign values to elements of std::vector using "for each" instruction? I tried to do something like this:

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

But then I get the following error:

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

The for_each algorithm does not seem appropriate for that type of problem. Let me know if I am misunderstanding the issue.

    // 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;

Personally, I have not ever found a good use for the for_each algorithm. It must be good for something because it was put into the library but I have never needed it in over 10 years of C++ programming. That one isn't particularly useful in my opinion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM