[英]For each in c++ and assigning values to std::vector
如何使用“ 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 ++编程中从未使用过它。 我认为那不是特别有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.