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++;
}
相关文章:
- 如何实现 Front() 方法以返回模板化双向链表C++的第一个元素?
- 如何实现容纳整数和无效指针的双向链表?
- 为什么我的双向链表删除函数会删除多个节点?
- 我对数据结构、双向链表有一些问题
- C++ 双向链表:使用矩阵类成员创建和填充列表
- 在 c++ 中具有向量的双向链表构造函数
- 如何在双向链表上实现复制赋值?
- 在C++中删除双向链表的头节点后出现访问冲突异常
- 在双向链表中实现 Popback
- 在C++中反转双向链表
- 双向链表 - 无法删除第一个节点
- 我当前实现的双向链表类是否需要重构迭代器 end() 功能?
- 双向链表 std::unique_ptr 类在节点删除时无法按预期工作
- C++ 双向链表 - 插入同时保持递增顺序
- 如何找到双向链表的最大元素?
- 如何实现双向链表的迭代器?
- 双向链表问题 - 包含项目但不显示
- 双向链表未正确打印值
- 插入到双向链表中的特定位置
- 如何在双向链表的网格中旋转列