菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
17
0

C++学习笔记1

原创
05/13 14:22
阅读数 18704

将最近工作中,方向转换比较快,经常一个季度做这个,一个季度做那个,遇到一些常用的C++语法,而记性不太好经常忘记,整理一下笔记,将一些自己喜欢用的语法记录下来,方便自己查阅。

 

 

map用法:
std::map<int, ststructInfo>::iterator iter = vec.begin();
for( , iter != vec.end(), iter++) {
  if(flage == iter->second.flage){
    pLarge = iter->second;
  }
}
std:map<int,string> personnel;
这样就定义了一个用int作为索引,并拥有相关联的指向string的指针.
为了使用方便,可以对模板类进行一下类型定义:

typedef map<int,CString> UDT_MAP_INT_CSTRING;
UDT_MAP_INT_CSTRING enumMap;
//数据的插入--第一种:用insert函数插入pair数据  
#include <map>  
#include <string>  
#include <iostream>   
using namespace std;  
int main()   
{  
    map<int, string> mapStudent;  
    mapStudent.insert(pair<int, string>(1, "student_one"));  
    mapStudent.insert(pair<int, string>(2, "student_two"));    
    map<int, string>::iterator iter;  
    for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)  
       cout<<iter->first<<' '<<iter->second<<endl;   
}  
//第二种:用insert函数插入value_type数据,下面举例说明  
#include <map>  
#include <string>   
#include <iostream>   
using namespace std;  
int main()   
{  
    map<int, string> mapStudent;  
    mapStudent.insert(map<int, string>::value_type (1, "student_one")); 
    mapStudent.insert(map<int, string>::value_type (2, "student_two"));     
    map<int, string>::iterator iter;   
    for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)   
       cout<<iter->first<<' '<<iter->second<<endl;   
}  
//第三种:用数组方式插入数据,下面举例说明    
#include <map>    
#include <string>   
#include <iostream>   
using namespace std;   
int main()   
{   
    map<int, string> mapStudent;  
    mapStudent[1] = "student_one";   
    mapStudent[2] = "student_two";  
    map<int, string>::iterator iter;   
    for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)  
        cout<<iter->first<<' '<<iter->second<<endl;  
}  


  以上三种用法,虽然都可以实现数据的插入,但是它们是有区别的,当然了第一种和第二种在效果上是完成一样的,用insert函数插入数据,在数据的 插入上涉及到集合的唯一性这个概念,即当map中有这个关键字时,insert操作是插入数据不了的,但是用数组方式就不同了,它可以覆盖以前该关键字对 应的值。

map临时保存数据时,调用一般设置保护锁,保证数据准确性:

 VOS_Mutex *m_mapIdMutex;

 

无序容器

C++11 引入了两组无序容器:
std::unordered_map/std::unordered_multimap 和 std::unordered_set/std::unordered_multiset。

无序容器中的元素是不进行排序的,内部通过 Hash 表实现,插入和搜索元素的平均复杂度为 O(constant)。

具体使用例子:

    m_msgHandlerMap["MariaWay"] = std::bind(&CSession::HandleCmd, this, 
        std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
class CSession{
public:
  int handleCmd(const Json::Value &root,  pLens &pt,  Json::Value &jsonRsp)
 
private:
  std::unordered_map<std::string, std::function<int(const Json::Value &root,  pLens &pt,  Json::Value &jsonRsp)>> m_msgHandlerMap;  //使用C++11特性模板,容器模板
}
 

发表评论

0/200
17 点赞
0 评论
收藏