STL vector class

In my project, we are currently loading a list of movies into an array. We have to change the program to use a vector. I added my vector,

vector<Movie> movies2;

which correctly creates and loads the movies in.

while(!iS.eof()) {
movies[movieCnt++] = Movie(s);
Movie o = Movie(s);
movies2.push_back(o);
getline(iS, s);
}

but now I am trying to create an iterator to go traverse through the list when I need to retrieve a movie. I have set it up like all the examples I know but it keeps complaining.

vector<Movie>::iterator p; (in my my header class)

const Movie * Movies::getMovie(string mc, int& mn) const {
//vector<Movie>::iterator p;
p = movies2.begin();
if(mc.length()==0)
return NULL; // not found
else {
string mcP = myToLower(mc);
int ndx=0;
for(;ndx<movieCnt &&
(myToLower(p[ndx].getTitle()).find(mcP)==
string::npos);ndx++);
mn = ndx<movieCnt?ndx+1:0;
return ndx<movieCnt?&p[ndx]:NULL;
}
}

Does anyone see what I could possibly be missing? This is my first time working with vectors and I am lost.
If you are bothering to use an iterator then you should probably use it to iterate through the vector:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const Movie * Movies::getMovie(string mc, int& mn) const
{
  if(mc.size())
  {
    string mcP = myToLower(mc);
    for(vector<Movie>::iterator p = movies2.begin(); p != movies2.end(); ++p)
    {
      if((p->getTitle()).find(mcP) != string::npos) // found substring in title
      {
        mn = (p - movies2.begin()); // can only do this on random access iterators
        return p; // not sure if we need a cast here or something like `return static_cast<const Movie*>(p); ??
      }
    }
  }
  return NULL;
}


EDIT: forgot to set mn (why do you need the numeric index if you are returning a pointer to the object?)
Last edited on
That makes sense. The numeric indexing was a way my teacher did it but we are not limited to do it that way. Thanks for the help. I am going to adjust my code with your suggestion and see how it works. Thanks again.
Yea, the great thing about vectors is that you don't need to use an iterator. However, if you are going to be changing the dimensions of the vector in a loop than you should use an iterator. You can typedef them to make it more readable if you are declaring them a lot.

But you can actually just traverse it like an array if you'd like.

1
2
3
4
vector<int> v;

for (int i = 0; i < v.size(); i++)
     cout << v[i] << endl;
Topic archived. No new replies allowed.