C++ vector

C++ vector

新建vector数组

  1. 已知内容:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    vector<int> a = {1,2,3,4,5};
    // 注意,不是[1,2,3,4,5]

    // 或者

    int i[6] = {6,1,3,2,4,7};
    vector<int> a(i,i+6);

    // 初始化固定长度,初值为0
    vector<int> vec(k, 0);

    // 初始化固定长度,无初值
    vector<int> vec(k);
  2. 不知道长度,每次用push进去

    1
    2
    3
    vector<int> a;
    a.push_back(1);
    a.push_back(2);

新建二维vector数组

1
vector<vector<int>> visited(h, vector<int>(w));

得到vector最后一个元素

1
merged.back()

计数

1
2
3
// vector中0的个数
int s1 = accumulate(students.begin(), students.end(), 0);

新建一个

1
ret.push_back(vector <int> ());

在末尾添加元素

1
ret.back().push_back(node->val);

切片、截取部分

取vector区间的元素
取数组{1, 4, 3, 2, 5}在[1, 3]区间的元素为{4, 3, 2}

1
2
3
4
5
6
std::vector<int> v{1,2,3,4,5}; 
std::vector<int> result(v.begin() + 1,v.begin() + 3);

//————————————————
//版权声明:本文为CSDN博主「thisiszdy」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
//原文链接:https://blog.csdn.net/thisiszdy/article/details/120086664

以下有点麻烦啊。。。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main(){
vector<int> Arrs {1,2,3,4,5,6,7,8,9};
// 假设有这么个数组,要截取第2个元素到第6个元素:2,3,4,5,6对应索引分别为 1,2,3,4,5
vector<int>::const_iterator First = Arrs.begin() + 1; // 找到第 2 个迭代器 (idx=1)
vector<int>::const_iterator Second = Arrs.begin() + 6; // 找到第 6 个迭代器 (idx=5)的下一个位置
vector<int> Arr2;
Arr2.assign(First,Second); // [First,Second) 左闭右开区间

for(auto i : Arr2){
cout << i<<"--";
}
return 0;
}
// ————————————————
// 版权声明:本文为CSDN博主「索隆啊」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
// 原文链接:https://blog.csdn.net/qq_36758461/article/details/120059080