[英]How can I iterate through variables?
If I have the code: 如果我有代码:
T a;
T b;
T c;
// ...
T z;
How can I iterate through them without creating std::vector<T&>
of them? 如何在不创建std::vector<T&>
的情况下迭代它们?
Any beautiful solution, something like (pseudo): 任何漂亮的解决方案,如(伪):
for (auto& it : [a, b, c, d, e, f]) {
// ...
}
(Without copies.) (没有副本。)
for (auto& var : {std::ref(a), std::ref(b), std::ref(c), std::ref(d), std::ref(e), std::ref(f)}) {
// ...
}
Should do the job. 应该做的工作。
If you don't want to actually modify the "variables" then you might be able do something like 如果你不想真正修改“变量”那么你可能会做类似的事情
// 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
});
Note that this requires all "variables" to be of the same type ( std::string
). 请注意,这要求所有“变量”具有相同的类型( std::string
)。 If you have a variable that is not a string you can use std::to_string
to convert them in the first step. 如果你有一个不是字符串的变量,你可以使用std::to_string
在第一步中转换它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.