begin() for empty STL container

B

barcaroller

If an STL container is empty, what will its begin() member function return?
Would it be a valid value that an iterator could use, like the end() member
function? In particular, can I assume that begin() == end()?
 
S

Salt_Peter

If an STL container is empty, what will its begin() member function return?
Would it be a valid value that an iterator could use, like the end() member
function? In particular, can I assume that begin() == end()?


Yes, but that doesn't make it valid, the container is empty.
 
R

Robbie Hatley

barcaroller said:
If an STL container is empty, what will its begin() member function return?
Would it be a valid value that an iterator could use, like the end() member
function? In particular, can I assume that begin() == end()?

begin() and end() will be equal. Both will be valid, can be assigned to iterators,
and can be used in loops, even though they do not point to actual elements:

// Not tested, but I'm
#include<iostream>
#include<list>
#include<string>
int main (void)
{
std::list<std::string> Bob; // empty list
std::list<std::string>::iterator i; // iterator for list

for ( i=Bob.begin() ; i!=Bob.end() ; ++i ) // Test "i!=Bob.end()" will fail.
{
std::cout << (*i) << std::endl; // This will never be executed.
}

Bob.push_back("Sam");
Bob.push_back("Tom");

for ( i=Bob.begin() ; i!=Bob.end() ; ++i ) // Test "i!=Bob.end()" will succeed.
{
std::cout << (*i) << std::endl; // This will execute twice.
}

return 0;
}

The first loop does nothing. (Nothing to print.)

The second loop will execute twice and will print:
Sam
Tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top