Jump to content
  • Advertisement
Sign in to follow this  
FGFS

clear vector

This topic is 2150 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

 

Share this post


Link to post
Share on other sites
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)
    {
          // ...
    }
    

Share this post


Link to post
Share on other sites

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

Something alike:

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

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!