Question

I have a separate stack in my program with this timer vector attached. When called, the stack pops an element out and the timer keeps track of how long it is out via user input. When the time reaches 0, the element is put back into the stack. I wanted to work through multiple timers so I tried to put them all into a vector and have them all decrement by one time unit when a function is called. Not totally clear on how vectors work so I do not know how to decrement all of a vector's values.

int wait(vector<int> &x){
    std::vector<int>::iterator itr;
for(itr = x.begin(); itr < x.end(); itr++)
  {     //psuedocode 
    //x[itr]--;
  }
}

I just want to make sure I'm going in the right direction.

Was it helpful?

Solution

Here is how you can decrement all the values in the vector

int wait(vector<int> &x){
  for(std::vector<int>::iterator itr = x.begin(); itr != x.end(); itr++)
  {
    (*itr)--;
  }
}

or using C++11

int wait(vector<int> x){
    for (int& i : x ) 
      i--;
}

OTHER TIPS

To decrease the value pointed by the iterator in the code, you can do -

for(itr = x.begin(); itr < x.end(); itr++)
  {     //psuedocode 
    (*itr)--;
  }

*itr returns the value being pointed by the iterator.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top