对于c++中的每个,并将值分配给std::vector
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++编程的10多年里从未需要过它。在我看来,那个不是特别有用。
相关文章:
- C++ 使用枚举类对象分配 std::map 值
- 如何在 C++11 的内存池中分配 std::map 的内部RB_tree节点?
- 分配 std::函数会导致段错误
- 我可以在堆栈上分配`std :: array`阵列,而不知道编译时大小
- 有条件地分配 std::string 作为引用
- 分配std :: vector元素的两种方法
- 为缓存分配 std::shared_ptr 的集合
- 在 c++ 中填充和分配 std::string
- 正确分配 std::vector
- 从函数结果中分配 std::shared_ptr 的一行是什么?
- 分配std::vector数组会减慢后续计算的速度
- 在结构中分配std::字符串时出现分段错误
- 尝试使用 std::bind 重新分配 std::function 并得到错误"attempting to reference a deleted function"
- 重新分配 std::clog 时退出时 SEGV
- 在 std::vector 中重新分配 std::vector,在 std::vector.reserve() 之后
- 没有可行的重载"="来分配 std::function 回调作为成员函数
- 动态分配std::string数组
- 重新创建(重新分配)std::shared_ptr或std::unique_ptr
- 分配std::string时出现分段错误
- 用std::矢量迭代器分配std::字符串在一个项目中会导致调试错误,但在另一个项目却能正常工作