![](http://static.oschina.net/uploads/space/2013/1102/170625_3OfN_347414.jpg)
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
using namespace std;
/*int main()
{
int a;
a = 10;
cout<<" "<<a<<endl;
return 0;
}
*/
typedef struct com{
string id;
vector<string> subnode;
vector<string> clid;
set<string> nlid;
}comcross;
void init1(vector<comcross> &com_vec,map<string,vector<string> > &map_com);
void init2(vector<comcross> &com_vec, map<string,vector<string> > &map_com);
int main()
{
vector<comcross> com_vec;
map<string,vector<string> > map_com;
init1( com_vec,map_com);
init2( com_vec,map_com);
for(vector<comcross> ::iterator iter = com_vec.begin();iter != com_vec.end();++iter)
{
for(set<string> ::iterator iter1 = iter->nlid.begin();iter1 != iter->nlid.end();++iter1)
{
cout<<" "<<*iter1;
}
}
system("pause");
return 0;
}
void init1( vector<comcross> &com_vec,map<string,vector<string> > &map_com)
{
string A[] = {"1","2","3","4"};
string B[] = {"3","5","6","7"};
string C[] = {"7","8","9","10"};
string D[] = {"4","10","11","12"};
//初始化map_com
vector<string> tmp1(A,A+4),tmp2(B,B+4),tmp3(C,C+4),tmp4(D,D+4);
map_com["A"]=tmp1;
map_com["B"]=tmp2;
map_com["C"]=tmp3;
map_com["D"]=tmp4;
//初始化com_vec
comcross com;
com.id = "A";
string clid[]={"1","2","5","6","8","9","11","12"};
vector<string> tmp5(clid,clid+8);
com.clid = tmp5;
string subnode[] = {"B","C","D"};
vector<string> tmp6(subnode,subnode+3);
com.subnode = tmp6;
string nlid[] ={"1","2","3","4"};
vector<string> tmp7(nlid,nlid+4);
com.nlid.insert(tmp7.begin(),tmp7.end());
com_vec.push_back(com);
}
void init2(vector<comcross> &com_vec, map<string,vector<string> > &map_com)
{
vector<comcross>:: iterator iter = com_vec.begin();
for(;iter != com_vec.end();++iter)
{
for(vector<string>:: iterator subiter1 = iter->subnode.begin();subiter1 != iter->subnode.end();++subiter1)
{
string subnodekey = *subiter1;
map<string,vector<string> >::iterator mapit = map_com.find(subnodekey);
if(mapit!=map_com.end()){
iter->nlid.insert(mapit->second.begin(),mapit->second.end());
}
}
}
for(iter = com_vec.begin();iter != com_vec.end();++iter)
{
for(vector<string> ::iterator subiter = iter->clid.begin();subiter != iter->clid.end();++subiter)
{
iter->nlid.erase(*subiter);
}
}
}
输出:
1、为什么set输出不是顺序的呢????
C++ STL中标准关联容器set, multiset, map, multimap内部采用的就是一种非常高效的平衡检索二叉树:红黑树,也成为RB树(Red-Black Tree)。map和set的树建立之时就会自动排好序,
该set中字符串按照字典序排序,所以10排在3,4,7前面。。。
2、容器erase越界问题(Linux下segmentation fault(core dumped)问题)
容器erase操作之后返回下一个iterator,所以不要在循环内部做删除操作。
一般都是由内存访问越界造成的,不管是用户态程序还是内核态程序访问越界都会出core。
在linux下一般使用gdb进行调试,避免这种问题就是在编写程序时,使用规范的逻辑,和保证健壮性的判断
小测试:
#include<stdio.h>
int main()
{
int *p;
*p=12;
return 1;
}
在程序中对非法地址p进行写操作,执行程序时显示segmentation fault。
#include<stdio.h>
int main()
{
int *p, temp;
temp=*p;
return 1;
}
在程序中对p指向地址进行
非法读操作
,执行时显示segmentation fault。