【问题标题】:How to sum two lists correctly?如何正确总结两个列表?
【发布时间】:2020-04-20 16:56:27
【问题描述】:

我的任务是通过将两个列表的元素相加来形成一个列表 Z。

如果它更简单,那么我有两个列表X {x1, x2, ... xn} & Y {y1, y2, ..yn} - >> 我需要形成 Z。 X & Y 大小相同。

Zi = Xi + Yi

我解决了这个问题,但我不能。我该如何解决这个问题?

代码:

void IndividualTask(list<float>& lisX, list<float>& lisY) {
    list<float> Z;
    int i = 0;
    list<float>::iterator x = lisX.begin();
    list<float>::iterator y = lisY.begin();
    for (list<float>::iterator it = lisX.begin(); it != lisX.end(); ++it) {
        Z.push_back((x + i) + (y + i));
        i++;
    }
}

【问题讨论】:

  • 如果list&lt;float&gt;std::list,你不能将list&lt;float&gt;::iteratorint 相加,比如(x + i),你只能对它们做++-- .您只能将整数与随机迭代器相加,例如来自 std::vector 的迭代器。
  • 基本上,您想要对 2 个列表求和。所以i 是没有意义的,它只是给你的,只是为了证明你想要什么。您需要同时增加 lisXlisY 然后 Z.push_back *xiter + *yiter (或任何您将调用的迭代器)

标签: c++ list


【解决方案1】:

您需要确保增加两个迭代器,以便您可以访问这两个元素:

std::list<float> IndividualTask(std::list<float>& lisX, std::list<float>& lisY) {
    std::list<float> Z;
    for (auto x = lisX.begin(), y = lisY.begin(); x != lisX.end() && y != lisY.end(); ++x, ++y) {
        Z.push_back(*x + *y);
    }
    return Z;
}

【讨论】:

    【解决方案2】:

    std::list 没有随机访问迭代器,这意味着您不能向其中添加数值以将它们推进几个位置。您一次只能将此类迭代器递增或递减一个。

    所以想法是在循环中使用两个迭代器并递增,将两个迭代器的值相加并将结果推送到Z。像这样的:

    void IndividualTask(const list<float>& lisX, const list<float>& lisY) {
        list<float> Z;
        auto x = lisX.begin();
        auto y = lisY.begin();
        while(x != lisX.end() && y != lisY.end()) {
            Z.push_back(*x + *y);
    
            ++x;
            ++y;
        }
    }
    

    【讨论】:

      【解决方案3】:

      在您最喜欢的 C++ 参考资料中研究 std::accumulate

      std::list<float> numbers;
      //...
      const float sum = std::accumulate(numbers.begin(), numbers.end(), 0.0);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-08
        • 1970-01-01
        • 2022-01-18
        • 2021-12-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多