Reputation: 162
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
?
Upvotes: 1
Views: 82
Reputation: 29955
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.
Upvotes: 1
Reputation: 19607
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.
Upvotes: 1