引用方式访问STL容器潜在隐患


map<int , vector<int> >& iMap;

如果用引用访问vector里的元素,必须分配内存先,而且分配不够会数据丢失;push_back则不会存在这个问题。


示例代码:

#include <iostream>
#include <vector>
#include <map>
using namespace std;
void fun_print(map<int , vector<int> >& iMap,int flag , const char* str = "null"){
        cout<<str<<endl;
        cout<<"*******"<<endl;
        for(int i = flag; i <iMap.size(); i++){
                vector<int>& ap = iMap[i];
                cout<<"\tlist["<<i<<"],";
                cout<<"list_size="<<ap.size()<<"_\t";
                for(int j = 0; j<ap.size(); j++)
                        cout<<ap[j]<<"\t";
                cout<<endl;
        }
}
int main()
{
        int flag = 0;
        cout<<"___________________________"<<endl;
        map<int,vector<int> > iMap;
        iMap[0].push_back(1);                                                                                                                        
        fun_print(iMap,flag,"push_back");

        flag++;
        cout<<"___________________________"<<endl;
        iMap[1].reserve(2);
        fun_print(iMap,flag,"reserve_2");	//size = 0
        iMap[1].push_back(10);	//size = 1
        fun_print(iMap,flag,"push_back_1");
        iMap[1].push_back(12);	//size = 2
        iMap[1].push_back(15);`//size = 3
        fun_print(iMap,flag,"cout");

        flag++;
        cout<<"___________________________"<<endl;
        iMap[2].resize(2);
        fun_print(iMap,flag,"resize_2");
        iMap[2][0]= 20;	//size = 2
        fun_print(iMap,flag,"[x][0]");
        iMap[2][1]= 22;	//size = 2
        iMap[2][2]= 24;	//size = 2,这个数据丢失
        fun_print(iMap,flag,"resize");
        
        flag++;
        cout<<"___________________________"<<endl;                                                                                                   
        vector<int>& tpp = iMap[3];
        tpp.push_back(1);
        tpp[0] = 30;	//size = 1,如果上行不push_back,会core! => Segmentation fault (core dumped)
        tpp[1] = 31;	//size = 1,这个数据丢失!
        fun_print(iMap,flag,"push_back&[x]");

        flag++;
        cout<<"___________________________"<<endl;
        iMap[4].resize(2);
        int& app = iMap[4][0];
        app = 42;	//size = 2,第二个数:默认构造0
        fun_print(iMap,flag,"resize&[x][x]");
        cout<<"___________________________"<<endl;
        return 0;
}
运行结果:




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值