简体   繁体   English

索引类型,以迭代不同类型的向量

[英]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? 如果我想使用一个索引,例如i ,遍历wordsvalues ,其类型应该是什么? Should it be size_t ? 应该是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. std::vector的成员类型别名size_type与模板参数无关,并且通常为std::size_t (并且不能/不会变得更大),所以可以。

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. 一般来说, std::vector::size_type几乎总是std::size_t ,但这不是标准要求的。 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. 迭代器使以后在需要时更容易使用算法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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