如何迭代变量

How can I iterate through variables?

本文关键字:变量 迭代 何迭代      更新时间:2023-10-16

如果我有代码:

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来转换它们。