C ++ delete all the characters from the string in a particular [Reserved]

Reprinted from https://www.cnblogs.com/7z7chn/p/6341453.html

 

C ++, from stringdelete all of a particular character, the following code can be used

str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());

Which,  removefrom <algorithm>its signature is

template <class ForwardIterator, class T>
  ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val);

Role: In a container, delete [first, last)all values equal to between valthe values.

Delete method: an equal valwith the next value is not equal to valthe value of coverage.

Returns: an iterator (denoted newEnd), the iterator to the next element of the last element has not been deleted, which is equivalent to the new vessel end.

So run to completion remove, the container [first, newEnd)elements within that is not deleted all the elements  [newEnd, end)between the elements has been useless.

In this way, then run str.erase(newEnd, str.end())to empty the [newEnd, end)elements between.

std::remove_ifAnd removesimilar, except that it accepts a third argument is a function.

// remove_if example
#include <iostream>     // std::cout
#include <algorithm>    // std::remove_if

bool IsOdd (int i) { return ((i%2)==1); }

int main () {
  int myints[] = {1,2,3,4,5,6,7,8,9};            // 1 2 3 4 5 6 7 8 9

  // bounds of range:
  int* pbegin = myints;                          // ^
  int* pend = myints+sizeof(myints)/sizeof(int); // ^                 ^

  pend = std::remove_if (pbegin, pend, IsOdd);   // 2 4 6 8 ? ? ? ? ?
                                                 // ^       ^
  std::cout << "the range contains:";
  for (int* p=pbegin; p!=pend; ++p)
    std::cout << ' ' << *p;
  std::cout << '\n';

  return 0;
}

Output:

myvector contains: 10 30 30 10 10 0 0 0

There is a std::remove_copysignature:

template <class InputIterator, class OutputIterator, class T>
  OutputIterator remove_copy (InputIterator first, InputIterator last,
                              OutputIterator result, const T& val);

It will [first, last)not equal between valthe elements from the resultcontainer of the copy start.

// remove_copy example
#include <iostream>     // std::cout
#include <algorithm>    // std::remove_copy
#include <vector>       // std::vector

int main () {
  int myints[] = {10,20,30,30,20,10,10,20};               // 10 20 30 30 20 10 10 20
  std::vector<int> myvector (8);

  std::remove_copy (myints,myints+8,myvector.begin(),20); // 10 30 30 10 10 0 0 0

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

Output:

myvector contains: 10 30 30 10 10 0 0 0

 

 

Guess you like

Origin www.cnblogs.com/nxopen2018/p/11697947.html