SET的完整用法

SET的第一行模板源码是这样的:

  template<typename _Key, typename _Compare = std::less<_Key>,
	   typename _Alloc = std::allocator<_Key> >

根据template和English的有关知识,我们可以知道set的定义方式应该是:
set<类型,比较函数(不写时默认为less<类型>,从小到大),空间配置器(从应用STL角度来说完全可以忽略,实际上也完全一定要忽略不写)>变量名

第110行:

      typedef _Rb_tree<key_type, value_type, _Identity<value_type>,
		       key_compare, _Key_alloc_type> _Rep_type;
      _Rep_type _M_t;  // Red-black tree representing set.

现在我们知道set是用红黑树来维护的。

按顺序 第149行:

      /**
       *  @brief  Builds a %set from a range.
       *  @param  first  An input iterator.
       *  @param  last  An input iterator.
       *
       *  Create a %set consisting of copies of the elements from [first,last).
       *  This is linear in N if the range is already sorted, and NlogN
       *  otherwise (where N is distance(first,last)).
       */
      template<typename _InputIterator>
        set(_InputIterator __first, _InputIterator __last)
	: _M_t()
        { _M_t._M_insert_unique(__first, __last); }

      /**
       *  @brief  Builds a %set from a range.
       *  @param  first  An input iterator.
       *  @param  last  An input iterator.
       *  @param  comp  A comparison functor.
       *  @param  a  An allocator object.
       *
       *  Create a %set consisting of copies of the elements from [first,last).
       *  This is linear in N if the range is already sorted, and NlogN
       *  otherwise (where N is distance(first,last)).
       */
      template<typename _InputIterator>
        set(_InputIterator __first, _InputIterator __last,
	    const _Compare& __comp,
	    const allocator_type& __a = allocator_type())
	: _M_t(__comp, __a)
        { _M_t._M_insert_unique(__first, __last); }

这个的意思是可以用迭代器初始化set(不懂可以看下面的测试代码),并且速度在数据有序的情况下为O(n)(常数偏大),无序的情况下为O(nlogn)(常数偏小)。

我的测试代码:

#include<bits/stdc++.h>
using namespace std;

vector<int>vec;
set<int>st;
int main()
{
	for(int i=1;i<=2000000;i++)
		vec.push_back(i);
	int t1 = clock();
	st = set<int>(vec.begin(),vec.end());
	printf("%d\n",clock()-t1);
	
	random_shuffle(vec.begin(),vec.end());
	t1=clock();
	st = set<int>(vec.begin(),vec.end());
	printf("%d\n",clock()-t1);
}

输出(不开O2):
1083
3007
输出(开O2):
724
1689
可以发现在开O2的情况下还是可以接受的,
100000个数只需要100ms左右。

219行

      /**
       *  @brief  %Set assignment operator.
       *  @param  x  A %set of identical element and allocator types.
       *
       *  All the elements of @a x are copied, but unlike the copy constructor,
       *  the allocator object is not copied.
       */
      set&
      operator=(const set& __x)
      {
	_M_t = __x._M_t;
	return *this;
      }

set的等于符号重载,O(n)
测试代码:

#include<bits/stdc++.h>
using namespace std;

vector<int>vec;
set<int>st;
int main()
{
	for(int i=1;i<=100000;i++)
		vec.push_back(i);
	int t1 = clock();
	st = set<int>(vec.begin(),vec.end());
	printf("%d\n",clock()-t1);
	
	t1=clock();
	set<int>st2 = st;
	printf("%d\n",clock()-t1);
}

输出 :
57
18

689行:

  template<typename _Key, typename _Compare, typename _Alloc>
    inline void
    swap(set<_Key, _Compare, _Alloc>& __x, set<_Key, _Compare, _Alloc>& __y)
    { __x.swap(__y); }

这个swap好像是直接交换指针的,O(1)

测试代码:

#include<bits/stdc++.h>
using namespace std;

vector<int>vec;
set<int>st;
int main()
{
	for(int i=1;i<=100000;i++)
		vec.push_back(i);
	int t1 = clock();
	st = set<int>(vec.begin(),vec.end());
	printf("%d\n",clock()-t1);
	
	t1=clock();
	set<int>st2;
	st2.swap(st);
	printf("%d\n",*st2.begin());
	printf("%d\n",clock()-t1);
}

输出:
57
1
0

943行:

      /**
       *  Erases all the elements.  Note that this function only erases the
       *  elements, and that if the elements themselves are pointers, the
       *  pointed-to memory is not touched in any way.  Managing the pointer is
       *  the user's responsibility.
       */
      void
      clear()
      { _M_erase_at_end(this->_M_impl._M_start); }

clear()函数,O(n)的。(Managing the pointer is the user’s responsibility.这话好绝,再也不用set装指针了)

测试代码:

#include<bits/stdc++.h>
using namespace std;

vector<int>vec;
set<int>st;
int main()
{
	for(int i=1;i<=100000;i++)
		vec.push_back(i);
	int t1 = clock();
	st = set<int>(vec.begin(),vec.end());
	printf("%d\n",clock()-t1);
	
	t1=clock();
	st.clear();
	printf("%d\n",clock()-t1);
}

输出:
53
10

272行:

      ///  Returns the comparison object with which the %set was constructed.
      key_compare
      key_comp() const
      { return _M_t.key_comp(); }

现在来解释一下比较函数。
因为STL比较强大,比较函数并不是一个函数,而是一个结构体,里面重载了()符号,用(a,b)代表比较a和b,并且返回一个值,1代表a<b,0otherwise(被STL注释语言同化了)
具体看下面代码应该能够有一些了解,需要一些template和结构体的前置知识。

测试代码:

#include<bits/stdc++.h>
using namespace std;

vector<int>vec;
set<int>st;

struct cmp
{
	bool operator ()(int u,int v){ return u<v; }
}a;

int main()
{
	printf("%d\n",a(2,1));
	printf("%d\n",a(1,2));
	less<int>b;
	printf("%d\n",b(1,2));
	greater<int>c;
	printf("%d\n",c(1,2));
}

输出:
0
1
1
0

285行,8种迭代器:

      /**
       *  Returns a read-only (constant) iterator that points to the first
       *  element in the %set.  Iteration is done in ascending order according
       *  to the keys.
       */
      iterator
      begin() const
      { return _M_t.begin(); }

      /**
       *  Returns a read-only (constant) iterator that points one past the last
       *  element in the %set.  Iteration is done in ascending order according
       *  to the keys.
       */
      iterator
      end() const
      { return _M_t.end(); }

      /**
       *  Returns a read-only (constant) iterator that points to the last
       *  element in the %set.  Iteration is done in descending order according
       *  to the keys.
       */
      reverse_iterator
      rbegin() const
      { return _M_t.rbegin(); }

      /**
       *  Returns a read-only (constant) reverse iterator that points to the
       *  last pair in the %set.  Iteration is done in descending order
       *  according to the keys.
       */
      reverse_iterator
      rend() const
      { return _M_t.rend(); }

#ifdef __GXX_EXPERIMENTAL_CXX0X__
      /**
       *  Returns a read-only (constant) iterator that points to the first
       *  element in the %set.  Iteration is done in ascending order according
       *  to the keys.
       */
      iterator
      cbegin() const
      { return _M_t.begin(); }

      /**
       *  Returns a read-only (constant) iterator that points one past the last
       *  element in the %set.  Iteration is done in ascending order according
       *  to the keys.
       */
      iterator
      cend() const
      { return _M_t.end(); }

      /**
       *  Returns a read-only (constant) iterator that points to the last
       *  element in the %set.  Iteration is done in descending order according
       *  to the keys.
       */
      reverse_iterator
      crbegin() const
      { return _M_t.rbegin(); }

      /**
       *  Returns a read-only (constant) reverse iterator that points to the
       *  last pair in the %set.  Iteration is done in descending order
       *  according to the keys.
       */
      reverse_iterator
      crend() const
      { return _M_t.rend(); }

好像前面加不加c都一样。。。迭代器就是一个变量只支持++和–,即只能迭代到下一个或上一个,因为这像迭代的过程,故名迭代器。
begin()是第一个,end()是最后一个的后一个(即是空),体现了STL左闭右开的风格。
rbegin()是最后一个,rend()是最前面的前面一个(即是空),体现了STL左闭右开的风格。

359行:

      ///  Returns true if the %set is empty.
      bool
      empty() const
      { return _M_t.empty(); }

      ///  Returns the size of the %set.
      size_type
      size() const
      { return _M_t.size(); }

size和empty,都是O(1)的。

#include<bits/stdc++.h>
using namespace std;

vector<int>vec;
set<int>st;
int main()
{
	for(int i=1;i<=1000000;i++) st.insert(i);
	int t1 = clock();
	printf("%d\n",st.size());
	printf("%d\n",st.empty());
	printf("%d\n",clock()-t1);
}

输出:
1000000
0
0
393行

      // insert/erase
      /**
       *  @brief Attempts to insert an element into the %set.
       *  @param  x  Element to be inserted.
       *  @return  A pair, of which the first element is an iterator that points
       *           to the possibly inserted element, and the second is a bool
       *           that is true if the element was actually inserted.
       *
       *  This function attempts to insert an element into the %set.  A %set
       *  relies on unique keys and thus an element is only inserted if it is
       *  not already present in the %set.
       *
       *  Insertion requires logarithmic time.
       */
      std::pair<iterator, bool>
      insert(const value_type& __x)
      {
	std::pair<typename _Rep_type::iterator, bool> __p =
	  _M_t._M_insert_unique(__x);
	return std::pair<iterator, bool>(__p.first, __p.second);
      }

insert是有返回值的!!!Insertion requires logarithmic time。。。
看注释应该就懂了,相同元素不重复插入,pair<set::iterater , bool>的前一个是插入的元素的迭代器,后一个是插入是否成功。
测试代码

#include<bits/stdc++.h>
using namespace std;

vector<int>vec;
set<int>st;
int main()
{
	pair<set<int>::iterator , bool>tmp = st.insert(1);
	printf("%d %d\n",*tmp.first,tmp.second);
	pair<set<int>::iterator , bool>res = st.insert(1);
	printf("%d %d\n",*res.first,res.second);
	pair<set<int>::iterator , bool>res1 = st.insert(2);
	printf("%d %d\n",*res1.first,res1.second);
}

输出:
1 1
1 0
2 1

415行:

      /**
       *  @brief Attempts to insert an element into the %set.
       *  @param  position  An iterator that serves as a hint as to where the
       *                    element should be inserted.
       *  @param  x  Element to be inserted.
       *  @return  An iterator that points to the element with key of @a x (may
       *           or may not be the element passed in).
       *
       *  This function is not concerned about whether the insertion took place,
       *  and thus does not return a boolean like the single-argument insert()
       *  does.  Note that the first parameter is only a hint and can
       *  potentially improve the performance of the insertion process.  A bad
       *  hint would cause no gains in efficiency.
       *
       *  For more on "hinting", see:
       *  http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt07ch17.html
       *  
       *  Insertion requires logarithmic time (if the hint is not taken).
       */
      iterator
      insert(iterator __position, const value_type& __x)
      { return _M_t._M_insert_unique_(__position, __x); }

指定位置的insert,能够potentially improve the performance of the insertion process.(卡常必备???)
测试代码:

#include<bits/stdc++.h>
using namespace std;

vector<int>vec;
set<int>st;
set<int>::iterator it;
int main()
{
	st.insert(1);
	int t1=clock();
	it = st.begin();
	for(int i=2;i<=100000;i++)
	{
		
		it++;
		st.insert(it,i);
		
		/*
		st.insert(i);
		*/
	}
	printf("%d\n",clock()-t1);
	printf("%d\n",st.size());

	st.clear();
	st.insert(1);
	t1=clock();
	it = st.begin();
	for(int i=2;i<=100000;i++)
	{
		/*
		it++;
		st.insert(it,i);
		*/
		
		st.insert(i);
		
	}
	printf("%d\n",clock()-t1);
	printf("%d\n",st.size());
}

输出:
30
100000
74
100000
效果好像还不错,vector初始化好像要55ms来着。。。

465行:

      /**
       *  @brief Erases an element from a %set.
       *  @param  position  An iterator pointing to the element to be erased.
       *
       *  This function erases an element, pointed to by the given iterator,
       *  from a %set.  Note that this function only erases the element, and
       *  that if the element is itself a pointer, the pointed-to memory is not
       *  touched in any way.  Managing the pointer is the user's responsibility.
       */
      void
      erase(iterator __position)
      { _M_t.erase(__position); }

      /**
       *  @brief Erases elements according to the provided key.
       *  @param  x  Key of element to be erased.
       *  @return  The number of elements erased.
       *
       *  This function erases all the elements located by the given key from
       *  a %set.
       *  Note that this function only erases the element, and that if
       *  the element is itself a pointer, the pointed-to memory is not touched
       *  in any way.  Managing the pointer is the user's responsibility.
       */
      size_type
      erase(const key_type& __x)
      { return _M_t.erase(__x); }

      /**
       *  @brief Erases a [first,last) range of elements from a %set.
       *  @param  first  Iterator pointing to the start of the range to be
       *                 erased.
       *  @param  last  Iterator pointing to the end of the range to be erased.
       *
       *  This function erases a sequence of elements from a %set.
       *  Note that this function only erases the element, and that if
       *  the element is itself a pointer, the pointed-to memory is not touched
       *  in any way.  Managing the pointer is the user's responsibility.
       */
      void
      erase(iterator __first, iterator __last)
      { _M_t.erase(__first, __last); }

用迭代器无返回值,用值删除会返回删除的个数(意味着用multiset的会将同一个值的删完),迭代器区间删除,作者也懒得分析复杂度了。

测试代码:

#include<bits/stdc++.h>
using namespace std;

vector<int>vec;
set<int>st;
set<int>::iterator it;
int main()
{
	st.insert(1);
	it = st.begin();
	for(int i=2;i<=1000000;i++)
	{
		it++;
		st.insert(it,i);
	}
	int t1=clock();
	printf("%d\n",st.erase(233));
	printf("%d\n",st.erase(233));
	for(int i=1;i<=100000;i++)
		st.erase(i);
	printf("%d\n",clock()-t1);
}

输出:
1
0
67
删除常数也可以接受吧。
518行:

      // set operations:

      /**
       *  @brief  Finds the number of elements.
       *  @param  x  Element to located.
       *  @return  Number of elements with specified key.
       *
       *  This function only makes sense for multisets; for set the result will
       *  either be 0 (not present) or 1 (present).
       */
      size_type
      count(const key_type& __x) const
      { return _M_t.find(__x) == _M_t.end() ? 0 : 1; }

这代码好露骨啊。
535行:

      /**
       *  @brief Tries to locate an element in a %set.
       *  @param  x  Element to be located.
       *  @return  Iterator pointing to sought-after element, or end() if not
       *           found.
       *
       *  This function takes a key and tries to locate the element with which
       *  the key matches.  If successful the function returns an iterator
       *  pointing to the sought after element.  If unsuccessful it returns the
       *  past-the-end ( @c end() ) iterator.
       */
      iterator
      find(const key_type& __x)
      { return _M_t.find(__x); }

      const_iterator
      find(const key_type& __x) const
      { return _M_t.find(__x); }

find函数,返回迭代器,没有就返回end();
关于后面那个函数我的理解是,set如果是const的就返回const_iterator,欢迎评论。

557行:

      /**
       *  @brief Finds the beginning of a subsequence matching given key.
       *  @param  x  Key to be located.
       *  @return  Iterator pointing to first element equal to or greater
       *           than key, or end().
       *
       *  This function returns the first element of a subsequence of elements
       *  that matches the given key.  If unsuccessful it returns an iterator
       *  pointing to the first element that has a greater value than given key
       *  or end() if no such element exists.
       */
      iterator
      lower_bound(const key_type& __x)
      { return _M_t.lower_bound(__x); }

      const_iterator
      lower_bound(const key_type& __x) const
      { return _M_t.lower_bound(__x); }
      //@}

      //@{
      /**
       *  @brief Finds the end of a subsequence matching given key.
       *  @param  x  Key to be located.
       *  @return Iterator pointing to the first element
       *          greater than key, or end().
       */
      iterator
      upper_bound(const key_type& __x)
      { return _M_t.upper_bound(__x); }

      const_iterator
      upper_bound(const key_type& __x) const
      { return _M_t.upper_bound(__x); }

lower_bound()和upper_bound(),意义显然。

594行:

       *  @brief Finds a subsequence matching given key.
       *  @param  x  Key to be located.
       *  @return  Pair of iterators that possibly points to the subsequence
       *           matching given key.
       *
       *  This function is equivalent to
       *  @code
       *    std::make_pair(c.lower_bound(val),
       *                   c.upper_bound(val))
       *  @endcode
       *  (but is faster than making the calls separately).
       *
       *  This function probably only makes sense for multisets.
       */
      std::pair<iterator, iterator>
      equal_range(const key_type& __x)
      { return _M_t.equal_range(__x); }

      std::pair<const_iterator, const_iterator>
      equal_range(const key_type& __x) const
      { return _M_t.equal_range(__x); }

一次计算出lower_bound(x)和upper_bound(x)况且只用一次的时间。。。。好像很有用(吗?)。equal_range…

627行:

  /**
   *  @brief  Set equality comparison.
   *  @param  x  A %set.
   *  @param  y  A %set of the same type as @a x.
   *  @return  True iff the size and elements of the sets are equal.
   *
   *  This is an equivalence relation.  It is linear in the size of the sets.
   *  Sets are considered equivalent if their sizes are equal, and if
   *  corresponding elements compare equal.
  */
  template<typename _Key, typename _Compare, typename _Alloc>
    inline bool
    operator==(const set<_Key, _Compare, _Alloc>& __x,
	       const set<_Key, _Compare, _Alloc>& __y)
    { return __x._M_t == __y._M_t; }

  /**
   *  @brief  Set ordering relation.
   *  @param  x  A %set.
   *  @param  y  A %set of the same type as @a x.
   *  @return  True iff @a x is lexicographically less than @a y.
   *
   *  This is a total ordering relation.  It is linear in the size of the
   *  maps.  The elements must be comparable with @c <.
   *
   *  See std::lexicographical_compare() for how the determination is made.
  */
  template<typename _Key, typename _Compare, typename _Alloc>
    inline bool
    operator<(const set<_Key, _Compare, _Alloc>& __x,
	      const set<_Key, _Compare, _Alloc>& __y)
    { return __x._M_t < __y._M_t; }

set的大小比较,<号被定义为字典序???线性复杂度。
multiset就是支持重复元素而已,记得erase的区别,很致命。。。。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值