【问题标题】:Is there a way to concatenate two arrays in c++ and return them?有没有办法在 c++ 中连接两个数组并返回它们?
【发布时间】:2012-10-14 06:41:06
【问题描述】:

我在python中有这样的递归函数

def recon(i,j):
    if i == 0 or j == 0:
        return []
    elif x[i-1] == y[j-1]:
        return recon(i-1,j-1) + [x[i-1]]
    elif table[i-1,j] > table[i,j-1]:
        return recon(i-1,j)
    else:
        return recon(i,j-1)

我正在尝试用 c++ 重写它,但问题是行

            return recon(i-1,j-1) + [x[i-1]]

我想用 c++ 做这个,但它不会编译,有没有办法像 python 一样连接数组并返回它们。

【问题讨论】:

  • 请展示您目前在 c++ 中的内容。对于您要实现的目标,最好使用std::vector 而不是数组;向量中可以添加元素,数组中则不能(它们固定为创建时的大小)
  • 这也是一个无效的语法@[x[i-1]]
  • C++ 中的数组与 Python 中的列表不同。您需要使用std::vectorstd::list

标签: c++ python arrays return concatenation


【解决方案1】:

不适用于数组。但是你可以用向量来做到这一点。

vector<int> x = ...;
vector<int> y = ...;
x.insert(x.end(), y.begin(), y.end()); // append y to x

您可以使用动态分配的内存进行类似的操作,但使用向量更容易。

【讨论】:

    【解决方案2】:

    也许你可以试试这个

    for(int j=0;j<10; j++)
        mer[j]=a[j];
    for(int i=0; i<10; i++, j++)
        mer[j]=b[i];
    

    其中 mer,a 和 b 已经初始化为数组变量。

    【讨论】:

      【解决方案3】:

      您需要创建一个大小正确的新数组以包含两个现有数组,然后循环遍历这两个数组以将它们复制进去(在复制第二个数组时不要忘记在目标数组上保留一个偏移量)

      【讨论】:

        【解决方案4】:

        这里似乎不需要递归:

        vector<int> recon(int i, int j) {
            vector<int> ret;
            while(i > 0 && j > 0)
                if(x[i-1] == y[j-1])
                    ret.push_back(x[--i]), --j;
                else if(table[i-1][j] > table[i][j-1])
                    --i;
                else
                    --j;
            std::reverse(ret.begin(), ret.end());
            return ret;
        }
        

        (免责声明:未经测试)

        【讨论】:

          猜你喜欢
          • 2021-01-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-02-21
          • 1970-01-01
          • 2019-05-12
          • 2017-12-31
          • 2022-10-17
          相关资源
          最近更新 更多