繁体   English   中英

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

[英]Type of index to iterate of vectors of different types

给定两个不同类型但长度相同的向量,同步访问两个索引的索引的类型应该是什么?

考虑以下代码:

#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;
}

如果我想使用一个索引,例如i ,遍历wordsvalues ,其类型应该是什么? 应该是size_t吗?

std::vector的成员类型别名size_type与模板参数无关,并且通常为std::size_t (并且不能/不会变得更大),所以可以。

但是还有其他方法可以遍历多个范围。

类型可以相同或不同,这取决于实现。 一般来说, std::vector::size_type几乎总是std::size_t ,但这不是标准要求的。 无论如何,请考虑使用迭代器:

#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
    }
}

迭代器使以后在需要时更容易使用算法。

暂无
暂无

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

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