lists and iterators - check null

I'm trying to use lists and iterators, I need to initialize a list and check if it has been initialised or not.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <list>
#include <cassert>

int main()
{
	std::list<char>m_WayPoints;
	std::list<char>::iterator  curWaypoint;

	m_WayPoints.insert('a');
	curWaypoint = m_WayPoints.begin();

	if (curWaypoint._Mynextiter == 0)
		std::cout << "nothing"; return 1;

	std::cout << "something";
	return 0;
}
Not sure I understand. A list is not a pointer. It cannot be null. It is initialized automatically when you create it on line 7.
Last edited on
How do I assign elements to "m_WayPoints" then? So I can falsify the condition on line 13?
The std::list has members like empty() or size()
Normally you don't need to sice std::list throws an std::bad_alloc if the insert doesn't succeed.
@Thomas1965

Is there any way to assert if curWaypoint is NULL?

1
2
 //returns the current waypoint
  Vector2D    CurrentWaypoint()const{assert(curWaypoint != NULL); return *curWaypoint;}


this line of code won't compile in the project I got
An iterator is not a pointer. It cannot be null.

What you normally do for iterators is to set them equal to the end() iterator instead. The end() iterator refers to one-past-the-end, so it doesn't refer to any valid element. If you set curWaypoint to m_WayPoints.end() you could check for that inside the assert.

 
assert(curWaypoint != m_WayPoints.end());
Last edited on
thank you Peter- problem solved
Topic archived. No new replies allowed.