By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,515 Members | 1,772 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,515 IT Pros & Developers. It's quick & easy.

begin() for empty STL container

P: n/a

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()?
May 31 '07 #1
Share this Question
Share on Google+
2 Replies


P: n/a
On May 30, 10:28 pm, "barcaroller" <barcarol...@music.netwrote:
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.
May 31 '07 #2

P: n/a

"barcaroller" <ba*********@music.netwrote in message news:f3**********@aioe.org...
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::stringBob; // 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
--
Cheers,
Robbie Hatley
lone wolf aatt well dott com
triple-dubya dott Tustin Free Zone dott org
May 31 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.