开发者

Iterate Multiple std::vector

I've read here and other places that when iterating a std::vector using indexes you should:

std::vector <int> x(20,1);
for (std::vector<int>::size_type i = 0; i < x.size(); i++){
  x[i]+=3;
}

But what if you are iterating two vectors of different types:

std::vector <int> x(20,1);
std::vector <double> y(20,1.0);
for (std::vector<int>::size_type i = 0; i < x.size(); i++){
  x[i]+=3;
  y[i]+=3.0;
}

Is it safe to assume that

std::vector<int>::size_type

is of the same type as

开发者_JAVA百科std::vector<double>::size_type

?

Would it be safe just to use std::size_t?


Yes, for almost any practical purpose, you can just use std::size_t. Though there was (sort of) an intent that different containers could use different types for their sizes, it's still basically guaranteed that (at least for standard containers) size_type is the same as size_t.

Alternatively, you could consider using an algorithm, something like:

std::transform(x.begin(), x.end(), x.begin(), std::bind2nd(std::plus<int>(), 3));
std::transform(y.begin(), y.end(), y.begin(), std::bind2nd(std::plus<double>(), 3.0));


In general, C++ standard doesn't give such guarantees: neither equality of size_types for differently parametrized containers, nor equality to size_t.


I think you can safely assume that size_type is an unsigned nonegative integer. You can't rely on much beyond that. Sure, most containers have a size_type which is the same as size_t but there are no guarantees.

The SGI documentation and this source http://www.cplusplus.com/reference/stl/vector/ seem to agree on the point.

You may also want to take a look to this solution for your problem: http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously#C.2B.2B

I hope this helps.


Well, I think that:

 for (std::vector<int>::size_type i = 0; i < x.size(); i++){

is something of a council of perfection - are you expecting your vectors to be really gigantic? Personally, I use unsigned int, with zero problems.

And now I suppose the downvotes will begin...


You should use iterators instead

std::vector <int> x(20,1);
std::vector <double> y(20,1.0);
std::vector<double>::iterator j = y.begin();
for (std::vector<int>::iterator i = x.begin(); i != x.end(); ++i){
  *i +=3;
  *j +=3.0;
  ++j;
}

Cause there's no guarantee that u size_type would be the same internal type, anyway, for std::vector you could iterate using unsigned int

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜