10017set02大小和交换

168 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第6天,点击查看活动详情

1.1 set大小和交换

1.2 功能描述:

  • 统计set容器大小以及交换set容器

1.3 函数原型:

  • size(); //返回容器中元素的数目
  • empty(); //判断容器是否为空
  • swap(st); //交换两个集合容器

1.4 代码示例:

#include <set>

void printSet(set<int> & s)
{
	for (set<int>::iterator it = s.begin(); it != s.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}

//大小
void test01()
{

	set<int> s1;
	
	s1.insert(10);
	s1.insert(30);
	s1.insert(20);
	s1.insert(40);

	if (s1.empty())
	{
		cout << "s1为空" << endl;
	}
	else
	{
		cout << "s1不为空" << endl;
		cout << "s1的大小为: " << s1.size() << endl;
	}

}

//交换
void test02()
{
	set<int> s1;

	s1.insert(10);
	s1.insert(30);
	s1.insert(20);
	s1.insert(40);

	set<int> s2;

	s2.insert(100);
	s2.insert(300);
	s2.insert(200);
	s2.insert(400);

	cout << "交换前" << endl;
	printSet(s1);
	printSet(s2);
	cout << endl;

	cout << "交换后" << endl;
	s1.swap(s2);
	printSet(s1);
	printSet(s2);
}

int main() {

	//test01();

	test02();

	system("pause");

	return 0;
}

总结:

  • 统计大小 --- size
  • 判断是否为空 --- empty
  • 交换容器 --- swap

1.5 C ++ STL set :: size()函数 (C++ STL set::size() function)

set::size() function is a predefined function, it is used to get the size of a set, it returns the total number of elements of the set container.

set :: size()函数是预定义的函数,用于获取集合的大小,它返回集合容器中元素的总数。

Prototype:

原型:

set<T> st; //declaration
 set<T>::iterator it; //iterator declaration
 int sz=st.size();

Parameter:  Nothing to pass

参数: 无通过

Return type:  Integer

返回类型: 整数

Usage:  The function returns size of the set

用法: 该函数返回集合的大小

For a set of integer,
    set<int> st;
    set<int>::iterator it;
    st.insert(4);
    st.insert(5);
    set content:
        4
        5
 
    int sz=st.size(); //sz=size of set that is 2
    Print sz; //prints 2
  • 与其他序列式容器相比,list和forward_list最大的缺陷是不支持任意位置的随机访问
  • 比如:要访问list的第6个元素,必须从已知的位置(比如头部或者尾部)迭代到该位置,在这段位置上迭代需要线性的时间开销;
  • list还需要一些额外的空间,以保存每个节点的相关联信息(对于存储类型较小元素的大list来说这可能是一个重要的因素。