简体   繁体   中英

Type of index to iterate of vectors of different types

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 ?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM