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

-3 c++ vector push-back

我正在进行C++任务,并且在push_back方面存在一些错误问题.错误消息显示:

没有匹配的成员函数来调用'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;
}
Run Code Online (Sandbox Code Playgroud)

son*_*yao 5

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

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

book.emplace_back(name,number,email);
Run Code Online (Sandbox Code Playgroud)

或者您可以将其更改为使用支撑初始化程序(也是从C++ 11开始):

book.push_back( {name, number, email} );
Run Code Online (Sandbox Code Playgroud)

对于pre-C++ 11,您可以将其更改为phoneBook显式构造.

book.push_back( phoneBook(name, number, email) );
Run Code Online (Sandbox Code Playgroud)