【问题标题】:C++ initialize array with another array and new valuesC++ 用另一个数组和新值初始化数组
【发布时间】:2020-10-23 06:30:07
【问题描述】:

我是从 python 开始使用 C++ 的,如果可能的话,我想用数组做同样的事情:

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

【问题讨论】:

  • 你需要编写代码来做到这一点;到目前为止你写了什么?
  • 你应该看看 std::vector
  • 注意:C++ 中的数组是从 C 中的数组派生而来的,而 C 中的数组旨在解决当时的问题。那个时候是1970年代。您会发现 C++ 中的数组非常简单和愚蠢。更喜欢使用a library container

标签: c++ arrays initialization concatenation


【解决方案1】:

您可以通过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());

【讨论】:

    【解决方案2】:

    要对数组做这样的事情,你可以考虑下面的代码

        #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++ 标准库提供的容器之一

    【讨论】:

    • @Alexander Wilkinson 请将帮助您解决/解决问题的答案标记为解决方案
    • 谢谢!我知道我可以用向量来做到这一点,我只是更喜欢使用数组,因为我真的不喜欢向量的语法。愚蠢的推理,我知道。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-08
    • 2015-08-25
    相关资源
    最近更新 更多