gpt4 book ai didi

c++ - 用点c++递归地添加到 vector

转载 作者:行者123 更新时间:2023-11-30 02:05:50 26 4
gpt4 key购买 nike

我想做的是获取两个名字的输入,然后将其存储在数据库中。

例如,第一个名字永远是顾问,第二个名字永远是学生。

例子:

输入:

约翰·史蒂文

约翰·巴里

约翰·哈罗德

输出:

顾问:约翰

学生:史蒂文、巴里、哈罗德

我希望我的程序获取 John 并将他放入 vector 数据库的第一个条目中,然后我想要获取 Steven Barry 和 Harold 并将它们全部放入 vector 子项中。

到目前为止,我的代码只需要两名顾问和三名学生。但是,我希望能够针对用户想要输入的顾问和学生数量执行此操作。

根据我读到的内容,我猜测我可以递归地执行此操作,但不确定如何操作。

欢迎任何其他想法/建议。

到目前为止的代码:

#include<iostream>
#include<vector>
#include<string>
using namespace std;

struct node
{
string name;
node * parent;
vector<node*> children;

};


int main()
{
vector<node*> dataBase;
node *advisor, *student, *advisor2, *student2, *student3;
advisor = new node;
student = new node;
advisor2 = new node;
student2 = new node;
student3 = new node;

//Add a student to advisor 1
cin>>advisor->name>>student->name;
advisor->children.push_back(student);
dataBase.push_back(advisor);

//Add another student to advisor 1
cin>>student3->name;
advisor->children.push_back(student3);

//Add another advisor and add a student to him
cin>>advisor2->name>>student2->name;
advisor2->children.push_back(student2);
dataBase.push_back(advisor2);


for(int i=0; i<dataBase.size(); i++)
{
cout<<"Advisor:"<<endl;
cout<<dataBase[i]->name<<endl;
cout<<"Students:"<<endl;
for(int j=0; j<dataBase[i]->children.size(); j++)
{
cout<<dataBase[i]->children[j]->name<<endl;
}
}

system("pause");
return 0;
}

最佳答案

更直接的方法是使用 vector 映射。

map<string, vector<string> > students_of_advisor;
while (cin) {
cin >> advisor >> student;
students_of_advisor[advisor].push_back(student);
}

然后你就可以打印了。

for(auto iter=students_of_advisor.begin();
iter != students_of_advisor.end();
++iter)
{
cout<<"Advisor:"<<endl;
cout<<iter->first<<endl;
cout<<"Students:"<<endl;
for(unsigned j=0; j != iter->second.size(); ++j)
{
cout << iter->second[j] << endl;
}
}

关于c++ - 用点c++递归地添加到 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9353725/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com