Deepak
Deepak

Reputation: 1088

strange output when using with vector iterato

I am getting strange output when running following code. In the getMeanGap function given below, it prints different vector element when comparing with vector elements printed in the calling function

//===Main Function========

    cout << ">>" << endl;
    for (typename vector<Type>::iterator it = v1.begin(); it != v1.end(); ++it)
    {
      cout << it->x << "\t" << it->y << endl; // "\t" << it->width << "\t" << it->height << endl;
    }

    cout << getMeanGap(v1) << endl;

//=======================

the getMeanGap function given below

template<typename Type>
float VIDSegment::getMeanGap(const vector<Type> & vec) const
{
  if (vec.size() < 2) return 0.0;
  cout << "----" <<endl;
  float sum = 0.0;
  for (typename vector<Type>::const_iterator it = vec.begin() - 1; it != vec.end(); ++it)
  {
    typename vector<Type>::const_iterator temp = it;
    temp++;
    cout << it->x << "\t" << it->y << endl;
    sum += ( (temp->x) - (it->x) - (it->width));
  }
  return float(sum / (vec.size() - 1));
}

While running above code I am getting following result

>>
26  51
56  19
112 23
175 25
211 26
331 23
379 23
424 23
471 23
----
0 0    // ??
26  51
56  19
112 23
175 25
211 26
331 23
379 23
424 23
471 23

May I know the reason for the above output ??

Upvotes: 1

Views: 70

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311048

The function has undefined behaviour because you are trying to access invalid iterator

vec.begin() - 1

and use it in statement

cout << it->x << "\t" << it->y << endl;

in loop

  for (typename vector<Type>::const_iterator it = vec.begin() - 1; it != vec.end(); ++it)
  {
    typename vector<Type>::const_iterator temp = it;
    temp++;
    cout << it->x << "\t" << it->y << endl;
    sum += ( (temp->x) - (it->x) - (it->width));
  }

Upvotes: 2

Related Questions