C++中map实现一对多的关系

因为map原本为1对1的映射,即需要借助其他的容器来实现1对多的关系;这里使用vector

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

map<string, vector<string> > res;
int main()
{
	//1 对 3 的关系
	string str1;
	cin >> str1;

	for (int i = 0; i < 3; i++)
	{
		string str;
		cin >> str;
		res[str1].push_back(str);
	}


	for (int i = 0; i < res[str1].size(); i++)
		cout << res[str1][i] << endl;
	system("pause");
	return 0;
}

 


版权声明:本文为maniac_ran原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。