I have the following code:
Where I stupidly iterate over a container (self-written).
If I compile this function with the cout
it works and the program terminates correctly after the iteration! Note: The cout does not interfere with the self-made container!
If I then comment it out, the test starts to take infinitely long and does not terminate!
My eyeballs where almost dropping inside my head! What the hack is going on here???
My first guess was, that the compiler does something wrong? (but why?) or that maybe branch prediction plays me wrong and somehow increments the iterator twice? (which will result in no end() iterator).
I can really not explain what is going on?
int loops = 100;
int n = 0;
RangeTypes<Type>::ContainerType range(a);
INIT_TIMER
START_TIMER
for(int i=1; i<loops; i++) {
for(auto it=range.begin(); it != range.end(); ++it) {
n += *it;
//std::cout << i << std::endl;
}
}
STOP_TIMER("Range: ")
Actually the RangeType Container looks like this, and is pretty simple, it takes a range, and iterates from start to end!
template<typename Type>
struct RangeTypes {
using RangeType = std::pair<Type,Type> ;
class Iterator {
public:
Iterator(): m_rangePtr(nullptr), m_currVal(0) {};
~Iterator() {};
Iterator(RangeType & range, bool atEnd=false): m_rangePtr(&range) {
if(atEnd) {
m_currVal = m_rangePtr->second;
} else {
m_currVal = m_rangePtr->first;
}
};
/** pre-increment ++it
* Allow to iterate over the end of the sequence
*/
Iterator & operator++() {
if(m_rangePtr) {
++m_currVal;
}
return *this;
}
/** post-increment it++ */
Iterator operator++(int) {
Iterator it(*this);
operator++();
return it;
}
bool operator==(const Iterator &rhs) {
if(m_rangePtr) {
if(m_rangePtr == rhs.m_rangePtr ) { // if sequences are the same
return m_currVal == rhs.m_currVal;
}
}
return false;
}
// Return false if the same!
bool operator!=(const Iterator &rhs) {
return !(*this==rhs);
}
// get current value;
Type operator*() {
return m_currVal;
}
private:
RangeType * m_rangePtr;
Type m_currVal;
};
class ContainerType : public RangeType {
public:
typedef Iterator iterator;
ContainerType(RangeType & range ): RangeType(range) {
// if range wrong, set to no range!
if(this->first > this->second) {
this->first = 0;
this->second = 0;
}
}
iterator begin() {
return iterator(*this);
};
iterator end() {
return iterator(*this,true);
};
};
};
HERE IS THE MWE: Compiled Example
Thanks for any help!!