【问题标题】:Creating array with non constant sizes创建具有非恒定大小的数组
【发布时间】:2019-01-16 06:39:43
【问题描述】:

我目前正在处理一项任务,我必须找到一种方法来输出两个字符串的最长公共子序列。在我发现此代码的实现的所有其他地方,它们都有一个相似之处:多个数组使用非常量变量进行初始化,我一直认为这是不允许的。当我试图编译程序时,我得到了一个错误。像这样的代码应该如何编译?

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

//Prints the Longest common subsequence
void printLCS(char *s1, char *s2, int m, int n);
/* Driver program to test above function */
int main()
{
char s1[] = "ABCBDAB";
char s2[] = "BDCABA";
printLCS(s1, s2, strlen(s1), strlen(s2));
return 0;
}

void printLCS(char *s1, char *s2, const int m, const int n)
{
int L[m + 1][n + 1];

//Building L[m][n] as in algorithm
for (int i = 0; i <= m; i++)
{
    for (int j = 0; j <= n; j++)
    {
        if (i == 0 || j == 0)
            L[i][j] = 0;
        else if (s1[i - 1] == s2[j - 1])
            L[i][j] = L[i - 1][j - 1] + 1;
        else
            L[i][j] = max(L[i - 1][j], L[i][j - 1]);
    }
}

//To print LCS
int index = L[m][n];
//charcater array to store LCS
char LCS[index + 1];
LCS[index] = '\0'; // Set the terminating character

                   //Stroing characters in LCS
                   //Start from the right bottom corner character
int i = m, j = n;
while (i > 0 && j > 0)
{
    //if current character in s1 and s2 are same, then include this character in LCS[]
    if (s1[i - 1] == s2[j - 1])
    {
        LCS[index - 1] = s1[i - 1]; // Put current character in result
        i--; j--; index--;     // reduce values of i, j and index

    }
    // compare values of L[i-1][j] and L[i][j-1] and go in direction of greater value.
    else if (L[i - 1][j] > L[i][j - 1])
        i--;
    else
        j--;
}

// Print the LCS
cout << "LCS of " << s1 << " and " << s2 << " is " << endl << LCS << endl;
}

特别是数组L和数组LCS的声明。

对不起,如果这段代码是一团糟,我并没有在这里发布。任何帮助将不胜感激。

【问题讨论】:

  • 如果您的问题指定了输入大小的最大限制,只需使数组大小不变。不过,您必须小心不要在堆栈上创建大型数组。您也可以使用std::vector,这将是最佳实践。
  • 这就是我开始编写自己的程序的过程,我主要是想知道上面的代码应该如何编译。
  • GCC 扩展 - 使用 -pedantic 编译。

标签: c++ arrays multidimensional-array variable-length-array lcs


【解决方案1】:

在 GCC 编译器中有一个非标准扩展,大多数人使用它允许可变长度数组。不过你真的不应该使用它,因为 VLA 有a lot of downsides,这就是为什么它们一开始就没有在 C++ 标准中。此外,当您的程序由于尝试在堆栈上创建一个大数组而接收到大量输入时,您可能最终会出现堆栈溢出。

使您的数组大小恒定或使用std::vector

【讨论】:

  • "...你最终可能会得到一个 stackoverflow..." !是的,他将不得不在 stackoverflow 找到进一步的解决方案。
【解决方案2】:

添加#include &lt;cstring&gt;(用于strlen()) 让我能够编译它:http://cpp.sh/3gwwd 和输出

LCS of ABCBDAB and BDCABA is 
BDAB

哪个是正确的,不是吗? (我不知道 LCS)[http://lcs-demo.sourceforge.net/]

当性能不是绝对优先时,您可以考虑使用std::vector&lt;char&gt;,它的障碍要少得多(您也包含了矢量类但没有使用它?)

【讨论】:

    猜你喜欢
    • 2021-03-14
    • 1970-01-01
    • 2011-03-27
    • 2020-04-28
    • 2014-08-18
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多