本文介绍了地图,但仅给出一行值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好
我正在使用网络模拟器(ns2)进行c ++,但是我在c ++中是一个全新的人.
我想读取每个节点的数据并保存在map中.我没有使用数组,因为到那时将不会读取所有节点;数据的大小未知.

我发出这样的命令

Hello
I''m doing c++ with network simulator(ns2)but I''m totally new in c++.
I want to read data for each node and keep in map.I didn''t use array as all nodes will not be read for that time;the size of data is not known.

I give a command like this

void Update(){
		int q=0.5;
		int NodeId=ra_addr ;
		CurNode= (MobileNode*) (Node::get_node_by_address(ra_addr_));
		map_table(NodeId,iEnergy );
		}

void map_table(int node_id,double Eg){
	map<int, double > mymap;
	map<int, double > ::iterator it;
	it=mymap.find(node_id);
	if(it == mymap.end())mymap.insert(map<int,double>::value_type(node_id,Eg));
        else mymap[node_id]=Eg;
        for( map<int, double > ::iterator ii=mymap.begin(); ii!=mymap.end(); ii++)
	   {
	       cout << (*ii).first << ": " << (*ii).second << endl;
	   }




当我打印时,它只包含一个node_id,不是全部.我的想法是检查id是否在地图中,更新新数据,例如,我尝试在头文件中声明map也给出相同的结果. br/>
结果应该像
节点||数据
1 3.45
2 4.25
6 1.23


预先谢谢你
pare




when i print,it contain only one node_id,not all.My idea is to check id if it''s in the map,update a new data,Eg.i try to declare map in header file also give the same result.

the result should be like
node || data
1 3.45
2 4.25
6 1.23


thank you in advance
pare

推荐答案

#include <iostream>
#include <map>

using namespace std;

map<int, double> mymap;

void map_table(int node_id, double Eg)
{
	map<int, double>::iterator it = mymap.find(node_id);
	if(it == mymap.end())
		mymap.insert(map<int,double>::value_type(node_id,Eg));
	else
		mymap[node_id]=Eg;

	for(map<int, double>::iterator i = mymap.begin(); i != mymap.end(); ++i)
	{
		cout << (*i).first << ": " << (*i).second << endl;
	}
}

int main()
{
	map_table(1, 40.0);
	cout << "---------------------------" << endl;
	map_table(2, 42.0);
	cout << "---------------------------" << endl;
	map_table(1, 43.0);
	cout << "---------------------------" << endl;
	map_table(3, 40.0);

	return 0;
}



打印:



That prints:

1: 40
---------------------------
1: 40
2: 42
---------------------------
1: 43
2: 42
---------------------------
1: 43
2: 42
3: 40



希望这会有所帮助,
弗雷德里克(Fredrik)



Hope this helps,
Fredrik


print data in map
0: 190.809
1: 91.8829
4: 58.4821
 print data in map
1: 91.8829
2: 2.40965
3: 276.987
4: 58.4821
 print data in map
0: 190.809
2: 2.40965
3: 276.987
4: 58.4821
 print data in map
0: 190.809
1: 91.8829
3: 276.987



似乎缺少一些ID.



seems like some id is missing.



这篇关于地图,但仅给出一行值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 05:59