gpt4 book ai didi

c++ - 动态设置数组大小 C++

转载 作者:行者123 更新时间:2023-11-30 01:18:34 25 4
gpt4 key购买 nike

我根本不懂任何 C++,但我正在尝试对我的应用程序正在使用的 C++ 库进行非常小的更新。在开始讨论之前,我希望有人能告诉我以下内容的正确语法:

我有以下几行代码:

#define A_NUMBER 100
#define ANOTHER_NUMBER 150

enum {
type1,
type2,
};

static int someMethod(int type)

{
char command[A_NUMBER];
//...more code
}

我需要做的是基于类型参数(type1 或 type2),我需要能够将数组的大小设置为 A_NUMBER 或 ANOTHER_NUMBER。

在伪代码中它会是这样的:

if (type == type1) {
char command [A_NUMBER]
}
else if (type == type2) {
char command [ANOTHER_NUMBER]
}

有没有办法动态定义大小?

最佳答案

是的,您可以使用 std::vector<char> :

if (type == type1) {
std::vector<char> x(A_NUMBER);
} else if (type == type2) {
std::vector<char> x(ANOTHER_NUMBER);
}

请记住在标题中包含:

#include <vector>

While your example code matches the "pseudo code" in the question, I think part of the question is how to decide the size via type and then use the resulting storage unconditionally, i.e. outside the conditional blocks.

然后它变得很简单:

std::vector<char> x;
if (type == type1) {
x.resize(A_NUMBER);
} else if (type == type2) {
x.resize(ANOTHER_NUMBER);
}

关于c++ - 动态设置数组大小 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22491004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com