Does the BOOST_FOREACH macro work for empty sequences or must a size check be done explicitly? list<int> mylist; if (!mylist.empty()) // <--- necessary? { foreach(int& i, mylist) { // take action } } The reason I ask is that neither begin() nor end() return valid iterators for empty sequences, but it is my understanding that BOOST_FOREACH needs iterators to work properly.
Does the BOOST_FOREACH macro work for empty sequences or must a size check be done explicitly?
list<int> mylist;
if (!mylist.empty()) //<--- necessary? { foreach(int& i, mylist) { // take action } }
The reason I ask is that neither begin() nor end() return valid iterators for empty sequences, but it is my understanding that BOOST_FOREACH needs iterators to work properly.
To be short: it's not necessary. BTW, begin() and end() for an empty list are valid. You can't dereference them, but they are valid. So one can use them for comparison. And BOOST_FOREACH does.
"Dmitry Vinogradov"
To be short: it's not necessary.
BTW, begin() and end() for an empty list are valid. You can't dereference them, but they are valid. So one can use them for comparison. And BOOST_FOREACH does.
I've had problems with standard 'for' loops when using empty containers: for (i = mylist.begin() ; i != mylist.end() ; i++) By problems I mean core-dumps, memory leaks, etc. These problems went away when I used a size check: if (!mylist.empty()) for (i = mylist.begin() ; i != mylist.end() ; i++) This leads me to believe that begin() and end() are not valid, or is there another way to explain this?
On 1/8/2010 1:40 PM, barcaroller wrote:
"Dmitry Vinogradov"
wrote: To be short: it's not necessary.
BTW, begin() and end() for an empty list are valid. You can't dereference them, but they are valid. So one can use them for comparison. And BOOST_FOREACH does.
I've had problems with standard 'for' loops when using empty containers:
for (i = mylist.begin() ; i != mylist.end() ; i++)
That's perfectly OK.
By problems I mean core-dumps, memory leaks, etc. These problems went away when I used a size check:
if (!mylist.empty()) for (i = mylist.begin() ; i != mylist.end() ; i++)
This leads me to believe that begin() and end() are not valid, or is there another way to explain this?
I suggest you look for the problem elsewhere. list::begin and list::end always return valid iterators. Comparing them is fine -- if the list is empty, the begin and end iterators will compare equal. -- Eric Niebler BoostPro Computing http://www.boostpro.com
participants (3)
-
barcaroller
-
Dmitry Vinogradov
-
Eric Niebler