如何让push#u回到C++;程序 我正在研究C++赋值,并且在PuxEnPress中存在一些问题。错误消息如下:
没有匹配的成员函数用于调用“push_back” 错误发生在以下行:如何让push#u回到C++;程序 我正在研究C++赋值,并且在PuxEnPress中存在一些问题。错误消息如下:,c++,vector,push-back,C++,Vector,Push Back,没有匹配的成员函数用于调用“push_back” 错误发生在以下行:book.push_back(姓名、号码、电子邮件) 代码如下: //Program #include <fstream> #include <iostream> #include <sstream> #include <string> #include <vector> using namespace std; // Declaring ye ol' phone
book.push_back(姓名、号码、电子邮件)代码>
代码如下:
//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;
//声明“电话簿”结构//
结构电话簿{
公众:
字符串名;
整数;
字符串电子邮件;
};
int main(){
//声明电话簿的向量
矢量书;
字符串文件名;
//读取文件
cout文件名;
std::字符串myline;
std::ifstream infle(文件名);
while(std::getline(infle,myline))
{
std::istringstream iss(myline);
字符串名;
整数;
字符串电子邮件;
如果(!(iss>>姓名>>号码>>电子邮件){break;}
//推进向量
预订。推回(姓名、号码、电子邮件);
}
//从用户处读取额外联系人
while(true){
智力选择;
选择;
如果(选项==1){
字符串名;
整数;
字符串电子邮件;
姓名;
数量;
cout>电子邮件;
预订。推回(姓名、号码、电子邮件);
}
否则{
打破
}
}
//打印电话簿
cout注意,只需要一个参数具有向量
元素的类型,即电话簿
如果您希望直接从参数构造元素(要添加),您可以使用(因为C++11),例如
book.emplace_back(name,number,email);
或者您可以将其更改为使用大括号初始值设定项(也是从C++11开始):
对于C++11之前的版本,您可以将其更改为显式构造电话簿
book.push_back( phoneBook(name, number, email) );
push_back
只有一个参数,很容易通过引用进行验证。您可以传递三个参数。欢迎使用Stack Overflow。请花时间阅读并参考您可以在此处询问的内容和方式。push_back(电话簿{name,number,email})可能有效你必须创建一个新的phoneBook实例,并将单个变量推回到向量中。谢谢,宋元耀!我使用了“book.push_back({name,number,email});这个程序很有效。这很有趣,因为我去cplusplus.com检查了push_back的格式,它没有提到有花括号。你让我免于数小时的挣扎。再次感谢!@JohnSmith好吧,这是从C++11引入的一个功能,不仅用于std::vector::push_back
。请参阅(#)(7))更多细节。
book.push_back( phoneBook(name, number, email) );