简体   繁体   English

C++ STL 按值设置擦除

[英]C++ STL Set Erase by Value

I want to remove an element from std::set .我想从std::set删除一个元素。

I am aware that the best and straightforward practice is to check its existence in the set using set<T>::find(T val) method, and then erase it using the returned set<T>::iterator .我知道最好和直接的做法是使用set<T>::find(T val)方法检查它在集合中的存在,然后使用返回的set<T>::iterator擦除它。 But I wish to use the shorthand method of erasing by value.但我希望使用按值擦除的速记方法。

Even though std::set does provide that through the overloaded function set<T>::erase(T val) to erase by value as listed here , I couldn't find what happens if the value does not exist in the set.尽管std::set确实通过重载函数set<T>::erase(T val)提供了按此处列出的值擦除,但我无法找到如果该值不存在于集合中会发生什么。

As one would intuitively expect, does it do nothing if the argument value does not exist in the set?正如人们直觉所期望的那样,如果参数值在集合中不存在,它是否什么都不做 Is it guaranteed that it won't throw any error/exception?是否保证它不会抛出任何错误/异常?

std::set abides by associative container requirements of 26.2.6 associative.reqmts . std::set遵守26.2.6 associative.reqmts 的关联容器要求。

It returns the number of actual erased elements, which for std::set must be zero or one, dependent on existence.它返回实际擦除元素的数量,对于std::set必须为零或一,取决于存在。 Per 26.2.6.1 associative.reqmts.except , it is only guaranteed not to throw if the container comparator (which can be customized, obviously) does not throw when used during the search.根据26.2.6.1 associative.reqmts.except ,只有在搜索期间使用容器比较器(显然可以自定义)不抛出时,才保证不抛出。

From cplusplus来自cplusplus

(1) void erase (iterator position); (1)voiderase(迭代器位置);

(2) size_type erase (const value_type& val); (2) size_type擦除(const value_type&val);

(3) void erase (iterator first, iterator last); (3) void erase (iterator first, iterator last);

Return value返回值

For the value-based version (2), the function returns the number of elements erased.对于基于值的版本 (2),该函数返回擦除的元素数。

Member type size_type is an unsigned integral type成员类型 size_type 是无符号整数类型


So it returns 0 if no elements are erased.因此,如果没有删除任何元素,则返回 0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM