CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Threaded View

  1. #3
    Join Date
    Apr 2008
    Posts
    725

    Re: in a pickle here with sorting and popping from a vector

    here's how I'd do it. No need to sort yourself - just let vector.erase(...) do it.

    Code:
    #include <vector>
    #include <string>
    #include <iostream>
    
    using namespace std;
    
    template< class T>
    void GetNext( vector<T> & vec, typename vector<T>::iterator& position, int step )
    {
      for( int i = 0; i < step; ++i )
      {
        ++position; // should be a bit more careful here about receiving .end(), but meh.
        if( position == vec.end() )
          position = vec.begin();
      }
    }
    
    template< class T>
    void DeleteEntry( vector<T> & vec, typename vector<T>::iterator& position )
    {
      position = vec.erase(position);
      if( position == vec.end() )
        position = vec.begin();
    }
    
    template<class T>
    void PrintVec( vector<T> const & vec)
    {
      cout << endl;
    
      vector<T>::const_iterator it = vec.begin();
      vector<T>::const_iterator end = vec.end();
      for(; it != end; ++it)
      {
        cout << *it << endl;
      }
    
      cout << endl;
    }
    
    int main()
    {
      vector<string> names;
      names.push_back("bill");
      names.push_back("sue");
      names.push_back("al");
      names.push_back("may");
      names.push_back("gin");
      names.push_back("tim");
    
      int goose = 3;
      vector<string>::iterator position = names.begin();
    
      while( names.size() )
      {
        PrintVec( names );
    
        GetNext( names, position, goose-1 );
        DeleteEntry( names, position );
        
      }
    
      cin.get();
    }
    Last edited by Amleto; April 25th, 2010 at 09:35 AM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured