[英]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
,遍歷words
和values
,其類型應該是什么? 應該是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.