views:

68

answers:

6

Is there a significant difference between doing this...

if ( !myVector.empty()) {
  for ( unsigned int i = 0; i < myVector.size(); ++i ) {
    // do stuff
  }
}

and this

for ( unsigned int i = 0; i < myVector.size(); ++i ) {
  // do stuff
}

if the vector is empty? What is the cost of this on an empty vector?

+2  A: 

Both size and empty are constant time for vectors. So most of the time (non-empty vectors), the first one just adds a small, constant amount of work. The second is clearly cleaner, and probably negligibly more efficient on average.

Matthew Flaschen
+1  A: 

vector::size is required to be O(1) complexity. So for any reasonable implementation, for VECTORS, you can skip the calls to empty().

A reasonable implementation of a vector would look something like this:

class vector { 
    private:
        size_t m_size;

    public:
        size_t size() {
            return m_size;
        }

        bool empty() {
            return m_size == 0;
        }
};
sharth
There is no complexity requirement for `vector::size()`. There is merely a recommendation that it _should_ have constant complexity (and, I can't imagine a reasonable implementation of `vector` where it wouldn't have constant complexity). Once C++0x is published, then `size()` will be required to have constant complexity.
James McNellis
A: 

Since you asked for performance, why do you need to call the method size in for loop? Why don't you get the value before the loop starts ?

size_t size = myvector.size();

As far as your question, others have already replied.

Jagannath
A: 
i < myVector.size();

Will cause the loop to die before running on an empty vector. Anything more is redundant.

James
A: 

On the first code snippet somehow you are checking the size of your Vector 2 times if it's not empty.

but when it's empty, first one is more efficient.

I can't suggest you to use first one or the second one. it depends on your program. and number of cases that your vector is empty.

x86shadow
A: 

You are right, empty() is faster than comparing size() against zero

That's a rule mentioned by Effective STL

shader
Meyers says, "empty is a constant-time operation for all standard containers, but for some list implementations, size may take linear time.", which is true. However, this does *not* apply for `vector`, where both are constant time. Clearly, calling `size` repeatedly for a `list` would be a bad idea.
Matthew Flaschen