高效存储多达 2048 个字符的数组

Efficiently store array of up to 2048 characters?

本文关键字:字符 数组 2048 存储 高效      更新时间:2023-10-16

从另一个源获取输入;填充最多 2048 个字符的字符串。

填充和比较此字符串的最有效方法是什么? - 我也希望能够轻松地附加到字符串中。

以下是我的三次尝试:

C型版本

#include <cstdio>
#include <cstring>
int main(void) {
    char foo[2048];
    foo[0]='a', foo[1]='b', foo[2]='c', foo[3]='';  // E.g.: taken from u-input
    puts(strcmp(foo, "bar")? "false": "true");
}

C++式版本 0

#include <iostream>
int main() {
    std::string foo;
    foo.reserve(2048);
    foo += "abc";  // E.g.: taken from user-input
    std::cout << std::boolalpha << (foo=="bar");
}

C++式版本 1

#include <iostream>
int main() {
    std::string foo;
    foo += "abc";  // E.g.: taken from user-input
    std::cout << std::boolalpha << (foo=="bar");
}

最有效的方法取决于您的优化对象。
一些常见的标准:

  1. 程序速度
  2. 程序大小
  3. 工作集大小
  4. 代码大小
  5. 程序员时间
  6. 安全

毫无疑问,1 和 2 的国王,在您的示例中可能也是 3,是 C 风格。
对于 4 和 5,C++样式 1。
第 6 点可能是C++式的。

尽管如此,还是

需要适当地组合强调这些目标,恕我直言,这有利于选项 0 C++。