將最近作業中,方向轉換比較快,經常一個季度做這個,一個季度做那個,遇到一些常用的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特性模板,容器模板 }轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/243449.html
標籤:C++
上一篇:求助:Runtime Error:Segmentation fault,但是沒有發現大佬說的陣列開得太小或者指標例外的問題。
下一篇:Linux行程創建之fork淺析
