代码之家  ›  专栏  ›  技术社区  ›  ande

c++双链表中对立元素的成对乘法

  •  0
  • ande  · 技术社区  · 8 年前

    我被赋予了以下任务:在给定的实数双链列表中,你必须将列表中的相反元素相乘(第一个与最后一个相乘,第二个与最后一个负一相乘,等等),然后将此乘积添加到新列表中。 一、 e:我们有以下清单:

    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 
    

    我提出了以下naÃve算法:

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

    由于向后遍历列表中的元素是有问题的,所以我只找到了删除列表中最后一个元素的选项。

    因此,我想知道是否有人能想出更优雅的算法来实现这一点,或者至少改进上面的算法。

    1 回复  |  直到 8 年前
        1
  •  1
  •   Detonar    8 年前

    您可以使用 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++;
    }
    
    推荐文章