C++ Vector VS Python list
C++ Vector VS Python list
构造
- 构造一个空列表
vector<int> cpp;
python = []
- 构造一个长度为6,初始值为0的列表
vector<int> cpp(6, 0);
python = [0 for _ in range(6)]
- 切片
vector<int> cpp = {1, 2, 3, 4};
vector<int> slices(cpp.begin() + 1, cpp.begin() + 3); // {2, 3}
python = [1, 2, 3, 4]
slices = python[1:3]
插入
- 尾部插入元素5
vector<int> cpp = {1, 2, 3, 4};
cpp.push_back(5); // {1, 2, 3, 4, 5}
python = [1, 2, 3, 4]
python.append(5) # [1, 2, 3, 4, 5]
- 索引1和2中间插入5
vector<int> cpp = {1, 2, 3, 4};
cpp.insert(cpp.begin() + 2, 5); // {1, 2, 5, 3, 4}
python = [1, 2, 3, 4]
python.insert(2, 5) # [1, 2, 5, 3, 4]
- 索引1和2中间插入两个5
vector<int> cpp = {1, 2, 3, 4};
cpp.insert(cpp.begin() + 2, 2, 5); // {1, 2, 5, 5, 3, 4}
python = [1, 2, 3, 4]
[python.insert(2, 5) for _ in range(2)] # 返回列表为[None, None], 但insert执行了两次
- 将B列表的部分连续元素插入到A列表中去
// 将B中的6, 7插入到cpp的2和3中间
vector<int> cpp = {1, 2, 3, 4};
vector<int> B = {5, 6, 7, 8};
cpp.insert(cpp.begin() + 2, B.begin() + 1, B.end() - 1); // {1, 2, 6, 7, 3, 4}
# 将B中的6, 7插入到python的2和3中间
python = [1, 2, 3, 4]
B = [5, 6, 7, 8]
[python.insert(2, B[2 - i]) for i in range(2)] # 返回列表为[None, None], 但insert执行了两次
我思故我在