簡體   English   中英

對於每個在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 ++編程中從未使用過它。 我認為那不是特別有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM