1

Given two vectors of different types but same length, what should be the type of the index to iterate over both in sync?

Consider the following code:

#include <iostream>
#include <string>
#include <vector>

int main(void)
{
    std::vector<std::string> words = {"foo", "bar"};
    std::vector<double> values = {42, 314};

    std::vector<std::string>::size_type i = 0;
    std::vector<double>::size_type j = 0;

    while (i < words.size() && j < values.size()) {
        std::string w = words[i];
        double v = values[j];
        // do something with w and v
        ++i;
        ++j;
    }

    return 0;
}

If I wanted to use a single index, say i, to iterate over both words and values, what should be its type? Should it be size_t?

gustgr
  • 152
  • 9

2 Answers2

1

The member type alias size_type of std::vector is independent of the template parameters and is generally std::size_t (and cannot be/does not make sense to be bigger), so yes.

But there are other approaches to iterating over multiple ranges.

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
  • 1
    "independent of the template parameters". That's untrue. It is dependent on the `Allocator`. – geza Sep 14 '19 at 13:00
  • @geza After checking the standard, it falls under *implementation defined*, and that neither mandates nor forbids this dependency. So I don't know whether and how to fix that statement of mine... – LogicStuff Sep 14 '19 at 13:13
  • This is wrong... No where in the standard it is said that `size_type` is independent of the template arguments and it is allowed to be dependent. – Aykhan Hagverdili Sep 14 '19 at 13:25
  • Hmm. I read this somewhere, maybe this is wrong. But still, it is worse now, because `size_type` can be anything. Even, it can be dependent on template parameters. – geza Sep 14 '19 at 13:28
1

The types may or may not be the same, it is implementation dependent. Generally speaking, std::vector::size_type is almost always std::size_t, but this is not required by the standard. In any case, consider using iterators:

#include <string>
#include <vector>

int main() // no need for (void) in C++
{
    std::vector<std::string> words = {"foo", "bar"};
    std::vector values = {42.0, 314.0}; // No need for <double> with C++17

    auto wit = words.cbegin(), wend = words.cend();
    auto vit = values.cbegin(), vend = values.cend();

    while (wit != wend && vit != vend) {
        std::string w = *wit++;
        double v = *vit++;
        // do something with w and v
    }
}

Iterators make it easier to use algorithms later on if needed.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93