What should be the type of index when iterating over the elements of a vector?

I usually iterate over a vector like this:

for (int i = 0; i < myVector.size(); i++) { Element* e = myVector[i]; } 

But then the compiler usually gives me this warning:

 warning: C4018: '<' : signed/unsigned mismatch 

So, if a int incorrect, what type should the index have? vector :: size () seems to be of type "size_type", but I would rather use a more meaningful type. Any suggestion?

+7
source share
4 answers

You should use std::vector<T>::size_type 1 . Its unsigned integral type. Its usually the same as size_t .

To find out the difference between size_type and size_t , see this section:

1. Similarly, you can use std::string::size_type , std::list<T>::size_type , std::deque<T>::size_type , std::set<T>::size_type and so on . Almost all standard containers define a nested type called size_type .


It can be argued that an iterator must be used instead of an index. But I also see that once an iterator makes the for-loop very wide horizontally, see This:

 for(std::vector<std::vector<std::string> >::iterator it = v.begin(); it != v.end(); ++it) { } 

It does not look. This is sometimes annoying. In such situations, some programmers prefer indexes over an iterator.

In C ++ 0x, the iterator has become more idiomatic. Now you can use the iterator without making the syntax cumbersome:

 for(auto it = v.begin(); it != v.end(); ++it) { } 

Or even better, using a range for the loop:

 for(auto & item : v) { } 
+13
source

The compiler throws a warning because your int is signed, but size () returns an unsigned int of type size_t. You do not want such a mismatch, because it can cause headaches if your int is negative. You can avoid all this by using size_t.

+2
source

If you just use it for iteration, you can use:

  typedef std::vector<Element*> ElementContainer; ElementContainer myVector(3); for (ElementContainer::const_iterator cit = myVector.begin();cit != myVector.end(); ++cit) { Element* e = *cit; } 

The advantage of this is that it is slightly more resilient to changing from vector<> to another container.

0
source

Just use unsigned . With size_t you never remember what the right header should include, and with vector<T>::size_type you type too much. For all practical purposes, they are one and the same thing, just a few times.

-one
source

All Articles