C++  STL初学笔记

更系统的版本见徐本柱的PPT

Ref:https://github.com/huihut/interview/tree/master/STL

 

set

在这儿:http://www.cnblogs.com/pdev/p/4035020.html

 

#include <vector>

可看作可以动态改变大小的数组。

注意:vector作为数组,下标自动从0开始

定义:vector <数据类型> v

    扩展:二维数组:   vector<vector<int> > Array2D;

应用:void  v.insert(int a,数据类型b) :在数组的第a个数后面插入b

        void  v.erase(int a,int b) :删除数组中位置从ab的元素

      int  v.begin() :返回数组位置(迭代器)

      int  v.end() :返回数组结尾位置(迭代器)

      数据类型  v.front() :返回第一个数据

        数据类型  v.back() :返回末尾的数据

      void  v.push_back(n) :在容器尾端插入新元素n

      void  v.pop_back() :删除结尾的一个元素

        void  v.reserve(int n) :重新定义数组大小

      int  v.empty() :判断容器是否为空。是则返回1

      int  v.size() :返回容器中元素个数

--------------------------------------------------------------------------

容器的迭代器:相当于数组的指针

Eg: 

 1 #include <cstdio>
 2 #include <vector>
 3 #include <cstdlib>
 4 #include <iostream>
 5 using namespace std;
 6 
 7 int main(int argc, char *argv[])
 8 {
 9     vector<int> arr;
10     int n, data;
11     while (cin >> n)
12     {
13         arr.clear();    //clean the array
14         if (arr.empty())
15         {
16             cout << "It's empty!" << endl;
17         }
18         for (int i = 0; i < n; ++i)
19         {
20             cin >> data;
21             arr.push_back(data);
22         }
23         cout << "The size of the array is " << arr.size() << endl;
24         cout << "All the element(s) in the array is(are) ";
25         /*
26         for (vector<int>::iterator it = arr.begin(); it != arr.end(); ++it)
27         {
28             cout << *it << " ";
29         }
30         */                    //用迭代器
31         for (int x=0;x<n;x++)
32             cout<<arr[x]<<" ";        //注意:vector和map还可以用这种类似数组下标的方式访问
33         cout << endl;
34     }
35     return EXIT_SUCCESS;
36 }
View Code

相关文章:

  • 2021-10-08
  • 2021-11-10
  • 2021-08-04
  • 2021-08-27
  • 2021-04-30
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-12-11
  • 2021-04-12
  • 2021-09-21
  • 2022-12-23
  • 2022-12-23
  • 2021-06-09
  • 2022-12-23
相关资源
相似解决方案