【问题标题】:bind2nd in a for_each loopfor_each 循环中的 bind2nd
【发布时间】:2016-03-29 13:40:39
【问题描述】:

有些事情我目前无法解决。 我期待一个输出,其中每个元素都增加 1。 显然不是这样的。

仔细看,我认为是因为bind2nd函数的返回值被丢弃了;也就是说该函数不会修改容器的元素。

我的想法对吗?有人可以确认或提供正确解释容器未被修改的原因吗?

#include <vector>
#include <iostream>
#include <algorithm>
#include <functional> using namespace std; void printer(int i) {
        cout << i << ", "; } int main() {
        int mynumbers[] = { 8, 9, 7, 6, 4, 1 };
        vector<int> v1(mynumbers, mynumbers + 6);
        for_each(v1.begin(), v1.end(), bind2nd(plus<int>(), 1));//LINE I
        for_each(v1.rbegin(), v1.rend(), printer);//LINE II
        return 0; }

【问题讨论】:

    标签: c++ foreach bind2nd


    【解决方案1】:

    template &lt;typename T&gt; std::plusoperator()的声明是

    T operator()(const T& lhs, const T& rhs) const;
    

    即它不会修改输入参数。你需要std::transform:

    std::transform(v1.cbegin(), v1.cend() v1.begin(), std::bind2nd(std::plus<int>(), 1));
    

    或者您可以使用 修改其输入参数的 lambda:

    std::for_each(v1.begin(), v1.end(), [] (int& x) { ++x; });
    

    【讨论】:

      【解决方案2】:
      for_each(v1.begin(), v1.end(), bind2nd(plus<int>(), 1));
      

      等价于:

      for (auto first = v1.begin(); first != last; ++first) {
          plus<int>()(*first, 1); // i.e. *first + 1;
      }
      

      正如您所见,它确实不会改变任何事情。

      您可以使用函子来更改 std::for_each 的值:

      std::for_each(v1.begin(), v1.end(), [](int &n){ n += 1; });
      

      【讨论】:

        【解决方案3】:

        std::for_each 不修改输入序列。

        要对容器的每个元素应用更改,请改用std::transform

        transform(v1.begin(), v1.end(), v1.begin(), bind2nd(plus<int>(), 1));
        //                              ~~~~~~~~~^ puts the results back into the input sequence
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-01-17
          • 2020-11-01
          • 1970-01-01
          • 2021-11-25
          • 2021-10-04
          • 1970-01-01
          • 2021-05-25
          相关资源
          最近更新 更多