当我调用该函数来填充第二个类时,它只是以某种方式传递了它。不是调用函数 (fill()) 有错误,因为我是在遇到此问题后写的。代码贴在下面:
class Name_pairs {
public:
void read_names();
void read_ages();
void sort();
vector<string> names() const { return name; }
vector<double> ages() const { return age; }
private:
vector<string> name;
vector<double> age;
};
void Name_pairs::read_names() {
string s;
while(cin>>s) {
if(s == "|")
break;
name.push_back(s);
}
}
void Name_pairs::read_ages() {
double d;
while(cin>>d) {
if(d < 0)
break;
age.push_back(d);
}
}
void Name_pairs::sort() {
vector<string> dup_name = name;
vector<double> dup_age = age;
std::sort(name.begin(), name.end());
double buffer;
for(int i = 0; i < name.size(); i++) {
for(int ii = 0; ii < dup_name.size(); ii++) {
if(name[i] == dup_name[ii]) {
buffer = age[i];
age[i] = dup_age[ii];
break;
}
}
}
return;
}
void fill(Name_pairs& np)
{
np.read_names();
np.read_ages();
np.sort();
}
int main() try
{
Name_pairs test;
Name_pairs test1;
fill(test);
fill(test1);
return 0;
}