【问题标题】:How can I get around the use of VLAs?如何绕过 VLA 的使用?
【发布时间】:2021-09-23 00:36:05
【问题描述】:

我编写了一些代码,需要使数组的长度与用户输入的长度相同:

#include <iostream>
#include <string>
using namespace std;

void abrev(string word) {
    int lastChar = word.length();

    if (lastChar > 10) {
        cout << word[0];
        cout << lastChar - 2;
        cout << word[lastChar - 1] << endl;
    } else {
        cout << word << endl;
    }
}
int main() {
    int n;

    cin >> n;


    string words[n];

    for (int i = 0; i <= n - 1; i++) {
        cin >> words[i];
    }


    for (int i = 0; i <= n - 1; i++) {
        abrev(words[i]);
    }

    return 0;
}

我真的不知道我能做什么,我没有想法。我使用的是compiler,它只是解决了这个问题,所以直到我将此代码提交给 codeforces.com 时我才意识到这一点,其中出现了这些错误:

Can't compile file:
program.cpp
program.cpp(20): error C2131: expression did not evaluate to a constant
program.cpp(20): note: failure was caused by a read of a variable outside its lifetime
program.cpp(20): note: see usage of 'n'
program.cpp(23): warning C4552: '>>': operator has no effect; expected operator with side-effect

另外我不认为最后一个错误与它有任何关系,如果你能帮助解决这个问题,那就太棒了! 感谢您的帮助!

【问题讨论】:

标签: c++


【解决方案1】:

大部分是重复的,要解决错误,很容易用std::vector修复它

由于函数 abrev 不会改变参数,所以最好使用 const 引用。

#include <iostream>
#include <string>
#include <vector>
using namespace std;

void abrev(const string& word) {
  int lastChar = word.length();

  if (lastChar > 10) {
    cout << word[0];
    cout << lastChar - 2;
    cout << word[lastChar - 1] << endl;
  } else {
    cout << word << endl;
  }
}
int main() {
  int n;

  cin >> n;

  std::vector<std::string> words(n);

  for (int i = 0; i <= n - 1; i++) {
    cin >> words[i];
  }

  for (int i = 0; i <= n - 1; i++) {
    abrev(words[i]);
  }

  return 0;
}

【讨论】:

  • 如何使用整数而不是字符串来做到这一点?
  • @Piggy 你有课本吗?看来你需要一些基础知识。 std::vector&lt;int&gt; words(n); 可以。
  • 是的,我刚点了一些 xD
猜你喜欢
  • 2018-09-19
  • 2012-05-06
  • 2016-12-29
  • 2012-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-24
相关资源
最近更新 更多