写这个小程序主要是想要测试如何使用hash_map进行数据统计,工作中的实际问题是需要将pcap文件中的所有数据包按照数据流四元组<源IP,目的IP,源Port,目的Port>进行统计
// Author: HSW
// Date: 2016/5/15
//
#include <iostream>
#include <string>
#include <vector>
#include <hash_map>
using namespace std;
int main()
{
hash_map<int, vector<string*>*> IntHashMap;
vector<string*>* TmpVector;
vector<string> MapKey1;
vector<string> MapKey2;
MapKey1.push_back("str1");
MapKey1.push_back("str2");
MapKey1.push_back("str1");
MapKey1.push_back("str2");
MapKey1.push_back("str1");
MapKey1.push_back("str2");
MapKey2.push_back("str1_1");
MapKey2.push_back("str2_1");
MapKey2.push_back("str1_2");
MapKey2.push_back("str2_2");
MapKey2.push_back("str1_3");
MapKey2.push_back("str2_3");
typedef pair<int, vector<string*>* > Makepair;
vector<string>::iterator iter1, iter2;
hash_map<int, vector<string*>*>::iterator HashMapiter;
vector<string*>::iterator pvectoriter;
int HashKey;
for (iter1 = MapKey1.begin(), iter2 = MapKey2.begin(); iter1 != MapKey1.end(); ++iter1, ++iter2)
{
HashKey = hash_value(*iter1);
if ((HashMapiter = IntHashMap.find(HashKey))!= IntHashMap.end())
{
(*(*HashMapiter).second).push_back(&(*iter2));
}
else
{
TmpVector = new vector<string*>;
(*TmpVector).push_back(&(*iter2));
IntHashMap.insert(Makepair(HashKey, TmpVector));
}
}
for (HashMapiter = IntHashMap.begin(); HashMapiter != IntHashMap.end(); ++HashMapiter)
{
TmpVector = (*HashMapiter).second;
cout << "对应键值 = " << (*HashMapiter).first << endl;
for (pvectoriter = (*TmpVector).begin(); pvectoriter != (*TmpVector).end(); ++pvectoriter)
{
cout << *(*pvectoriter) << "\t\t\t";
}
cout << endl;
}
system("pause");
return 0;
}
运行截图如下: