C++11特性--基于范围的for循环,新的STL容器,新的STL方法( cbegin(),cend(),crbegin(),crend())

来源:互联网 发布:电脑超频软件 编辑:程序博客网 时间:2024/05/01 12:31
1.模板和STL方面的修改
(1)基于范围的for循环
   *对于内置数组以及包含方法begein()和end()的类合和STL容器,基于范围的for循环可简化为它们编写循环的工作
   *如果要在循环中修改数组或容器的每个元素,可使用引用类型
  Example:
  int main()
{
int arr[]{1,2,3};
for(auto x:arr)
{
cout<<x<<ends;
}

cout<<endl;

for(auto &x:arr)
{
x=0;
}

for(auto x:arr)
{
cout<<x<<ends;
}

return 0;
}



output:
1 2 3
0 0 0



 (2)新的STL容器
      *array模板,可以指定元素类型和固定的元素个数,虽然长度固定,
       但是,因为array包含begin()和end(),使得array对象能使用于众多基于范围的STL算法
    Example:
    int main()
{
array<int,5> arr{1,3,5,4,2};
sort(arr.begin(),arr.end());
for(auto x:arr)
{
cout<<x<<ends;
//1 2 3 4 5
}

return 0;
}


   *forward_list,unordered_map,unordered_multimap,unordered_set,unordered_multiset
    其中forward_list是一种单链表,只能沿着一个方向遍历,其余四种都是使用哈希表实现的。


 (3)新的STL方法
      cbegin(),cend(),crbegin(),crend()分别是的begin(),end(),rbegin(),rend()的const版本
    Example:
   int main()
{
forward_list<int> flst{1,2,3};
for(auto p=flst.cbegin();p!=flst.cend();p++)
{
cout<<*p<<ends;
//1 2 3
}

return 0;
}


   (4)摒弃export
        C++11终止了export用法,但仍然保留了关键字export,供以后使用


   (5)尖括号
        C++11不在要求声明嵌套模板是使用空格将尖括号分开
      Example:
         vector<list<int>> vec;//ok

原创粉丝点击