[英]How can I iterate through all my vector elements and check their variables? (C++)
[英]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
在第一步中转换它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.