gpt4 book ai didi

c++ - 迭代不同类型 vector 的索引类型

转载 作者:行者123 更新时间:2023-11-30 03:14:18 24 4
gpt4 key购买 nike

给定两个不同类型但长度相同的 vector ,同步迭代两者的索引类型应该是什么?

考虑以下代码:

#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,但这不是标准所要求的。无论如何,请考虑使用迭代器:

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

如果需要,迭代器可以让以后更容易地使用算法。

关于c++ - 迭代不同类型 vector 的索引类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57935668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com