为什么我会"No viable conversion from 'vector<Country>' to 'int'"?

Why am I getting "No viable conversion from 'vector<Country>' to 'int'"?

本文关键字:Country lt gt to int vector viable No conversion from 为什么      更新时间:2023-10-16

我真的不确定为什么会收到这个错误。我试过用谷歌搜索,但没有得到最好的结果。。。如果有人能告诉我为什么我会出现这个错误:

No viable conversion from 'vector<Country>' to 'int'

int main()
{
    vector<Country> readCountryInfo(const string& filename);
    // Creating empty vector
    vector<Country> myVector;
    // Opening file
    ifstream in;
    in.open("worldpop.txt");
    if (in.fail()) {
        throw invalid_argument("invalid file name");
    }
    while (in) {
        char buffer; // Character buffer
        int num; // Integer to hold population
        string countryName; // Add character buffer to create name
        while (in.get(buffer)) {
            // Check if buffer is a digit
            if (isdigit(buffer)) {
                in.unget();
                in >> num;
            }
            // Check if buffer is an alphabetical character
            else if (isalpha(buffer) || (buffer == ' ' && isalpha(in.peek()))) {
                countryName += buffer;
            }
            // Checking for punctuation to print
            else if (ispunct(buffer)) {
                countryName += buffer;
            }
            // Check for new line or end of file
            else if (buffer == 'n' || in.eof()) {
                // Break so it doesn't grab next char from inFile when running loop
                break;
            }
        }
        Country newCountry = {countryName, num};
        myVector.push_back(newCountry);
    }
    return myVector;
}

上面写着

int main()

main返回一个int,因为标准要求它返回。

然后,在最后,你说

return myVector;

myVector是不能转换为intvector<Country>
因此出现了错误消息。

我怀疑,根据的声明

vector<Country> readCountryInfo(const string& filename);

对于确实返回vector<Country>的函数,您本打算在名为"readCountryInfo"的函数中编写代码,但不知怎的,却把它写错了地方。

int main()应该返回int,而不是myVector(代码的最后一行)。

在c++中,main返回一个int,通常为零。