C++/STL Algorithms Modifying sequence operations/remove

Материал из C\C++ эксперт
Версия от 10:28, 25 мая 2010; Admin (обсуждение | вклад) (1 версия: Импорт контента...)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Combine remove and erase together

  
 
/* The following code example is taken from the book
 * "The C++ Standard Library - A Tutorial and Reference"
 * by Nicolai M. Josuttis, Addison-Wesley, 1999
 *
 * (C) Copyright Nicolai M. Josuttis 1999.
 * Permission to copy, use, modify, sell and distribute this software
 * is granted provided this copyright notice appears in all copies.
 * This software is provided "as is" without express or implied
 * warranty, and with no claim as to its suitability for any purpose.
 */
#include <iostream>
#include <vector>
#include <deque>
#include <list>
#include <set>
#include <map>
#include <string>
#include <algorithm>
#include <iterator>
#include <functional>
#include <numeric>
/* PRINT_ELEMENTS()
 * - prints optional C-string optcstr followed by
 * - all elements of the collection coll
 * - separated by spaces
 */
template <class T>
inline void PRINT_ELEMENTS (const T& coll, const char* optcstr="")
{
    typename T::const_iterator pos;
    std::cout << optcstr;
    for (pos=coll.begin(); pos!=coll.end(); ++pos) {
        std::cout << *pos << " ";
    }
    std::cout << std::endl;
}
/* INSERT_ELEMENTS (collection, first, last)
 * - fill values from first to last into the collection
 * - NOTE: NO half-open range
 */
template <class T>
inline void INSERT_ELEMENTS (T& coll, int first, int last)
{
    for (int i=first; i<=last; ++i) {
        coll.insert(coll.end(),i);
    }
}
using namespace std;
int main()
{
    vector<int> coll;
    INSERT_ELEMENTS(coll,2,6);
    INSERT_ELEMENTS(coll,4,9);
    INSERT_ELEMENTS(coll,1,7);
    PRINT_ELEMENTS(coll,"coll:               ");
    // remove all elements with value 5
    vector<int>::iterator pos;
    // remove all elements less than 4
    coll.erase(remove_if(coll.begin(), coll.end(),  // range
                         bind2nd(less<int>(),4)),   // remove criterion
               coll.end());
    PRINT_ELEMENTS(coll,"<4 removed:         ");
}
/* 
coll:               2 3 4 5 6 4 5 6 7 8 9 1 2 3 4 5 6 7
<4 removed:         4 5 6 4 5 6 7 8 9 4 5 6 7
 */


Remove all instances of "0"

  
#include <algorithm>
#include <vector>
#include <list>
#include <iostream>
using namespace std;
int main (){
    list <int> l;
    for (int nCount = 0; nCount < 10; ++ nCount)
        l.push_back (nCount);
    list <int>::const_iterator li;
    for ( li = l.begin (); li != l.end (); ++ li )
        cout << *li << " ";
    vector <int> v (l.size () * 2);
    vector <int>::iterator iLastPos;
    iLastPos = copy ( l.begin (), l.end (), v.begin () );
    vector <int>::iterator i;
    i = remove (v.begin (), v.end (), 0);
    // Use this new "end position" to resize vector
    v.erase (i, v.end ());
    return 0;
}


Remove an element and then erase that element

  
 
/* The following code example is taken from the book
 * "The C++ Standard Library - A Tutorial and Reference"
 * by Nicolai M. Josuttis, Addison-Wesley, 1999
 *
 * (C) Copyright Nicolai M. Josuttis 1999.
 * Permission to copy, use, modify, sell and distribute this software
 * is granted provided this copyright notice appears in all copies.
 * This software is provided "as is" without express or implied
 * warranty, and with no claim as to its suitability for any purpose.
 */
#include <iostream>
#include <vector>
#include <deque>
#include <list>
#include <set>
#include <map>
#include <string>
#include <algorithm>
#include <iterator>
#include <functional>
#include <numeric>
/* PRINT_ELEMENTS()
 * - prints optional C-string optcstr followed by
 * - all elements of the collection coll
 * - separated by spaces
 */
template <class T>
inline void PRINT_ELEMENTS (const T& coll, const char* optcstr="")
{
    typename T::const_iterator pos;
    std::cout << optcstr;
    for (pos=coll.begin(); pos!=coll.end(); ++pos) {
        std::cout << *pos << " ";
    }
    std::cout << std::endl;
}
/* INSERT_ELEMENTS (collection, first, last)
 * - fill values from first to last into the collection
 * - NOTE: NO half-open range
 */
template <class T>
inline void INSERT_ELEMENTS (T& coll, int first, int last)
{
    for (int i=first; i<=last; ++i) {
        coll.insert(coll.end(),i);
    }
}
using namespace std;
int main()
{
    vector<int> coll;
    INSERT_ELEMENTS(coll,2,6);
    INSERT_ELEMENTS(coll,4,9);
    INSERT_ELEMENTS(coll,1,7);
    PRINT_ELEMENTS(coll,"coll:               ");
    // remove all elements with value 5
    vector<int>::iterator pos;
    pos = remove(coll.begin(), coll.end(),   // range
                 5);                         // value to remove
    PRINT_ELEMENTS(coll,"size not changed:   ");
    // erase the ""removed"" elements in the container
    coll.erase(pos, coll.end());
    PRINT_ELEMENTS(coll,"size changed:       ");
}
 /* 
coll:               2 3 4 5 6 4 5 6 7 8 9 1 2 3 4 5 6 7
size not changed:   2 3 4 6 4 6 7 8 9 1 2 3 4 6 7 5 6 7
size changed:       2 3 4 6 4 6 7 8 9 1 2 3 4 6 7
 */


Remove copy Elements if They Meet a Criterion

  
#include <algorithm>
#include <functional>
#include <vector>
#include <iostream>
using namespace std;
template <class T>
void print(T& c){
   for( typename T::iterator i = c.begin(); i != c.end(); i++ ){
      std::cout << *i << endl;
   }
}

template<class InputIterator, class OutputIterator, class Predicate >
OutputIterator copy_if( InputIterator start, InputIterator stop,OutputIterator out, Predicate select ){
   while( start != stop ){
      if( select( *start ) )
         *out++ = *start;
      ++start;
   }
   return out;
}
int main( )
{
   const int numbers = 7;
   const int num[numbers] = { -5, 0, 13, 20, 10, 4, -1 };
   vector<int> v1( num, num+numbers );
   print( v1 );
   vector<int> v2( num, num+numbers );
   
   vector<int>::const_iterator v2_copy_end = remove_copy_if( v1.begin(), v1.end(), v2.begin(),not1( bind2nd( greater<int>(), 10 ) ) );
   for( vector<int>::const_iterator i = v2.begin(); i != v2_copy_end;++i )
      cout << *i << " ";
}


remove empty string

  
#include <functional>
#include <algorithm>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
void removeEmptyStrings(vector<string>& strings)
{
  vector<string>::iterator it = remove_if(strings.begin(), strings.end(),mem_fun_ref(&string::empty));
  // erase the removed elements
  strings.erase(it, strings.end());
}
void printString(const string& str)
{
  cout << str << " ";
}
int main(int argc, char** argv)
{
  vector<string> myVector;
  myVector.push_back("A");
  myVector.push_back("B");
  myVector.push_back("C");
  myVector.push_back("D");
  myVector.push_back("E");
  myVector.push_back("F");
  removeEmptyStrings(myVector);
  cout << "Size is " << myVector.size() << endl;
  for_each(myVector.begin(), myVector.end(), &printString);
  cout << endl;
  return (0);
}


Use std::remove to delete all element in a vector by value

  
 
#include <iostream>
using std::cout;
using std::endl;
#include <algorithm>
#include <vector>
#include <iterator>
int main()
{
   int a[ 10 ] = { 10, 2, 10, 4, 16, 6, 14, 8, 12, 10 };
   std::ostream_iterator< int > output( cout, " " );
   std::vector< int > v( a, a + 10 ); // copy of a
   std::vector< int >::iterator newLastElement;
   cout << "Vector v before removing all 10s:\n   ";
   std::copy( v.begin(), v.end(), output );
   // remove all 10s from v
   newLastElement = std::remove( v.begin(), v.end(), 10 );
   cout << "\nVector v after removing all 10s:\n   ";
   std::copy( v.begin(), newLastElement, output );
   return 0;
}
/* 
Vector v before removing all 10s:
   10 2 10 4 16 6 14 8 12 10
Vector v after removing all 10s:
   2 4 16 6 14 8 12 
 */


Use the generic remove algorithm

  
 
#include <iostream>
#include <cassert>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
  const int  N = 11;
  int array1[N] = {1, 2, 0, 3, 4, 0, 5, 6, 7, 0, 8};
  vector<int> vector1;
  for (int i = 0; i < N; ++i)
    vector1.push_back(array1[i]);
  // Remove the zeros from vector1:
  vector<int>::iterator new_end;
  new_end = remove(vector1.begin(), vector1.end(), 0);
  for (int i = 0; i < (int)vector1.size(); ++i)
    cout << vector1[i];
  cout << "\n\n\n\n\n";
  // The size of vector1 remains the same:
  assert (vector1.size() == N);
  cout << vector1.size();
  cout << "\n\n\n\n\n";
  // The nonzero elements are left in [vector1.begin(), new_end).  Erase the rest:
  vector1.erase(new_end, vector1.end());
  // Show that 3 elements were removed and the nonzero elements remain, in their original order:
  assert (vector1.size() == N - 3);
  cout << vector1.size();
  cout << "\n\n\n\n\n";
  for (int i = 0; i < (int)vector1.size(); ++i)
    cout << vector1[i];
  return 0;
}
/* 
12345678708


11


8


12345678
 */