dbUser11
dbUser11

Reputation: 349

How to sum two lists correctly?

My task is to form a list Z by summing the elements of two lists.

If it is simpler, then I have two lists X {x1, x2, ... xn} & Y {y1, y2, ..yn} - >> I need to form Z. X & Y size is the same.

Zi = Xi + Yi

I solve this problem, but I can’t. How can I solve the problem?

Code:

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++;
    }
}

Upvotes: 0

Views: 1035

Answers (3)

Thomas Matthews
Thomas Matthews

Reputation: 57729

Research std::accumulate in your favorite C++ reference:

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

Upvotes: 1

Lukas-T
Lukas-T

Reputation: 11350

std::list has no random accesss iterators, which means you can't add an a numeric value to it to advance them by several positions. You can only increment or decrement such an iterator by one at a time.

So the idea is to take two iterators and increment both inside the loop, add the values of both iterators and push the result to Z. Something like this:

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;
    }
}

Upvotes: 1

Aplet123
Aplet123

Reputation: 35550

You need to make sure you increment both iterators so you have access to both elements:

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;
}

Upvotes: 2

Related Questions