TBB concurrent_hash_map基本用法
#include<map>
#include<string>
#include<vector>
#include<fstream>
#include<iostream>
#include <tbb/concurrent_hash_map.h>
using namespace std;
int main () {
tbb::concurrent_hash_map<std::string, std::vector<int>> hashMap;
std::vector<std::string> key = {"xiao", "ming"};
std::vector<std::vector<int>> val = {{1,2,3,4},{5,6,7,8}};
for(int i = 0; i < 2; ++i){
tbb::concurrent_hash_map<std::string, std::vector<int>>::value_type hashMapValuePair(key[i], val[i]);
hashMap.insert(hashMapValuePair);
}
for(tbb::concurrent_hash_map<std::string, std::vector<int>>::iterator iterator1 = hashMap.begin();
iterator1 != hashMap.end(); ++iterator1 ){
cout << "key : " << iterator1->first << endl;
cout << "value : {";
for(auto &ite : iterator1->second){
cout<< ite << ",";
}
cout << "}" << endl;
}
cout << "hashMap size = " << hashMap.size() << endl;
tbb::concurrent_hash_map<std::string, std::vector<int>>::const_accessor hashAccessor;
if(hashMap.find(hashAccessor,"xiao")){
cout << "find : " << endl;
cout << "key : " << hashAccessor->first << endl;
cout << "value : {";
for(auto &ite : hashAccessor->second){
cout<< ite << ",";
}
cout << "}" << endl;
}
if(hashMap.erase(hashAccessor)){
cout << "the number of hashMap after delete : " << hashMap.size() << endl;
}
}
输出结果
key : xiao
value : {1,2,3,4,}
key : ming
value : {5,6,7,8,}
hashMap size = 2
find :
key : xiao
value : {1,2,3,4,}
the number of hashMap after delete : 1
简化一点的代码
#include<map>
#include<string>
#include<vector>
#include<fstream>
#include<iostream>
#include <tbb/concurrent_hash_map.h>
using namespace std;
typedef tbb::concurrent_hash_map<std::string, std::vector<int>> HashMap;
typedef typename HashMap::const_accessor HashMapConstAccessor;
typedef typename HashMap::accessor HashMapAccessor;
typedef typename HashMap::iterator HashMapIterator;
typedef HashMap::value_type HashMapValuePair;
int main () {
HashMap hashMap;
std::vector<std::string> key = {"xiao", "ming"};
std::vector<std::vector<int>> val = {{1,2,3,4},{5,6,7,8}};
for(int i = 0; i < 2; ++i){
HashMapValuePair hashMapValuePair(key[i], val[i]);
hashMap.insert(hashMapValuePair);
}
for(HashMapIterator iterator1 = hashMap.begin(); iterator1 != hashMap.end(); ++iterator1 ){
cout << "key : " << iterator1->first << endl;
cout << "value : {";
for(auto &ite : iterator1->second){
cout<< ite << ",";
}
cout << "}" << endl;
}
cout << "hashMap size = " << hashMap.size() << endl;
HashMapConstAccessor hashAccessor;
if(hashMap.find(hashAccessor,"xiao")){
cout << "find : " << endl;
cout << "key : " << hashAccessor->first << endl;
cout << "value : {";
for(auto &ite : hashAccessor->second){
cout<< ite << ",";
}
cout << "}" << endl;
}
if(hashMap.erase(hashAccessor)){
cout << "the number of hashMap after delete : " << hashMap.size() << endl;
}
}