tags:

views:

83

answers:

4

I was trying to use the vector STL, where iam facing a weird response from the following sample program :

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

vector<int>::iterator  fun();
  vector<int> myvector;

bool IsOdd (int i) {
  return ((i%2)==1);
}

int main()
{
   vector<int>::iterator  it;

     it = fun();

if (it == myvector.end() )
cout << "Reached end, Global" << endl;
else
cout << "Not end" << endl;


}

vector<int>::iterator  fun() {
  vector<int>::iterator it;

  myvector.push_back(10);
  myvector.push_back(26);
  myvector.push_back(40);
  myvector.push_back(56);

  it = find_if (myvector.begin(), myvector.end(), IsOdd);
  cout << "The first odd value is " << *it << endl;

if (it == myvector.end() )
cout << "Reached end, inside the function" << endl;
else
cout << "Not end" << endl;

  return it;
}

Iam getting "Reached End" inside the function fun(), whereas, in the main program, it is showing up as "Not End".

Not sure, what might be the reason. Also, found that, the Address of myvector.end() is showing up as Zero in the main program [ after the fun() call ], where-as, showing a non-zero value inside the function fun().

+2  A: 

The function is using the local myvector, main is using the global one.

Your modified code produces:

Reached end, inside the function
Reached end, Global

as expected.

Edit: Well, not as expected - as others have pointed out:

it = find_if (myvector.begin(), myvector.end(), IsOdd);
cout << "The first odd value is " << *it << endl;

will cause undefined behaviour with your dataset, because you don't have any odd values. You want:

it = find_if (myvector.begin(), myvector.end(), IsOdd);
if ( it != myvector.end() ) {
  cout << "The first odd value is " << *it << endl;
}
anon
A: 

There are two different myvectors, one is global, another is in fun. Therefore, you're comparing an iterator to the global vector with an iterator to a local vector which moreover doesn't exist anymore.

Alexandre C.
A: 

You have two instances of vector with name myvector. One global and one local to function fun. Inside fun this local vector hides the global vector. Since you are operating on two totally different vector objects you are seeing these results.

Naveen
A: 

You dereferenced *it without checking if it was before the end. None of your vector values are odd, so it will be end and you will cause undefined behaviour by dereferencing it.

DeadMG