如何迭代变量
How can I iterate through variables?
如果我有代码:
T a;
T b;
T c;
// ...
T z;
如何在不创建它们的std::vector<T&>
的情况下迭代它们?
任何漂亮的解决方案,类似(伪):
for (auto& it : [a, b, c, d, e, f]) {
// ...
}
(无副本。)
for (auto& var : {std::ref(a), std::ref(b), std::ref(c), std::ref(d), std::ref(e), std::ref(f)}) {
// ...
}
应该做这份工作。
如果你不想真正修改"变量",那么你可以做一些类似的事情
// TODO: Put your own variables here, in the order you want them
auto variables = { a, b, c, .... };
// Concatenate all strings
std::string result = std::accumulate(std::begin(variables), std::end(variables), "",
[](std::string const& first, std::string const& second)
{
return first + ' ' + second; // To add spacing
});
请注意,这需要所有"变量"都是相同的类型(std::string
)。如果您有一个不是字符串的变量,您可以在第一步中使用std::to_string
来转换它们。
相关文章:
- 如何在 c++ 中将字符串迭代器变量传递给函数?
- C++ Code 在 for 循环期间不会累积变量中的总和,仅提供最终迭代值
- 需要循环帮助以迭代方式添加到程序集中的总和变量
- 迭代器或反向器的一个变量
- ActorItr 迭代器变量中有什么,* ActorItr 返回什么?
- 如何在每次迭代后在循环中获取变量的值?
- 从迭代器转换为变量的类型.(C++11 模板)
- 从 for 循环的每次迭代创建一个新变量
- 增加迭代变量背后的直觉?
- 如何在C++中迭代非常量变量?
- 将多个计算放入使用基于迭代次数的变量的 for 循环中
- 如何将迭代器变量声明为私有成员变量
- 让宏将迭代参数传递到通过宏变量提供的代码体中
- 在每次迭代中显示变量
- C :我可以将成员变量的迭代器带入班级之一
- 为什么我需要在每次迭代使用字符串流变量的循环时清除该变量
- C++ 列表中的对象变量在迭代过程中不会更新
- 作为变量的目录迭代器值
- 迭代器变量在C 中表现奇怪
- 为什么在循环中定义的变量地址在每次迭代中都保持不变