簡體   English   中英

如何將對象的向量分配到堆

[英]How to Allocate Vector of Objects to the Heap

我目前有一個從 file.txt 讀取的程序。 該文件的內容包含參加奧運會跳遠項目的運動員。

格式為[名字]、[姓氏]、[國籍]、[距離]

該程序將首先驗證文件是否可以讀取,如果可以,則輸出控制台消息“數據加載成功”。

其次,它會提示用戶輸入閾值距離(例如:7.7m),它將打印出所有距離 > 7.7m 的運動員。

我目前的程序能夠做我想做的一切。 但是,我需要幫助的是有 40 個指針(因為有 40 個 Athlete 對象)指向堆中的對象。 在我想在內存中釋放它們之后。 在此先感謝您的幫助!

測試文件

#include <iostream>
#include<fstream>
#include<vector>
#include<string>
#include "Person.h"
#include "Athlete.h"
using namespace std;
using std::cerr;

//overload the operator << to be used for printing the Athlete  Objects
ostream& operator<<(ostream& out, Athlete& a) {
    out << a.getFirstName() << " " << a.getLastName() << " " << a.getNationality() << " " << a.getDistance() << "\n";
    return out;
}

vector<Athlete> athletesList;
vector<Athlete> readAthletesFromFile() {

    athletesList.reserve(40);
    fstream athlethesFile("file.txt");
    if (!athlethesFile) {
        cerr << "Could not open file\n";
        return athletesList;
    }
    string tmpFirstName;
    string tmpLastName;
    string tmpNationality;
    string tmpDoubleDistance;
    while (true) {
        athlethesFile >> tmpFirstName;
        athlethesFile >> tmpLastName;
        athlethesFile >> tmpNationality;
        athlethesFile >> tmpDoubleDistance;
        if (!athlethesFile) break;
        auto tmpDistance = stod(tmpDoubleDistance);
        athletesList.emplace_back(tmpFirstName, tmpLastName, tmpNationality, tmpDistance);

        //cout << athletesList.back();   

    }
    cout << "Data is loaded successfully." << "\n";
    return athletesList;
}

double validateUserInput() {
    double input;
    cout << "Please enter the distance threshold: ";
    cin >> input;

    if (input < 0) {
        throw runtime_error("Please enter positive integer.");
    };
    if (input < 6.55) {
        throw runtime_error("Number entered is too low!");
    }
    if (input > 8.11) {
        throw runtime_error("Number entered is too high!");
    }

    return input;
}

void printAthletes(vector<Athlete> athletesList, double maxDistance) {


    if (6.55 <= maxDistance <= 8.11) {
        cout << "The athletes that exceed " << maxDistance << " m " << "are: " << endl;
        for (int i = 0; i < athletesList.size(); i++) {
            double tdist = athletesList[i].getDistance();
            if (tdist > maxDistance) {
                cout << athletesList[i];
            }
        }
    }
}

int main() {
    try{
        vector<Athlete> athletes {readAthletesFromFile()};
        double maxDistance {validateUserInput()};
        if (maxDistance >= 0)
            printAthletes(athletes, maxDistance);

        system("pause");
        return 0;
    }
        catch (exception & e) {
        cerr << "Exception occured: " << e.what() << endl;
        return -1;
    }
}

文件.txt

Aleksandr Menkov Russia 8.09
Aleksandr Petrov Russia 7.89
Alyn Camara Germany 7.72
Arsen Sargsyan Armenia 7.62
Boleslav Skhirtladze Georgia 7.26
Christian Reif Germany 7.92
Christopher Tomlinson Great_Britain 8.06
Damar Forbes Jamaica 7.79
Eusebio Caceres Spain 7.92
George Kitchens United_States 6.84
Godfrey Khotso-Mokoena South_Africa 8.02
Greg Rutherford Great_Britain 8.08
Henry Frayne Australia 7.95
Ignisious Gaisah Ghana 7.79
Li Jinzhe China 7.77
Lin Ching-Hsuan-Taipei China 7.38
Louis Tsatoumas Greece 7.53
Luis Rivera Mexico 7.42
Marcos Chuva Portugal 7.55
Marquise Goodwin United_States 8.11
Mauro-Vinicius da-Silva Brazil 8.11
Michel Torneus Sweden 8.03
Mitchell Watt Australia 7.99
Mohamed Fathalla-Difallah Egypt 7.08
Mohammad Arzandeh Iran 7.84
Ndiss Kaba-Badji Senegal 7.66
Povilas Mykolaitis Lithuania 7.61
Raymond Higgs Bahamas 7.76
Roman Novotny Czech-Republic 6.96
Salim Sdiri France 7.71
Sebastian Bayer Germany 7.92
Sergey Morgunov Russia 7.87
Stanley Gbagbeke Nigeria 7.59
Stepan Wagner Czech-Republic 7.5
Supanara Sukhasvasti Thailand 7.38
Tyrone Smith Bermuda 7.97
Vardan Pahlevanyan Armenia 6.55
Viktor Kuznyetsov Ukraine 7.5
Will Claye United_States 7.99
Zhang Xiaoyi China 7.25

您將數據對象存儲在std::vector

vector<Athlete> athletes {readAthletesFromFile()};

這樣將調用對象的析構函數並為您釋放所有內存(分配的相同std::vector )。 你會想繼續讓std::vector為你做這件事。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM