C++使用另一个数组和新值初始化数组

C++ initialize array with another array and new values

本文关键字:数组 初始化 新值 另一个 C++      更新时间:2023-10-16

我从python来到C++,如果可能的话,我想用数组做等效的事情:

both = [...]
a = [a1, a2] + both
[a1, a2, ...]
b = [b1, b2] + both
[b1, b2, ...]

你可以用std::vector来做到这一点

std::vector<int> both = {...};
std::vector<int> a = {a1, a2};
a.insert(a.end(), both.begin(), both.end());
std::vector<int> b = {b1, b2};
b.insert(b.end(), both.begin(), both.end());

要对数组执行此类操作,您可以考虑以下代码

#include <iostream>

int main()
{
int both[] ={1, 2, 3};
std::cout << sizeof(both)/sizeof(*both);
int a[sizeof(both)/sizeof(*both) + 2] = {4, 4};
int b[sizeof(both)/sizeof(*both) + 2] = {5, 5};
for (int i = 0; i < sizeof(both)/sizeof(*both); ++i)
{
a[2+i] = both[i];
b[2+i] = both[i];
}

return 0;
}

但是由于您使用的是 c++,而不是 c,因此您可以真正考虑使用 c++ 标准库提供的容器之一。