如何为std::vector使用“for each”指令的元素赋值?我试图做这样的事情:
std::vector<int> A(5);
for each(auto& a in A)
a = 4;
Run Code Online (Sandbox Code Playgroud)
但后来我收到以下错误:
error C3892 : 'a' : you cannot assign to a variable that is const
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
就我个人而言,我还没有找到 for_each 算法的好用处。它一定对某些东西有好处,因为它被放入了库中,但我在 10 多年的 C++ 编程中从未需要它。在我看来,那个不是特别有用。