如何将结构名称更改为整数?

How can I change struct name to an integer?

本文关键字:整数 结构      更新时间:2023-10-16

我已经使用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;
} 

用户在此处输入其数据。我想以结构形式保存太多数据,所以我使用了"a"。根据我的说法,它必须计算1.age=(bla..(,3.age=(bla..( 请帮帮我。

我想你正在寻找类似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"]);

您还可以为每个员工提供另一个变量,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"),而使用地图时你写printInformation(employees["joe"]).你决定。