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 @   cogitoergosum  阅读(405)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示