如何在地图中的现有元组中添加元组? [英] How to add a tuple to the existing tuples in map?

查看:71
本文介绍了如何在地图中的现有元组中添加元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为c的元组列表和一个名为map1的元组列表的映射。我想将列表的元组添加到地图中的特殊元素。例如,我想将元组{1,2}添加到map1 [0]。我写的代码如下:

I have a list of tuples named "c" and a map of list of tuples named "map1". i want to add the tuples of list to special elements in map. for example, i want to add tuple{1,2} to map1[0]. the code I wrote is as follow:

list<std::tuple<int, int>> l = list<std::tuple<int, int>>();
	auto it=c.begin();
	while(c.size()>k)
	{
		tuple<int, int> f=it._Ptr[0]._Myval;
		int seed=std::get<0>(f);
		int Dseed=std::get<1>(f);
	        Cmerge=find_nearest_group(Dseed);
		int Cnew= costof_new_group(Dseed,k);
		if(Cmerge<Cnew)
		{
			l.push_back(make_tuple(seed, Dseed));
			map1[PMerge] = l;
			c.remove(f);
		}
		else
		{
			create_new_group(seed,k);
			for(int i=0;i<k;i++)
			{				
				tuple<int, int> f=it._Ptr[0]._Myval;
			
				std::advance(it, 1);
				c.remove(f);
			}
		}
		
	}






问题是当while循环重复时,l清除并清除map中存在的元组并将新元组替换为map元素。例如,如果map1 [0]中存在元组是{3,2},{4,5]},并且在下一个重复中,l中的元组是{3,6},它将替换{3,2}和{在map1 [0]中有{3,6}的4,5}。但我想将新元组添加到旧元组中。我该如何解决这个问题呢?



我尝试了什么:



i将l列表定义为全局以避免被清除,但它没有帮助



the problem is when the while loop repeats, the "l" clears and it clears the tuples exist in map and replace the new tuple into the element of map. for example, if the tuples exist in map1[0] are {3,2},{4,5]} and in the next repeat the tuple in l is {3,6}, it replace {3,2} and {4,5} with {3,6} in map1[0]. but i want to add the new tuple to the old tuples. how can i resolve the problem?

What I have tried:

i defined the "l" list as global to avoid being clear, but it was not helpfull

推荐答案

我认为你的问题是语句 map1 [PMerge] = l; 。如果map1 [PMerge]已经有一个值,它会用新列表l替换该值。您不能对此问题使用下标表示法。你必须使用map :: find()和map :: insert()。



find()返回一个map元素的迭代器,它是一对< int,list>,或者返回end()。如果iterator == end(),则需要添加一对< int,list>到地图。如果iterator!= end(),它已经指向一对< int,list>。你需要将一个元组推到现有的列表中,由foundit->第二个给出。



I think your problem is the statement map1[PMerge] = l;. If map1[PMerge] already has a value, it replaces that value with your new list l. You can't use the subscript notation for this problem. You have to use map::find() and map::insert().

find() returns an iterator to a map element, which is a pair<int, list>, or it returns end(). If the iterator == end(), you need to add a pair<int, list> to the map. If the iterator != end(), it already points to a pair<int, list>. You need to push a tuple onto the existing list, given by foundit->second.

auto foundit = map1.find(PMerge);
if (foundit == map1.end())
{
    map1.insert(make_pair(PMerge, l));
}
else
{
    foundit->second.push_back(make_tuple(seed, Dseed));
}


这篇关于如何在地图中的现有元组中添加元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆