gpt4 book ai didi

c++ - 用另一个和额外元素的内容初始化 C++ (11) std::vector

转载 作者:IT老高 更新时间:2023-10-28 22:08:43 24 4
gpt4 key购买 nike

我需要一种“优雅”的方式来在声明阶段使用另一个 vector 的内容和一些额外元素来初始化 vector 。

我要解决的是:

让我们考虑以下带有初始化的(示例)声明:

const std::vector<std::string> c90_types = {
"char",
"signed char",
"unsigned char",
"short",
"unsigned short",
"int",
"unsigned int",
"long",
"unsigned long",
"float",
"double",
"long double"
};

const std::vector<std::string> c99_types = {
"char",
"signed char",
"unsigned char",
"short",
"unsigned short",
"int",
"unsigned int",
"long",
"unsigned long",
"float",
"double",
"long double",
"long long",
"unsigned long long",
"intmax_t",
"uintmax_t"
};

如您所见,c99_types 有一个子集,正是 c90_types。我想避免我需要更改子集然后手动更改“超集”的情况,只是为了避免可能引入错误的额外步骤:)

顺便说一句,我不想​​写这样的代码:

second.insert(second.begin(), first.begin(), first.end());
second.push_back(something);

有什么好的和干净的解决方案吗?

最佳答案

有一个技巧叫做“我想用一些复杂的东西来初始化一个 const 变量”。这在 C++11 中成为可能,无耻地从 Javascript 中窃取。

const std::vector<std::string> c90_types = {
"char",
// and so on, and so forth....
};

const std::vector<std::string> c99_types = ([&](){
const auto additional_types = { // initializer_list<const char *>, but it does not matter.
"long long",
"unsigned long long",
"intmax_t",
"uintmax_t"
};

std::vector<std::string> vec{c90_types};

vec.insert(vec.end(), additional_types.begin(), additional_types.end());

return vec;
})();

将您的初始化逻辑打包到一个未命名的 lambda 中,并立即调用它,复制初始化您的 const 变量。

vec 被移动,而不是被复制。

关于c++ - 用另一个和额外元素的内容初始化 C++ (11) std::vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28963884/

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