-
Vectors and Iterators
I need some help figuring out some existing code. I've been given a project to recompile quite a bit of code in Visual Studio 2005 from 2003 and I'm having a bit of trouble with vectors and iterators. I'm a C/C++ novice, so humor me please. Here is a bit of the code:
This is defined in EventBufferData.h:
Code:
Type m_type;
TimeStamp m_timeStamp;
std::vector< Entry >::iterator mp_entry;
std::string m_value;
std::string m_value0;
bool m_triggered0;
TimeStamp m_timeStamp0;
and this is a part of EventBufferData.cpp:
Code:
EventBufferData::EventBufferData () :
m_type(EventTypeNull),
mp_entry(NULL),
m_value(""),
m_triggered0(false),
m_value0("")
{
m_timeStamp.sysTime = "";
m_timeStamp.simTime = "";
m_timeStamp0.sysTime = "";
m_timeStamp0.simTime = "";
}
The problem comes from the line mp_entry(NULL). It seems this was fine in .NET 2003, but in 2005 I get an error : error C2664: 'std::_Vector_iterator<_Ty,_Alloc>::_Vector_iterat or(const std::_Vector_iterator<_Ty,_Alloc> &)' : cannot convert parameter 1 from 'int' to 'const std::_Vector_iterator<_Ty,_Alloc>
But what I really want to know is what is this line doing? mp_entry is defined as std::vector< Entry >::iterator mp_entry; and I can't find any examples online of an iterator being referenced as iterator_name(NULL).
-
Instead of mp_entry(NULL), write: mp_entry()
-
In fact, do the same for m_value and m_value0 (and even m_triggered0 if you wanted). An empty vector and empty string are the default, so if you use the default constructor or leave them out of the initializer list entirely they will be properly initialized. The default for bool is false, so if you used m_triggered0() it would be correctly initialized. However, unlike vector and strinng, since bool is a built-in type if you don't put it in the initializer list it won't be initialized at all and will contain garbage data.
Edit: I thought mp_entry was a vector, so ignore my references to vector above.
-
It is strange though that this code would store an iterator for a longer time. Iterators are typically meant for ... iterating (locally).
Watch out because vector's iterators tend to get invalidated quite often. (Storing indices might be somewhat safer.)