c++11相关特性

发现好多情况下都会用到c++11的新特性啊。

所以稍稍总结一下,只会粗略的说,不会详细的讲……

1.auto&decltype

c++11新增关键字,类型推导。

迭代器在之前必须写得很长,比如:

set<int>s;
set<int>::iterator it=s.begin();

而c++11只需写成:

auto it=s.begin();

 但auto只能对变量而不能对表达式进行类型推导,所以又引入了decltype关键字。

decltype只会推导表达式的类型而不会算出数值。

auto a=233,b=666;
decltype (a+b) c;

2.constexpr

常量表达式的修饰符。

可修饰常量和函数。

扫描二维码关注公众号,回复: 7427847 查看本文章

注意赋给常量的值必须是系统能够识别的,而不能是自定义的变量。

#include<bits/stdc++.h>
constexpr long long qwq(long long x){
    return x*x;
}
int main(){
    constexpr int a=1;
    return 0;
}
View Code

3.nullptr

空指针值,为了区分0和NULL。

因为NULL的本质是0,所以就算把NULL赋给int也不会报错,但nullptr就不行,因为它只代表空指针。

4.tuple

元组。

相当于高级的pair,成员可为任意个。

相关操作参考下面的代码。

#include<iostream>
#include<tuple>
using namespace std;
tuple<int,int,int>s=make_tuple(1,2,3);//make_tuple:制造元组
int main(){
    cout<<get<0>(s)<<" "<<get<1>(s)<<" "<<get<2>(s)<<endl;//get:得到元组中的某位元素
    int x,y,z;
    tie(x,y,z)=s;//tie:拆元组
    cout<<x<<" "<<y<<" "<<z<<endl;
    tuple<int,long long>w=make_tuple(5,4ll);
    auto ws=tuple_cat(w,s);//tuple_cat:合并元组
    cout<<get<0>(ws)<<" "<<get<1>(ws)<<" "<<get<2>(ws)<<" "<<get<3>(ws)<<" "<<get<4>(ws)<<endl;
    return 0;
}
View Code

5.哈希容器

c++11新增了一些基于Hash的容器:

unorder_map,unorder_set,unorder_mulitmap,unorder_nulitset。

性能比set,map等更优。

6.容器&数组遍历

只能说非常方便,甚至可以遍历map……

#include<bits/stdc++.h>
using namespace std;
vector<int>s;
int a[3];
int main(){
    a[0]=233,a[1]=666,a[2]=555;
    s.push_back(19240817),s.push_back(1e9+7),s.push_back(998244353);
    for(auto &x:s)cout<<x<<" ";
    puts("");
    for(int &x:a)cout<<x<<" ";
    puts("");
    return 0;
}
View Code

7.容器初始化

可以像数组一样对容器进行初始化,包括map(为什么又拿map开刀……)。

map<int,int>mp{{233,1},{521,2}};

8.Lamabda

匿名函数。

可以在使用时再定义函数,而不用费力起函数名。

如sort:

#include<bits/stdc++.h>
using namespace std;
int a[101];
int main(){
    srand(time(0));
    int n=100;
    for(register int i=1;i<=n;++i)a[i]=rand();
    sort(a+1,a+n+1,[](int skyh,int yxs){
        return skyh>yxs;
    });
    for(register int i=1;i<=n;++i)printf("%d ",a[i]);
    return 0;
}
View Code

用法很灵活,非常好的特性。然而我对它理解不是非常透彻

9.mt19937

C++11引入,基于Mersenne twister算法实现的高质量随机数。

得到的随机数在int范围内。

据说比rand()函数快,不过实测时mt19937比rand还要慢一些……

不过开O2后mt19973要快一些。

#include<random>
#include<cstdio>
using namespace std;
int main(){
    //freopen("1.in","w",stdout);
    mt19937 rd(time(NULL));
    int n=rd()%5+5,m=rd()%5+5;
    printf("%d %d\n",n,m);
    return 0;
}
View Code

10.尖括号

可能你在打代码的时候没有注意,但这也是c++11的特性。

>>不再只被认为是流。

vector<pair<int,int>>s;//是合法的

猜你喜欢

转载自www.cnblogs.com/remarkable/p/11619029.html