简体   繁体   English

C ++双链表相反元素的成对乘法

[英]Pairwise multiplication of the opposite elements of the c++ doubly-linked list

I've been given a following task: with the given double-linked list of real numbers you have to multiply the opposite elements of the list (first with the last, second with the last minus one, etc.) and add this product to the new list. 我已经完成了以下任务:使用给定的实数双向链接列表,您必须将列表的相反元素相乘(第一个与最后一个,第二个与最后一个减号,依此类推),然后将此乘积添加到新列表。 Ie: we have that list: 即:我们有该列表:

1.1 2.2 3.3 4.4 5.5 

Then we print 然后我们打印

1.1 * 5.5 = 6.05; 
2.2 * 4.4 = 9.68; 
3.3 * 3.3 = 10.89;

And the final list is: 最后的列表是:

6.05 9.68 10.89 

I've come up with the following naïve algorithm: 我提出了以下朴素算法:

#include <iostream>
#include <list>

using namespace std;

int main() {
    double x = 0;   
    double q = 0;   //for the product of the elements
    list <double> user_values, calculated_products;

    //data entry
    while ( cin >> x) {
        user_values.push_back(x);
        if (cin.get() == '\n') break;
    }

    //pairwise multiplication of the opposite elements (х1 * хn; x2 * xn-1; etc.):
    for (auto p = user_values.begin(); p!=(user_values.end()); ++p){
        cout << (*p) << " * " << (*user_values.rbegin()) << " = " ;
        q = (*p) * (*user_values.rbegin());  //result of the multiplication
        cout << q  << "; " << endl;
        calculated_products.push_back(q);  //saving result to the new list
        user_values.pop_back();   //removing the last element of the list, in order to iterate backwards. This is probably the most confusing part.
    }

    //result output:
    cout << "we have such list of products: " << endl;
    for (const auto& t: calculated_products){
        cout << t << " ";
    }
    cout << endl;
    return 0;
}

Since it is problematic to iterate through elements of the list backwards, I've only found the option of removing the last elements of the list. 由于向后遍历列表元素是有问题的,因此我仅找到了删除列表的最后一个元素的选项。

So I wonder whether someone could came up with more elegant algorithm for doing that, or at least refine the one above. 因此,我想知道是否有人会想出一种更优雅的算法来做到这一点,或者至少完善上面的算法。

You can use rbegin() to iterate from back to forth: 您可以使用rbegin()来回迭代:

auto i1 = user_values.begin();
auto i2 = user_values.rbegin();
double bufResult = 0;   //for the product of the elements

for(int i=0; i<user_values.size()/2; i++)
{
    bufResult = (*i1) * (*i2);  //result of the multiplication
    cout << (*i1) << " * " << (*i2) << " = " << bufResult << "; " << endl;
    calculated_products.push_back(bufResult);  //saving result to the new list
    i1++;
    i2++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM