C++ 11 snippets , 1
1->创建7个Thread,跑个非常大的循环.观察CPU
- void func(string &name)
- {
- for(auto i=;i<0xFFFFFFFF;i++)
- {
- //cout << name << this_thread::get_id() << "running \n";
- }
- }
- int main()
- {
- string thread_01_name("AThread");
- string thread_02_name("BThread");
- string thread_03_name("CThread");
- string thread_04_name("DThread");
- string thread_05_name("EThread");
- string thread_06_name("FThread");
- string thread_07_name("HThread");
- thread thread_01(func,ref(thread_01_name));
- thread thread_02(func,ref(thread_02_name));
- thread thread_03(func,ref(thread_03_name));
- thread thread_04(func,ref(thread_04_name));
- thread thread_05(func,ref(thread_05_name));
- thread thread_06(func,ref(thread_06_name));
- thread thread_07(func,ref(thread_07_name));
- thread_01.join();
- thread_02.join();
- thread_03.join();
- thread_04.join();
- thread_05.join();
- thread_06.join();
- thread_07.join();
- }
2->Mutex
- static int globNum = ;
- mutex g_lock;
- void func()
- {
- g_lock.lock();
- std::cout << " going to in thread ID " << std::this_thread::get_id() << std::endl;
- std::this_thread::sleep_for((std::chrono::seconds()));
- std::cout << " leaving thread ID " << std::this_thread::get_id() << std::endl;
- globNum += ;
- g_lock.unlock();
- }
- int main()
- {
- std::thread t1(func);
- std::thread t2(func);
- std::thread t3(func);
- t1.join();
- t2.join();
- t3.join();
- cout << globNum << endl;
- return ;
- }
3->
4->容器类
- vector <int> test;
- test.push_back();
- test.push_back();
- for(auto &e : test )
- {
- cout << e <<endl;
- }
5,memset,lambda
- #include <iostream>
- #include <cstring>
- #include <algorithm>
- #include <vector>
- struct table
- {
- int age;
- char name[];
- int arr[];
- };
- int main()
- {
- char buffer[]="hello";
- std::cout << "buffer is " << buffer <<std::endl;
- char buffer2[] = "dest";
- memcpy(buffer,buffer2,);
- std::cout << "after memcpy is " << buffer <<std::endl;
- memset(buffer,'*',strlen(buffer));
- std::cout << "after memset is " << buffer <<std::endl;
- int intBuffer[] ={,,,,};
- memset(intBuffer,,sizeof(int)*);
- for(const auto &n:intBuffer)
- {
- std::cout <<"memset int buffer" <<n << std::endl;
- }
- double doubleBuffer[]={1.0,2.0,3.0,4.0,5.0};
- memset(doubleBuffer,,sizeof(double)*); // set all double buffer inside is 0
- for(const auto&n: doubleBuffer)
- {
- std::cout << "double buffer is " << n <<std::endl;
- }
- int a =;
- int b =;
- std::swap(a,b);
- std::cout << "A:" <<a <<" B:" <<b <<std::endl;
- table ta;
- ta.age = ;
- strcpy(ta.name,"houdini");
- memset(ta.arr,,sizeof(int)*);
- table tb;
- tb.age = ;
- strcpy(tb.name,"maya");
- memset(tb.arr,,sizeof(int)*);
- std::cout << "ta " <<ta.age << " " << ta.name <<std::endl;
- std::cout << "tb " <<tb.age << " " << tb.name <<std::endl;
- std::cout << "swap struct \n";
- std::swap(ta,tb);
- std::cout << "ta " <<ta.age << " " << ta.name <<std::endl;
- std::cout << "tb " <<tb.age << " " << tb.name <<std::endl;
- // [] define the lambda , () is the arg
- // [captures] (params) -> ret {Statments;}
- std::cout << "\nlambda \n";
- auto func = []() { std::cout << "Hello world"; };
- func(); // now call the function
- std::vector<int> v;
- v.push_back();
- v.push_back();
- v.push_back();
- std::for_each(std::begin(v), std::end(v), [](int n) {std::cout << n << std::endl;});
- std::cout << "Make a lambda function \n";
- auto is_odd = [](int n) {return n+;};
- std::cout << is_odd() <<std::endl;
- std::function<int(int)> func2 = [](int i) { return i+; };
- std::cout << "func2: " << func2() << '\n';
- return ;
- }
6,匿名指向函数指针:
- int printadd(int x,int y)
- {
- std::cout << "x y :" << x << " | " << y<<std::endl;
- return x+y;
- }
- int main()
- {
- typedef int (*callBack)(int x,int y);
- auto will_callBack = [](callBack callBackParm,int x,int y)
- {
- return callBackParm(x,y);
- };
- std::cout << will_callBack(printadd,,) <<std::endl;
- return ;
- }
7,变长参数,C和C++
C:
- int* AllocateArray(int count, ...)
- {
- int *p = static_cast<int*> (malloc(sizeof(int)*count));
- va_list args;
- va_start(args, count);
- for (int i = ; i < count; ++i)
- {
- int arg = va_arg(args, int);
- *(p+i) = arg;
- }
- va_end(args);
- return p;
- }
- void DestroyArray(int *p)
- {
- free(p);
- }
- int main()
- {
- int *p = AllocateArray(,,,,,);
- auto lm = [](int *p,int size)
- {
- for(int i=;i<size;i++)
- {
- std::cout << p[i] <<std::endl;
- }
- };
- lm(p,);
- DestroyArray(p);
- }
C++
- #include <iostream>
- using namespace std;
- // end of call for 0 parameters
- void show_list() {}
- // we just transfer the ref
- template <typename T>
- void show_list(const T &value)
- {
- cout << value <<" eof" << endl;
- }
- template <typename T ,typename... Args>
- void show_list(const T &value ,const Args&... args)
- {
- cout << value << ",";
- show_list(args...);
- };
- int main()
- {
- show_list("",,,,);
- show_list("",,,,);
- return ;
- }
8,模板函数.
基本概念:
(1):显式实例化(explicit instantiation)
template class ArrayTP<string,100> ;// generate ArrayTP<string,100> class
(2):显式具体化(explicit specialization)
- template<>
- class ClassName<specialized-type-name>
- {...}
(3):部分具体化(partial specialization)
- template <class T1,class T2>
- class Pair
- {
- //...
- };
- template <class T1>
- class Pair<T1,int>
- {
- //...
- };
当参数和模板都一致,类似以下形式:
1,
- template <typename T>
- inline T add(T x,T y)
- {
- return x+y;
- }
- int main()
- {
- std::cout << add(,) <<std::endl;
- std::cout << add(1.0f,2.0f) <<std::endl;
- //std::cout << add(1.0f,2) <<std::endl; //ERROR
- std::cout << add<int>(1.01,) <<std::endl;
- std::cout << add<double>(1.01,) <<std::endl;
- std::cout << add<float>(1.11f,) <<std::endl;
- return ;
- }
2,显式模板定义,当返回值是模板,但是参数不是模板:
- struct Data
- {
- int val;
- };
- template <typename ValueType>
- inline ValueType addOne(int val)
- {
- std::cout << "go to addOne default template ";
- return ValueType(val) + ValueType();
- }
- template <>
- inline float addOne<float>(int val)
- {
- std::cout << "go to addOne <float> ";
- return float(val) + float();
- }
- template <>
- inline Data addOne<Data> (int val)
- {
- std::cout << "go to addOne <Data> struct";
- Data x;
- x.val = val + ;
- return x;
- }
- inline std::ostream &operator<<(std::ostream &os,Data rh)
- {
- os << rh.val <<std::endl;
- return os;
- }
- int main()
- {
- Data x = {};
- std::cout << addOne<int>() << std::endl; // default template
- std::cout << addOne<float>() <<std::endl;
- std::cout << addOne<Data>() <<std::endl;
- return ;
- }
9,std::shared_ptr<> 智能指针.
- #include <iostream>
- #include <memory>
- #include <string>
- //template <typename Data>
- class Test
- {
- public:
- Test():mName("NULL NAME")
- {
- std::cout <<"Create Test\n";
- }
- Test(std::string name)
- {
- mName = name;
- }
- void printName()
- {
- std::cout << "name is : " << mName <<std::endl;
- }
- void setName(std::string name)
- {
- mName = name;
- }
- ~Test(){
- std::cout <<mName<< " Test destroyed\n";
- }
- //using Ptr = std::shared_ptr<Test>;
- typedef std::shared_ptr<Test> Ptr;
- private:
- std::string mName;
- };
- int main()
- {
- std::cout << "Hello, World!" << std::endl;
- Test::Ptr test(new Test("Houdini"));
- test->printName();
- Test::Ptr test2 = test;
- test2->setName("maya");
- test2->printName();
- std::cout << test2.use_count() <<std::endl; //
- test2.reset();
- // test2 can't access
- std::cout << test.use_count() <<std::endl; //
- return ;
- }
10,迭代器:
(1) 基于C++11 的forloop
- #include <iostream>
- #include <vector>
- #include <algorithm>
- using namespace std;
- void showValue(int x)
- {
- cout << x <<endl;
- }
- template <typename iter,typename func>
- func Navie_foreach(iter first,iter end,func f)
- {
- for(;first!=end;++first)
- {
- f(*first);
- }
- return std::move(f);
- };
- int main()
- {
- vector<int> list;
- list.push_back();
- list.push_back();
- list.push_back();
- cout << "use algorithm \n";
- for_each(list.begin(),list.end(),showValue);
- cout << "use my function \n";
- Navie_foreach(list.begin(),list.end(),showValue);
- cout << "use for(auto x: list) \n";
- for(auto x: list)
- {
- showValue(x);
- }
- return ;
- }
(2)自定义一个简单的CStringIter
- class CStrIter
- {
- private:
- char **next;
- public:
- CStrIter():next(){
- }
- CStrIter(char **text)
- {
- next = text;
- }
- const char* operator*()
- {
- return *next;
- }
- CStrIter &operator++() // for ++it
- {
- next = next+;
- return *this;
- }
- bool operator!=(void *data)
- {
- return *next != NULL;
- }
- };
- int main()
- {
- char *menu[]= {"Houdini","Maya",NULL};
- CStrIter iter(menu);
- for(; iter!=NULL;++iter)
- {
- cout << *iter <<endl;
- }
- }
(3)自定义一个简单的超尾迭代器
- #include <iostream>
- #include <iterator>
- #include <vector>
- #include <algorithm>
- using namespace std;
- template <typename T>
- void dpelement(T i)
- {
- cout << "->" << i <<endl;
- }
- template<>
- void dpelement<int>(int i)
- {
- cout << "int ->" << i <<endl;
- }
- void unit_test_foreach()
- {
- const int size = ;
- int app[size]= {,,,};
- vector<int> dice(size);
- copy(app,app+size,dice.begin());
- for_each(dice.begin(),dice.end(),dpelement<int>);
- }
- template <typename T>
- struct ourArray
- {
- public:
- class Iter
- {
- public:
- Iter():mHandle(),mArrayIndex(){
- }
- Iter(T *IterFirst):mHandle(IterFirst),mArrayIndex()
- {
- }
- Iter &operator=(T *data)
- {
- mHandle = data;
- return *this;
- }
- Iter& operator++() // for ++it
- {
- mHandle = mHandle+;
- mArrayIndex += ;
- return *this;
- }
- T &operator*() // *it is our value
- {
- return *mHandle;
- }
- bool operator!=(T *data)
- {
- return mHandle != data ;
- }
- void next()
- {
- mHandle += ;
- mArrayIndex +=;
- }
- int index()const
- {
- return mArrayIndex;
- }
- private:
- T *mHandle;
- unsigned int mArrayIndex ;
- };
- public:
- ourArray(int length)
- {
- mArray = new T[length + ];
- for(int i=;i<length;i++)
- {
- mArray[i] = T(i+);
- }
- // define a eof signals
- mArray[length] = 0xFFFFFFFF;
- _size = length;
- }
- ~ourArray()
- {
- delete []mArray;
- mArray = nullptr;
- }
- void clear()
- {
- delete []mArray;
- mArray = nullptr;
- }
- T *begin()
- {
- return mArray;
- }
- T *end()
- {
- return mArray+(_size);
- }
- int operator[](int i)
- {
- return mArray[i];
- }
- unsigned int size()const
- {
- return _size;
- }
- const Iter ConstIter()
- {
- ourArray<T>::Iter iter;
- iter = array.begin();
- return iter;
- }
- private:
- unsigned int _size;
- T *mArray;
- };
- int main()
- {
- ourArray<float> array();
- ourArray<float>::Iter iter;
- for(iter=array.begin();iter!=array.end();++iter)
- {
- cout << " INDEX: " <<iter.index() << " Of value: " <<*iter <<endl;
- }
- cin.get();
- return ;
- }
(4)
ostream_iterator,fill,copy
- ostream_iterator <int,char> out_iter(cout,"\n");
- *out_iter++ = ; //same as cout<<15 << "\n"
- *out_iter = ;
- // STL copy vector to out_iter
- vector <int> data();
- fill(data.begin(),data.end(),); // fill 1 to array
- copy(data.begin(),data.end(),out_iter); // print 1 six times
- cout << "\n";
- copy(data.begin(),data.end(),ostream_iterator<int,char>(cout,"->"));
- cout << "\n";
istream_iterator
- int val = ;
- auto inputStr_iter = istream_iterator<int,char>(cin);
- val = *inputStr_iter;
- cout << "type value is " << val <<endl;
copy
- template <typename T>
- void dpelement(T i)
- {
- cout << "->" << i <<endl;
- }
- template<>
- void dpelement<int>(int i)
- {
- cout << "int ->" << i <<endl;
- }
- string s1[] = {"good","wife","good","life"};
- vector<string> s1_t();
- copy(s1,s1+,s1_t.begin());
- for_each(s1_t.begin(),s1_t.end(),dpelement<string>);
- const int size = ;
- int app[size]= {,,,};
- vector<int> dice(size);
- copy(app,app+size,dice.begin());
- for_each(dice.begin(),dice.end(),dpelement<int>);
list
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <list>
- using namespace std;
- template <typename T>void showValue(T x)
- {
- cout << x <<endl;
- }
- template <typename container,typename valueType>
- void showContainerValue(const char*containerName, const container &con)
- {
- cout <<"------"<< containerName <<"------\n";
- for_each(con.begin(),con.end(),showValue<valueType>);
- cout <<"------"<< containerName <<"------\n\n";
- };
- int main()
- {
- list<int> one(,);
- showContainerValue<list<int>,int>("one",one);
- int stuff[] = {,,,,,,};
- list<int> two;
- two.insert(two.begin(),stuff,stuff+);
- showContainerValue<list<int>,int>("two",two);
- two.sort();
- showContainerValue<list<int>,int>("two after sort",two);
- two.unique();
- showContainerValue<list<int>,int>("two after unique",two);
- cin.get();
- return ;
- }
set,set_union,set_difference,set_intersection (set里的元素不会重复,即使插入重复的。,set会自动排序,所以有可能顺序跟insert顺序不一样)
- #include <set>
- #include <iostream>
- #include <algorithm>
- #include <iterator>
- using namespace std;
- int main()
- {
- int nq_array[] = {,,,,,};
- set<int> unique_mapsA(nq_array,nq_array+);
- set<int>::iterator start = unique_mapsA.begin();
- unique_mapsA.insert();
- unique_mapsA.insert();
- unique_mapsA.insert();
- for(;start!=unique_mapsA.end();start++)
- {
- cout << *start <<endl;
- }
- set<int> unique_mapsB;
- unique_mapsB.insert();
- unique_mapsB.insert();
- set<int> unique_mapsC;
- // set_union()
- // set_difference()
- // set_intersection()
- set_intersection(unique_mapsA.begin(),unique_mapsA.end(),unique_mapsB.begin(),unique_mapsB.end(),
- insert_iterator<set<int>>(unique_mapsC,unique_mapsC.begin()));
- set<int>::iterator cIter;
- cout << "set_intersection\n";
- for(cIter=unique_mapsC.begin();cIter!= unique_mapsC.end(); cIter++)
- {
- cout << *cIter <<endl;
- }
- cin.get();
- return ;
- }
set对ostream_iterator<int,char>out(cout,"\n")
- cout << "ostream_iterator print set data\n";
- ostream_iterator<int,char> out(cout,"\n");
- copy(unique_mapsB.begin(),unique_mapsB.end(),out);
(5)multimap,pair (multimap的key 可以是重复的)
包括如何取出重复的键元素
- #include <map>
- #include <string>
- #include <iostream>
- using namespace std;
- typedef multimap<int,string> mm;
- typedef pair<int,string> mp;
- template <typename T>
- void printData(T &cont)
- {
- auto iter = cont.begin();
- for(;iter!=cont.end();iter++)
- {
- cout << *iter <<endl;
- }
- }
- // specialize our multimap<int,string>
- template <>
- void printData<mm>(mm &cont)
- {
- auto iter = cont.begin();
- for(;iter!=cont.end();iter++)
- {
- cout << "key:"<<(*iter).first << " -> value:"<<(*iter).second <<endl;
- }
- }
- int main()
- {
- mm codes;
- mp item(,"maya");
- codes.insert(item);
- codes.insert(mp(,"houdini"));
- codes.insert(mp(,"json"));
- printData(codes);
- // isolate 213 data
- cout << "\nisolate 213 data\n";
- pair<mm::iterator,mm::iterator> range = codes.equal_range();
- for(mm::iterator it = range.first; it!=range.second; ++it)
- {
- cout << (*it).first << "->"<<(*it).second <<endl;
- }
- cin.get();
- return ;
- }
9,函数对象
list,list->insert(),list.remove_if()
- #include <iostream>
- #include <list>
- #include <algorithm>
- #include <iterator>
- template <typename T_C,typename valType>
- void showArrayVals(T_C &cont,const char* contName)
- {
- ostream_iterator<valType,char> out(cout,"\n");
- cout << "----------" << contName << "----------\n";
- for(auto iter = cont.begin();iter!=cont.end();iter++)
- {
- *out++ = *iter;
- }
- cout << "----------" << contName << "----------\n";
- }
- template <typename T>class TooBig
- {
- private:
- T cutoff;
- public:
- TooBig(const T&cut):cutoff(cut){
- }
- bool operator()(const T& v){return v>cutoff;}
- };
- using namespace std;
- int main()
- {
- TooBig<int> b100();
- list<int> vals;
- vals.insert(vals.begin(),);
- list<int>::iterator it = vals.begin(); // first element
- ++it;
- vals.insert(it,); // array [1,2]
- --it;
- vals.insert(it,,); // array [1,10,10,2]
- vals.insert(it,,); // array [1,10,10,3,2]
- vals.insert(it,,); // array [1,10,10,3,5,2]
- showArrayVals<list<int>,int>(vals,"vals container");
- vals.remove_if(b100); // remove greater 9
- showArrayVals<list<int>,int>(vals,"after remove vals > 9 container");
- vals.remove_if(TooBig<int>()); // remove greater 4
- showArrayVals<list<int>,int>(vals,"after remove vals > 4 container");
- cin.get();
- return ;
- }
10,STL string,map,set ,匿名函数
- #include <iostream>
- #include <string>
- #include <cctype>
- #include <iterator>
- #include <algorithm>
- #include <map>
- #include <set>
- using namespace std;
- template <typename T>
- void showMap(T &mm)
- {
- T::const_iterator iter;
- for(iter=mm.begin();iter!=mm.end();iter++)
- {
- cout << "Key:"<<(*iter).first << " val:" << (*iter).second <<endl;
- }
- }
- char chToLower(char ch){
- return tolower(ch);
- }
- string &StrToLower(string &st)
- {
- transform(st.begin(),st.end(),st.begin(),chToLower);
- return st;
- }
- // function convert map's value to a set,and convert to lower char
- template <typename T1,typename T2>
- void mapToSet(T1 &rhMap,T2 &rhSet)
- {
- T1::const_iterator iter;
- for(iter=rhMap.begin();iter!=rhMap.end();iter++)
- {
- string item = (*iter).second;
- StrToLower(item);
- rhSet.insert(item);
- }
- }
- // show container's value
- template<typename cont,typename valType>
- void showContainerValues(cont &cc)
- {
- //for_each(begin(cc), end(cc), [](valType n) {std::cout << n << std::endl;});
- for_each(cc.begin(),cc.end(),
- [](valType n) {std::cout << n << std::endl;}
- );
- }
- int main()
- {
- map<int,string> ids;
- ids.insert(pair<int,string>(,"ADMIN"));
- ids.insert(pair<int,string>(,"ADMIN2")); // do not accept repeat key
- ids.insert(pair<int,string>(,"SUPER"));
- ids.insert(pair<int,string>(,"HOUDINI"));
- ids.insert(pair<int,string>(,"NUKE"));
- ids[] = "MASTER"; // map can use [] anywhere
- showMap(ids);
- //
- cout << "\ninsert all map to set\n";
- set<string> wordset;
- mapToSet<>(ids,wordset);
- showContainerValues<set<string>,string>(wordset);
- cin.get();
- return ;
- }
11
C++ 11 snippets , 1的更多相关文章
- C++ 11 snippets , 2
<1>auto ,initializer_list<T>,auto指向函数指针的简易,和typdef 定义的类型执行函数指针有多复杂. #include <iostrea ...
- Visual Studio 2010 中的 Web 开发
概述 Microsoft Visual Studio 2010 为 ASP.NET Web 应用程序的开发提供非常多新的功能.这些新功能旨在帮助开发者高速方便地创建和部署质量高且功能全的 Web 应用 ...
- [OpenCV] Install OpenCV 3.4 with DNN
目标定位 一.开始全面支持 Tensorflow OpenCV3.4 新功能 当前最新进展OpenCV 3.4 dev:https://github.com/opencv/opencv/tree/ma ...
- 地区sql
/*Navicat MySQL Data Transfer Source Server : localhostSource Server Version : 50136Source Host : lo ...
- 25+ Useful Selenium Web driver Code Snippets For GUI Testing Automation
本文总结了使用Selenium Web driver 做页面自动化测试的一些 tips, tricks, snippets. 1. Chrome Driver 如何安装 extensions 两种方式 ...
- Java 9 揭秘(11. Java Shell)
Tips 做一个终身学习的人. 在本章节中,主要介绍以下内容: 什么是Java shell JShell工具和JShell API是什么 如何配置JShell工具 如何使用JShell工具对Java代 ...
- 11月26号host
127.0.0.1 localhost255.255.255.255 broadcasthost::1 localhostfe80::1%lo0 localhost # Google start216 ...
- 11月16host文件
#################################################################################################### ...
- c++ telescoping constructor is NOT supported until c++11
Telescoping constructor: see Effective Java 2nd Edition Item 2 If you want to use telescoping constr ...
随机推荐
- js 各种事件 如:点击事件、失去焦点、键盘事件等
事件驱动: 我们点击按钮 按钮去掉用相应的方法. demo: <input type="button" v ...
- ECharts基础
echarts: js引用:<script type="text/javascript" src="js/echarts.js"></scri ...
- ipv4转化为ipv6
十進制轉換成十六進位 IPV6為十六進位,所以十進制轉換成十六進位192=c0 168=a8192.168.1.1 轉成 16 進制為 c0.a8.01.01可以使用 Windows 工程版或是程式設 ...
- Hbase学习02
第2章 Apache HBase配置 本章在“入门”一章中进行了扩展,以进一步解释Apache HBase的配置. 请仔细阅读本章,特别是基本先决条件,确保您的HBase测试和部署顺利进行,并防止数据 ...
- java中用jdom创建xml文档/将数据写入XML中
import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; i ...
- Linux记录-使用python临时搭建web服务器
python2: python -m SimpleHTTPServer 8888 python3: python -m http.server 8888 wget ip:8888/文件
- Linux拉你入门
前言:为了做一个更优秀的程序猿,Linux是必不可少的,因此利用闲杂的时间来增加自己对Linux的认识 (一)关于Linux命令编(至于怎样安装vmvare这一个章节就先不介绍了) 1.基础命令 1. ...
- Understanding Favicon
Favicon 简介 Favicon : 是favorites icon 的缩写,被称为website icon . page icon. urlicon. 最初定义一个favicon的方法是将一个名 ...
- 让Windows Server 2008r2 IIS7.5 ASP.NET 支持10万并发请求
由于之前使用的是默认配置,服务器最多只能处理5000个同时请求,今天下午由于某种情况造成同时请求超过5000,从而出现了上面的错误. 为了避免这样的错误,我们根据相关文档调整了设置,让服务器从设置上支 ...
- 11-SQLServer的事务、存储过程和触发器
一. 事务 在SQLServer中,每条SQL语句,默认就是一条隐式的事务,但是如果我们需要一组SQL语句,那么就需要采用SQLServer提供的特有的标记 来声明事务的开始.提交和回滚了. 事务的开 ...