Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stl remove-erase #11

Open
coneo opened this issue Apr 6, 2015 · 1 comment
Open

stl remove-erase #11

coneo opened this issue Apr 6, 2015 · 1 comment
Labels

Comments

@coneo
Copy link
Owner

coneo commented Apr 6, 2015

对于forward迭代器的容器,我们可以使用remove来删除元素。但是需要注意一点的是,remove需要配置容器相应的erase函数使用,不然无法达到删除元素的效果。这就是我们所称的remove-erase语义。下面会详细的对其说明。

先看下remove和remove_if的声明:

template< class ForwardIt, class T >
ForwardIt remove( ForwardIt first, ForwardIt last, const T& value );


template< class ForwardIt, class UnaryPredicate >
ForwardIt remove_if( ForwardIt first, ForwardIt last, UnaryPredicate p );

remove会在first和last迭代器的左开区间 [first, last) 去找元素value,把找到的value的迭代器放到容器的最后。并不会真正的删除元素value,只是对容器进行一个重排,所以在remove之后,其size并不会变。这样我们就可以根据remove返回的迭代器进行真正的删除了。使用方式如下:

vector<int> a {1, 2, 3, 4};                                 // {1, 2, 3, 4}
a.erase(std::remove(a.begin(), b.end(), 2),   a.end());     // {1, 3, 4}

由于remove针对前置迭代器,那么原生指针也可以使用:
int a[] = {1, 2, 3, 4};

看下面一个例子:

int main()
{
  vector<int> l;
  l.push_back(1);
  .push_back(2);
  l.push_back(3);
  l.push_back(4);
  l.push_back(3);
  printList(l);     // 1 2 3 4 3 

  std::remove(l.begin(), l.end(), 3);
  printList(l);    // 1 2 4 4 3

  l.erase(std::remove(l.begin(), l.end(), 3), l.end());
  printList(l);     // 1 2 4 4
}

btw: 为毛要给这个函数起一个remove的名字。

@coneo coneo added the c&c++ label Apr 6, 2015
@Huangtuzhi
Copy link

可能是因为re-move吧

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants