如何在 C++ 中使用 STL 列表从另一个函数调用一个函数?

How to call a function from another function using STL list in C++?

我是 C++ 中数据结构的新手,我想使用 STL 列表 编写代码来显示以下内容:

Input for data radius:
Radius 1: 20
Press [Y] for next input: Y
Radius 2: 12
Press [Y] for next input: N

List of Existing Records:
ID:1, Radius: 20, Volume: 33,514.67
ID:2, Radius: 12, Volume: 7,239.17
Total record: 2

我写了这样的代码,但我不太确定如何准确地包含音量值 dataVolume() 以便我可以获得所需的输出:

#include <iostream>
#include <list>

using namespace std;

struct sphere {
    int recordID;
    double radius, volume;
};

double dataVolume(sphere* values) {
    double v = (4 * 3.14 * (values->radius) * (values->radius) * (values->radius)) / 3.0;
    return v;
}

void dataRadius(sphere* values) {
    int i = 0;
    char choice;
    do {
        cout << "Radius " <<i+1 <<": ";
        cin >> values->radius;
       // values->volume = dataVolume();
        cout << "Press [Y] for next input: ";
        cin >> choice;
        i++;
    } while (choice == 'Y');

}

void displayData(list<sphere>Record) {
    cout << "List of Existing Records:" << endl;
    list<int>::iterator i;
    int count = 0;
    for (auto i = Record.begin(); i != Record.end(); i++) {
        cout << "ID: " << count + 1 << ", Radius: " << i->radius <<
            ", Volume: " << i->volume << endl;
        count = count + 1;
    }
    cout << "Total record: " << count << endl;
}

int main() {

    list<sphere>Record;
    sphere values;
    dataRadius(&values);    
    displayData(Record);
    return 0;
}
double dataVolume(double radius) {
    double v = (4 * 3.14 * radius * radius * radius) / 3.0;
    return v;
}

void dataRadius(sphere* values) {
    int i = 0;
    char choice;
    do {
        cout << "Radius " <<i+1 <<": ";
        cin >> values->radius;
        values->volume = dataVolume(values->radius);
        cout << "Press [Y] for next input: ";
        cin >> choice;
        i++;
    } while (choice == 'Y');
}

此外,您应该将球体推入列表。 我会这样重写的。

void dataRadius(list<sphere> & Record) {
    int i = 0;
    char choice;
    do {
        cout << "Radius " <<i+1 <<": ";
        sphere values; // construct a new sphere
        cin >> values.radius;
        values.volume = dataVolume(values.radius);
        Record.push_back(values);
        cout << "Press [Y] for next input: ";
        cin >> choice;
        i++;
    } while (choice == 'Y');
}

int main() {
    list<sphere>Record;
    dataRadius(Record);    
    displayData(Record);
    return 0;
}