insert and incompatible iterators

As an exercise, I am implementing my own versions of the STL containers std::vector and std::string. When implementing my version of the following insert method

 void insert (iterator position, InputIterator first, InputIterator last);

Open in new window

I would like to check that the input iterators first and last refer to the same container. I know that the STL containers carry out such a check, since if one tries to use insert when this condition fails, one gets an error, e.g., "string iterators incompatible". How is this check implemented for STL containers?
Who is Participating?
sarabandeConnect With a Mentor Commented:
with my compiler (ms visual c++ 2008) the following compiles without error:

std::vector<std::string> v0, v1, v2;

v0.insert(v0.begin(), v1.begin(), v2.end());

Open in new window

even if I exchange the 2nd and 3rd argument there is no (compiler) error.

however at runtime there is a check if you run the code in the debugger. the debugger has additional information for arguments at runtime and "knows" to which container an iterator belongs. because of that it would find out that v2.end() is beyond the range spanned by v1.begin() and v1.end() and therefore I get a debug assertion.

at my system it happened in function std::vector::const_iterator::operator== member function.

     _SCL_SECURE_VALIDATE(this->_Has_container() && this->_Same_container(_Right));

Open in new window

when calling the Compat member function.

the operator == compares the right boundaries of the containers defined by the iterators first and last. it is checked in debug mode by calling the global function _Debug_range which exactly does the check you talked of.

void __CLRCALL_OR_CDECL _Debug_range(_InIt _First, _InIt _Last, const wchar_t *_File, unsigned int _Line)
{   // test iterator pair for valid range

Open in new window

in release mode the program crashes because of the error. when I run it from IDE it breaks in the function _Distance(_First, _Last, _Count); with access violation what is not very surprising because the (pointer) addresses associated with the iterators would not span a useable array of strings especially if using string class objects.

All Courses

From novice to tech pro — start learning today.