pumpkinjuice pumpkinjuice - 1 year ago 134
C++ Question

c++ iterate over arrays of different types

I have m ints and n floats and I want to iterate over them in one loop. In order to do so, I can think of two possible ways but I don't know if they are actually feasible:

  1. Ideally I want to store the m+n numbers in one array (e.g. in one std::vector), is there a way (a container, or by means of polymorphism) that I could do this?

  2. If I must store the ints and floats in two arrays, is there (or how to write) an iterator that can iterate the two arrays in on loop?

Any idea is welcome!

Answer Source

It seems a template function might be a good solution:

  1. it preserves the semantics of "doing the same for both containers of floats and containers of ints", without creating an artificial container of floats/ints for the sake of saving a few lines of code
  2. from a performance perspective there will be no difference with a hand coded loop iterating over both arrays if you enable compiler optimisations -O3
  3. it will work for other types (e.g. double, int64_t, int32_t etc.)

It would look like this:

template<typename T>
void processData(std::vector<T> data) {
   for (auto& d : data) {
     // do some processing

you would call it with:

processData(std::vector<float>{1.2, 2.5, 3.5, 4.5});
processData(std::vector<int>{1, 2, 3, 4});

see a working example here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download