我的任务是通过将两个列表的元素相加来形成一个列表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++;
}
}发布于 2020-04-21 01:08:09
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;
}
}发布于 2020-04-21 01:07:03
您需要确保递增两个迭代器,以便可以访问这两个元素:
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;
}发布于 2020-04-21 01:24:05
在您最喜欢的C++参考中研究std::accumulate:
std::list<float> numbers;
//...
const float sum = std::accumulate(numbers.begin(), numbers.end(), 0.0);https://stackoverflow.com/questions/61327878
复制相似问题