C++ 模板类vector学习笔记(初学者)

//包含头文件并使用命名空间
1
include <vector> 2 #using namespace std;

1.在计算中,矢量(vector)对应数组

2.要创建模板类对象,可使用通常的<type>表示法来指出要使用的类型

3.另外,vector模板使用动态内存分配,因此可以初始化参数来指出需要多少矢量

例1:利用vector创建一维数组

#include <iostream>
#include <vector>

using namespace std;

void main()
{
    int n, i;
    cin >> n;
    //定义
    vector <int> a;
    //通过resize()来修改容器结构
    a.resize(n);
    //通过capacity()查看容器当前空间上限
    a.capacity();
    cout << "容器目前大小为 " << a.size() << endl << "--------------" << endl << endl;
    cout << "容器目前上限为 " << a.capacity() << endl << "--------------" << endl << endl;
    //使用[]访问vector中的元素
    cout << "循环输出容器中的元素" << endl << "-----------" << endl;
    for (i = 0; i < n; i++)
    {
        a[i] = i;
        cout << a[i] << " ";
        if ((i + 1) % 5 == 0 && i != 0)
            cout << endl;
    }
    cout << endl << endl;
}

例2:利用vector创建二维Mat类型容器

#include <iostream>
#include <vector>
#include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;

void main()
{
    int m, n;
    vector< vector<int> > ImageGroup;
    //修改行数为m
    cout << "请输入行数m=: ";
    cin >> m;
    ImageGroup.resize(m);
    //修改列数为n
    cout << "请输入列数n=: ";
    cin >> n;
    int i,j;
    for (i = 0; i < m; i++)
        ImageGroup[i].resize(n);
    for (i = 0; i < m; i++)
    {
        for (j = 0; j < n; j++)
        {
            ImageGroup[i][j] = (i+1)*(j+1);
            cout << ImageGroup[i][j] << " ";

        }
        cout << endl;
    }
    cout << endl;
}

例2程序运行结果如下:

  以上笔记作于学习openCV时遇到需要用vector的情况。

猜你喜欢

转载自www.cnblogs.com/sunrise-to-set/p/10897083.html