簡體   English   中英

C ++雙鏈表相反元素的成對乘法

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

我已經完成了以下任務:使用給定的實數雙向鏈接列表,您必須將列表的相反元素相乘(第一個與最后一個,第二個與最后一個減號,依此類推),然后將此乘積添加到新列表。 即:我們有該列表:

1.1 2.2 3.3 4.4 5.5 

然后我們打印

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

最后的列表是:

6.05 9.68 10.89 

我提出了以下朴素算法:

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

由於向后遍歷列表元素是有問題的,因此我僅找到了刪除列表的最后一個元素的選項。

因此,我想知道是否有人會想出一種更優雅的算法來做到這一點,或者至少完善上面的算法。

您可以使用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