3

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?

Any beautiful solution, something like (pseudo):

for (auto& it : [a, b, c, d, e, f]) {
    // ...
}

(Without copies.)

vladon
  • 8,158
  • 2
  • 47
  • 91

2 Answers2

11
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.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
2

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). If you have a variable that is not a string you can use std::to_string to convert them in the first step.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Your `initializer_list` does a copy. – Jarod42 Jul 22 '16 at 09:05
  • @Jarod42 And in most cases it's really nothing to worry about. We don't know the use-case of the OP, if the OP is doing this multiple times a second then yes it might be an issue. If the OP is doing once or twice during a ten-hour run-time then it's really insignificant. It's all about context (which we don't have). If this is measured to be a bottleneck then maybe use `std::cref` instead. – Some programmer dude Jul 22 '16 at 09:13
  • OP stated explicitly, *"(Without copies.)"*. But I mostly agree in practice. – Jarod42 Jul 22 '16 at 09:16