Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C++ Vectors? Iterators? Eh?

  1. Aug 21, 2008 #1
    I came across a snippet of code like this:

    Code (Text):

      protonPropagator pp;
      vector<hit> hits;

      vector<hit>::iterator itr;
      for(int i=0;i<5;i++){
        hits = pp.compute(startX,startY,startZ,startE,theta,phi);

        fout<<i<<" "<<hits.size()<<" "<<startX<<" "<<startY<<" "<<startZ<<" "<<startE<<" "<<theta<<" "<<phi<<endl;

          cerr<<"No hits in this event, skipping"<<endl;
    And I was told it will iterate through the vector "hits" 5 times. But by the looks of it, nothing is really being iterated. You have an initialization of "itr", but then it's never used.

    So it looks like you get some value for hits and overwrite it on each successful iteration of the for() loop. Since it's printed out, you store it in a file so it doesn't matter if it's written over.

    Am I correct here? That the line "vector<hit>::iterator itr;" is useless? Or is it used to print to file, i.e. "copy(hits.begin(),hits.end(),ostream_iterator<hit>(fout,"\n"));"?
  2. jcsd
  3. Aug 21, 2008 #2


    User Avatar
    Science Advisor
    Homework Helper

    The iterator itr doesn't seem to be necessary, ostream_iterator<hit> will create a hidden one on the fly.
  4. Aug 21, 2008 #3


    User Avatar

    Staff: Mentor

    You're right, the iterator itr is irrelevant to this section of code. Is it used anywhere else?

    It certainly wouldn't be the first time that comments or documentation don't match the actual code. :rolleyes:

    There is a for-loop that iterates (cycles) five times. Maybe that's what they're referring to with the verb "iterates", not the iterator itr.
  5. Aug 21, 2008 #4
    Okay, I think I see what is going on now. The vector "hits" has some number of values in it like an array. I had thought that each value of hits carried its own array, i.e. making it a 2d array where each value of hits had its own array associated with it.

    That's why it's being cleared and reused every time.

    I still can't figure out what this line does, though:


    I know it copies the entire vector hits into the file, but how does ostream_iterator work?
  6. Aug 21, 2008 #5


    User Avatar

Share this great discussion with others via Reddit, Google+, Twitter, or Facebook