如何让 push_back 在 C++ 程序中工作

How to get push_back to work in C++ program

我正在处理 C++ 作业,但遇到了一些关于 push_back 的错误问题。错误消息如下:

No matching member function for call to 'push_back'.

错误发生在以下行:book.push_back(name,number,email);

代码如下:

//Program

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

// Declaring ye ol' phonebook structure //
struct phoneBook {
public:
    string name;
    int number;
    string email;
};

int main(){
    // Declaring the VECTOR of the Phonebook
    vector<phoneBook>book;
    string fileName;
    //reading the file
    cout <<"Enter file name to read contacts: ";
    cin >> fileName;

    std::string myline;
    std::ifstream infile(fileName);
        while (std::getline(infile, myline))
    {
        std::istringstream iss(myline);
        string name;
        int number;
        string email;
        if(!(iss >> name >> number >> email)) {break;}
        //pushing into vector
        book.push_back(name,number,email);
    }

//reading extra contacts from user
    while(true){
        int choice;
        cout << "Do you want to add extra contact? If so, type 1. If not, type 2 to exit:";
        cin >> choice;
        if(choice == 1){
            string name;
            int number;
            string email;
            cout << "Enter name: ";
            cin >> name;
            cout << "Enter number: ";
            cin >> number;
            cout << "Enter email: ";
            cin >> email;
            book.push_back(name,number,email);
        }
        else{
            break;
        }
    }

    //printing phone book
    cout << "Contacts are here: " << endl;
    for(int i=0;i<book.size();i++){
        cout << book[i].name << ""<<book[i].number<< "" << book[i].email << endl;
    }
    return 0;
}

请注意,std::vector::push_back 只需要一个具有 vector 元素类型的参数,即 phoneBook

如果您想直接从参数构造元素(要添加),您可以使用 emplace_back (C++11 起),例如

book.emplace_back(name,number,email);

或者您可以将其更改为使用大括号初始化程序(也自 C++11 起):

book.push_back( {name, number, email} );

对于 C++11 之前的版本,您可以将其更改为显式构建 phoneBook

book.push_back( phoneBook(name, number, email) );