AlgebraMaster

Modern C++ 创造非凡 . 改变世界

导航

C++ 11 snippets , 1

1->创建7个Thread,跑个非常大的循环.观察CPU

void func(string &name)
{
    for(auto i=0;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();

}
View Code

 

2->Mutex

static int globNum = 0;
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(1)));
    std::cout << " leaving thread ID  " << std::this_thread::get_id() << std::endl;
    globNum += 1;
    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 0;
}
View Code

 

3->

 

 

 

4->容器类

vector <int> test;
test.push_back(1);
test.push_back(2);
for(auto &e : test )
{
    cout << e <<endl;
}

 

5,memset,lambda

#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>

struct table
{
    int age;
    char name[20];
    int arr[4];
};


int main()
{

    char buffer[6]="hello";
    std::cout << "buffer is " << buffer <<std::endl;

    char buffer2[6] = "dest";
    memcpy(buffer,buffer2,4);
    std::cout << "after memcpy is " << buffer <<std::endl;

    memset(buffer,'*',strlen(buffer));
    std::cout << "after memset is " << buffer <<std::endl;


    int intBuffer[5] ={1,2,3,4,5};
    memset(intBuffer,0,sizeof(int)*5);
    for(const auto &n:intBuffer)
    {
        std::cout <<"memset int buffer" <<n << std::endl;
    }

    double doubleBuffer[5]={1.0,2.0,3.0,4.0,5.0};
    memset(doubleBuffer,0,sizeof(double)*5); // set all double buffer inside is 0
    for(const auto&n: doubleBuffer)
    {
        std::cout << "double buffer is " << n <<std::endl;
    }

    int a =10;
    int b =11;
    std::swap(a,b);
    std::cout << "A:" <<a <<" B:" <<b <<std::endl;


    table ta;
    ta.age = 1;
    strcpy(ta.name,"houdini");
    memset(ta.arr,0,sizeof(int)*4);

    table tb;
    tb.age = 2;
    strcpy(tb.name,"maya");
    memset(tb.arr,1,sizeof(int)*4);


    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(1);
    v.push_back(2);
    v.push_back(3);
    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+1;};
    std::cout << is_odd(2) <<std::endl;

    std::function<int(int)> func2 = [](int i) { return i+4; };
    std::cout << "func2: " << func2(6) << '\n';



    return 0;
}
View Code

 

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,1,2) <<std::endl;

   return 0;
}

 

 

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 = 0; 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(5,1,2,3,4,5);
    auto lm = [](int *p,int size)
    {
        for(int i=0;i<size;i++)
        {
            std::cout << p[i] <<std::endl;
        }
    };

    lm(p,5);
    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("1",2,3,4,5);
    show_list("1",2,3,4,5);
    return 0;
}
View Code

 

 

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(1,2) <<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,2) <<std::endl;
    std::cout << add<double>(1.01,2) <<std::endl;
    std::cout << add<float>(1.11f,2) <<std::endl;
    return 0;
}

 

2,显式模板定义,当返回值是模板,但是参数不是模板:

struct Data
{
    int val;
};
template <typename ValueType>
inline ValueType addOne(int val)
{
    std::cout << "go to addOne default template ";
    return ValueType(val) + ValueType(1);
}

template <>
inline float addOne<float>(int val)
{
    std::cout << "go to addOne <float> ";
    return float(val) + float(1);
}
template <>
inline Data addOne<Data> (int val)
{
    std::cout << "go to addOne <Data> struct";
    Data x;
    x.val = val + 1;
    return x;
}

inline std::ostream &operator<<(std::ostream &os,Data rh)
{
    os << rh.val <<std::endl;
    return os;
}




int main()
{
    Data x = {1};
    std::cout << addOne<int>(1) << std::endl; // default template
    std::cout << addOne<float>(1) <<std::endl;
    std::cout << addOne<Data>(1) <<std::endl;

    return 0;
}
View Code

 

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; //2
    test2.reset();
    // test2 can't access
    std::cout << test.use_count() <<std::endl; //1
    return 0;
}
View Code

 

 

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(1);
    list.push_back(2);
    list.push_back(3);

    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 0;
}
View Code

 

(2)自定义一个简单的CStringIter

class CStrIter
{
private:
    char **next;
public:
    CStrIter():next(0){
    }
    CStrIter(char **text)
    {
        next = text;
    }
    const char* operator*()
    {
        return *next;
    }
    CStrIter &operator++() // for ++it
    {
        next = next+1;
        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;
    }
    
}
View Code

 

(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 = 4;
    int app[size]= {1,3,4,2};
    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(0),mArrayIndex(0){

        }
        Iter(T *IterFirst):mHandle(IterFirst),mArrayIndex(0)
        {
            
        }
        Iter &operator=(T *data)
        {
            mHandle = data;
            return *this;
        }

        Iter& operator++() // for ++it
        {
            mHandle = mHandle+1;
            mArrayIndex += 1;
            return *this;
        }
        T &operator*()   // *it is our value
        {
            return *mHandle;
        }
        bool operator!=(T *data)
        {
            return mHandle != data ;
        }
        void next()
        {
            mHandle += 1;
            mArrayIndex +=1;
        }
        int index()const
        {
            return mArrayIndex;
        }
        
    private:
        T *mHandle;
        unsigned int mArrayIndex ;
    };

public:
    ourArray(int length)
    {
        mArray = new T[length + 1 ];
        for(int i=0;i<length;i++)
        {
            mArray[i] = T(i+1);
        }
        // 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(10);
    ourArray<float>::Iter iter;
    for(iter=array.begin();iter!=array.end();++iter)
    {
        cout << " INDEX: " <<iter.index() << " Of value: " <<*iter <<endl;
        
    }
    cin.get();
    return 0;

}
View Code

 

(4)

ostream_iterator,fill,copy

ostream_iterator <int,char> out_iter(cout,"\n");

    *out_iter++ = 15; //same as cout<<15 << "\n"
    *out_iter = 16;

    // STL copy vector to out_iter
    vector <int> data(6);
    fill(data.begin(),data.end(),1);        // 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";
View Code

istream_iterator

int val = 0;
    auto inputStr_iter = istream_iterator<int,char>(cin);
    val = *inputStr_iter;
    cout << "type value is " << val <<endl;
View Code

 copy

template <typename T>
void dpelement(T i)
{
    cout << "->" << i <<endl;
}
template<>
void dpelement<int>(int i)
{
    cout << "int ->" << i <<endl;
}



string s1[4] = {"good","wife","good","life"};
    vector<string> s1_t(4);
    copy(s1,s1+4,s1_t.begin());
    for_each(s1_t.begin(),s1_t.end(),dpelement<string>);


const int size = 4;
    int app[size]= {1,3,4,2};
    vector<int> dice(size);
    copy(app,app+size,dice.begin());
    for_each(dice.begin(),dice.end(),dpelement<int>);
View Code

 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(5,2);
    showContainerValue<list<int>,int>("one",one);

    int stuff[7] = {5,3,1,2,2,4,4};
    list<int> two;
    two.insert(two.begin(),stuff,stuff+7);
    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 0;
}
View Code

 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[6] = {1,2,1,3,2,4};
    set<int> unique_mapsA(nq_array,nq_array+6);
    set<int>::iterator start  = unique_mapsA.begin();
    unique_mapsA.insert(5);
    unique_mapsA.insert(6);
    unique_mapsA.insert(5);

    for(;start!=unique_mapsA.end();start++)
    {
        cout << *start <<endl;
    }

    set<int> unique_mapsB;
    unique_mapsB.insert(2);
    unique_mapsB.insert(3);

    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 0;
    
}
View Code

 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);
View Code

 

(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(213,"maya");
    codes.insert(item);
    codes.insert(mp(213,"houdini"));
    codes.insert(mp(110,"json"));
    printData(codes);


    // isolate 213 data
    cout << "\nisolate 213 data\n";
    pair<mm::iterator,mm::iterator> range = codes.equal_range(213);
    for(mm::iterator it = range.first; it!=range.second; ++it)
    {
        cout << (*it).first << "->"<<(*it).second <<endl;
    }
    cin.get();
    return 0;

}
View Code

 

 

 

 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(9);
    list<int> vals;
    vals.insert(vals.begin(),1);

    list<int>::iterator it = vals.begin(); // first element
    ++it;
    vals.insert(it,2);  // array [1,2]
    --it;
    vals.insert(it,2,10); // array [1,10,10,2]
    vals.insert(it,1,3);  // array [1,10,10,3,2]
    vals.insert(it,1,5);  // 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>(4));   // remove greater  4
    showArrayVals<list<int>,int>(vals,"after remove vals > 4 container");

    cin.get();
    return 0;
}
View Code

 

 

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>(0,"ADMIN"));
    ids.insert(pair<int,string>(0,"ADMIN2"));  // do not accept repeat key
    ids.insert(pair<int,string>(1,"SUPER"));
    ids.insert(pair<int,string>(2,"HOUDINI"));
    ids.insert(pair<int,string>(3,"NUKE"));

    ids[0] = "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 0;
}
View Code

 

 

 

11

posted on 2016-09-17 21:43  gearslogy  阅读(580)  评论(0编辑  收藏  举报