您的位置:首页 > 编程语言 > C语言/C++

c++11新特性的简单介绍

2017-09-08 16:24 323 查看
#include
#include
#include
#include
#include
#include
#include
#include

using std::cout;
using std::cin;
using std::endl;
using std::vector;
using std::string;
using std::for_each;
using std::shared_ptr;
using std::thread;

std::mutex g_mutex;

void my_thread1(int num, const string& str){
g_mutex.lock();
for(int i=0; i<10; i++){
cout << "num:" << num << ", name:" << str << endl;
}
g_mutex.unlock();
}

void my_thread2(){
int g_num = 20;
for (int i=0; i<10; i++){
cout << "num:" << g_num << endl;
}
}

int main(int argc,char * argv [ ]){
//类型推导
//auto自动根据初始化子的类型产生参数,首先应有被明确初始化的参数
vector myvec(3, 4);
for (auto itr = myvec.cbegin();itr != myvec.cend();itr++){
cout << *itr << endl;
}

int my_array[4] = {1,2,3,4};
for (auto &x : my_array){
x *= 2;
cout << x << endl;
}

//lambda函数,用[&]声明
vector someList(2, 5);
int total = 0;
int value = 10;
for_each(someList.begin(), someList.end(), [&, value](int x){
total += (x * value);
});
cout << total << endl;

//空指针nullptr
char *pc = nullptr;
char str[] = "hello world";
pc = str;
cout << pc << endl;

//通用智能指针
shared_ptr p_first(new double);
shared_ptr p_copy = p_first;
*p_copy = 21.1;
cout << *p_first << endl;

//c++11线程类std::thread,独占式互斥量std::mutex,允许超时的互斥量
int num = 1234;
string str_td = "qwer";
thread t(my_thread1,num,str_td);
thread t1(my_thread2);
t.join();
t1.join();

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息