0
다음 작업이 주어진 것입니다. 주어진 이중 링크 목록의 실수로 목록의 반대 요소를 곱해야합니다 두 번째로 마지막 마이너스 1 등)을 선택하고이 제품을 새 목록에 추가하십시오. 즉 :C++ 이중 링크 목록의 반대 요소를 쌍으로 곱하기
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;
}
목록의 요소를 역순으로 반복하는 것은 문제가됩니다. 목록의 마지막 요소를 제거하는 옵션 만 발견했습니다.
그래서 나는 누군가가 그 일을하기 위해 더 훌륭한 알고리즘을 만들 수 있었는지 궁금하다.
질문 [SE 코드 검토 (https://codereview.stackexchange.com/)로 이동한다. – user0042
@JTejedor 그는리스트를 수정하고 있기 때문에'rbegin()'은 원하는 원소가 이제 마지막 원소이기 때문에 다음 반복에서 올바른 원소를 가리킨다. – Zinki