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

本文介绍了一个使用C++实现的多线程示例,涉及互斥锁的使用来保护共享资源,展示了如何创建和使用智能指针以确保资源的有效管理。此外,还介绍了几种常用的数据结构操作,如向量的初始化、遍历及通过lambda表达式进行累加计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

书灯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值