C++ vector 使用笔记

map 插入 vector 

#include <string>   

#include <iostream>   

#include <algorithm>   

#include <map>   

#include <vector>   

using namespace std;   

typedef map<string, string> STRING2STRING;   

typedef std::map<string, vector<string > > STRING2VECTOR;   

 

int main()   
{   

    std::map<string, string > map_test;   

    map_test.insert(STRING2STRING::value_type("2001", "test1"));   
    map_test.insert(STRING2STRING::value_type("2005", "test5"));   

    map<string, string>::const_iterator map_conitor = map_test.begin();   
    for(; map_conitor!= map_test.end(); map_conitor++)   
    {   

        cout<<map_conitor->first<<"  "<<map_conitor->second<<endl;      
    }   


    

    map<int, vector<string> > m_map; 


    vector<string> m_vec;
    m_vec.resize(2);

    m_vec[0] = "aaaaa";
    m_vec[1] = "bbbbb";
    // m_vec.clear();
    // cout<<m_vec[0]<<endl;


    m_map[0] = m_vec;
    if(m_map[0].empty()) { cout<<"not push_back can not assignment"<<endl;}
   
    cout<<m_map[0][1]<<endl;




    //  push_back 方式
    vector<string> m_vecPush;
    m_vecPush = m_map[0];
    cout<<"assignment m_vecPush:"<<m_vecPush[0] <<endl;



    map<int, vector<string> > m_mapPush;
    m_vecPush.resize(2);

    m_vecPush.push_back("aaaaa");
    m_vecPush.push_back("bbbbb");

    
    //  m_mapPush[0] = m_vecPush;   与 m_mapPush.insert 等价
    m_mapPush.insert(pair<int,vector<string> >(0,m_vecPush));  




   if(m_mapPush[0].empty()) { cout<<"push_back can not assignment"<<endl;}
    cout<<m_mapPush[0][1]<<endl;



    // m_mapPush[dev_id].empty()  与  m_mapPush.find(dev_id) == m_mapPush.end() 类似
    if(m_mapPush[2].empty()) {
        cout<<"m_mapPush empty way  not exits"<<endl;
    }

    if(m_mapPush.find(1) == m_mapPush.end()) {
        cout<<"m_mapPush find way  not exits"<<endl;
    }




    /////////////////////////// vector 清空元素  ///////////////////////////////
     // 清空元素,不回收空间
    m_vecPush.clear(); 
    cout<<"clear vector size:"<<m_vecPush.capacity()<<endl;
    // 清空元素并释放空间
    m_vecPush.clear(); 
    vector<string>().swap(m_vecPush);
    cout<<"swap vector size:"<<m_vecPush.capacity()<<endl;


















 }

 

 之前在开发板上使用

m_vec[0] = "aaaaa"; 这种方式,然后用 m_map[0] = m_vec; 发现m_vec赋值不成功。要用m_vec.push_back("aaaa")这种方式才能赋值给map。 但在台式linux上不存在这种情况。

 

posted @ 2017-03-22 15:43  cogitoergosum  阅读(402)  评论(0编辑  收藏  举报