我一直在使用struct一段时间,但我总是有问题。看这个例子: - `
#include <iostream>
struct Employee
{
short id;
int age;
double wage;
};
void printInformation(Employee employee)
{
std::cout << "ID: " << employee.id << "\n";
std::cout << "Age: " << employee.age << "\n";
std::cout << "Wage: " << employee.wage << "\n";
}
int main()
{
Employee joe = { 14, 32, 24.15 };
Employee frank = { 15, 28, 18.27 };
// Print Joe's information
printInformation(joe);
std::cout << "\n";
// Print Frank's information
printInformation(frank);
return 0;
}`
此代码完全正常,但何时我将使用字符串而不是“Joe”和“Frank”。我试过但失败了。 这是我工作的代码。
'#include <bits/stdc++.h>
using namespace std;
struct People{
string name;
int id;
int age;
int wage;
};
int main(){
string iname;
int iid = 0;
int iage;
int iwage;
while(1){
iid++;
cout << "ID No." << iid << endl <<"Enter Name";
std::getline(std::cin,iname);
cout << "Enter your Age:-";
cin >> iage;
cout << "Enter your Wage :-";
cin >> iwage;
cout << "See your details."<<endl <<"Name"<<iname<< endl<< "ID."<< iid <<
endl << "Age" << iage << endl<< "Wage" << iwage << endl;
People a = static_cast<People>(iid);
People a={iname,iid,iage,iwage};
std::cout << "Name:" << a.name << "\n";
std::cout << "ID: " << a.id << "\n";
std::cout << "Age: " << a.age << "\n";
std::cout << "Wage: " << a.wage << "\n";
}
return 0;
}
此处用户输入其数据。我想以struct的形式保存太多数据,所以我用'a'。根据我,它必须计算1.age =(bla ..),3.age =(bla ..) 请帮帮我。
答案 0 :(得分:4)
我认为你正在寻找类似std :: map
的东西http://en.cppreference.com/w/cpp/container/map
示例:
std::map<std::string, Employee> employees;
Employee joe = { 14, 32, 24.15 };
employees["joe"] = joe;
printInformation(employees["joe"]);
答案 1 :(得分:0)
您还可以为每个员工<div id="navbarContentHamburger">
<svg width="25" height="25">
<path d="M0,5 50,5" stroke="#fff" stroke-width="3"/>
<path d="M0,10 50,10" stroke="#fff" stroke-width="3"/>
<path d="M0,15 50,15" stroke="#fff" stroke-width="3"/>
</svg>
</div>
提供另一个变量,然后将员工存储在一个向量中,然后在函数循环中通过员工,直到找到具有该名称的员工:
string name;
我认为它比使用地图更好,因为你只需要写#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Employee{
string name;
short id;
int age;
double wage;
};
vector<Employee> Employees;
void printInformation(string employee){
for(int i = 0; i < Employees.size(); i++){
if(Employees[i].name == employee){
cout << "Name: " << Employees[i].name << "\n";
cout << "ID: " << Employees[i].id << "\n";
cout << "Age: " << Employees[i].age << "\n";
cout << "Wage: " << Employees[i].wage << "\n";
}
}
}
int main(){
Employee joe = {"joe", 14, 32, 24.15 };
Employee frank = {"frank", 15, 28, 18.27 };
Employees.push_back(joe);
Employees.push_back(frank);
printInformation("joe");
printInformation("frank");
return 0;
}
,当你使用地图时你写printInformation("joe")
。你决定了。