std::transform using C++0x lambda expression

后端 未结 6 1222
灰色年华
灰色年华 2020-12-28 13:05

How is this done in C++0x?

std::vector myv1;
std::transform(myv1.begin(), myv1.end(), myv1.begin(),
               std::bind1st(std::multiplies         


        
6条回答
  •  悲&欢浪女
    2020-12-28 14:01

    Using a mutable approach, we can use for_each to directly update the sequence elements through references.

    for_each(begin(myv1), end(myv1), [](double& a) { a *= 3; });
    


    There has been some debate going on if for_each is actually allowed to modify elements as it's called a "non-mutating" algorithm.

    What that means is for_each isn't allowed to alter the sequence it operates on (which refers to changes of the sequence structure - i.e. invalidating iterators). This doesn't mean we cannot modify the non-const elements of the vector as usual - the structure itself is left untouched by these operations.

提交回复
热议问题