clear vector

Started by
3 comments, last by FGFS 10 years, 7 months ago

Hi

I do:

for (std::vector<char>::iterator it = keys.begin() ; it <= keys.end(); ++it)
{
std::copy(keys.begin(), keys.end(), ApEntrystr);
}

works ok but now I want not more than 4 entries. How to clear when reaching 4 values?

Thanks

Advertisement

It isn't obvious to me what you mean.

  • Do you mean that you want to clear "keys" completely when 4 elements have been processed?
  • Do you mean you want to copy at most 4 elements using "ApEntrystr"
  • Do you want to clear the destination, whatever it is, when it reaches 4 entries?
  • Do you want to ensure the destination never has more than 4 entries?
  • Perhaps something else?
  • Giving us a little more detail about the intent of the code would help.

    On a side note your loop is incorrect, it increments the outer iterator past the end of the vector. A correct version is:

    for (std::vector<char>::iterator it = keys.begin() ; it < keys.end(); ++it)
    {
          // ...
    }
    

    Maybe you want to loop one more time than you have elements in the vector. In which case the cleaner solution might be to explicitly do that:

    // You could explain why you want the extra iteration here...
    int limit = keys.size() + 1;
    for (std::vector<char>::size_type i = 0 ; i < limit ; ++i)
    {
          // ...
    }
    

    Thanks. I want, if the user types more than 4 chars, to start at 0.

    Something alike:

    // if(keys.at(it)==4)
    // {
    // keys.clear();
    // }

    Have you tried comparing keys.size()?

    Note that you must be careful structurally modifying a vector when you are iterating over it, it is easy to end up with invalid iterators and/or accessing elements incorrectly, or stepping outside the bounds. One option might be to remove excessive elements before entering the loop (e.g. using erase()), so you don't have to worry about this condition in the loop body.

    With size it works, thanks.

    This topic is closed to new replies.

    Advertisement