C/C++教程

C++ set集合测试

本文主要是介绍C++ set集合测试,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一、概述

  案例:c++ stl之set集合练习

二、代码示例

#include <iostream>
#include <set>
#include <string>

using namespace std;

//打印set元素
void printSet(set<int> &s){
	for(set<int>::iterator it=s.begin();it!=s.end();it++){
		cout << *it<<" ";
	}
	cout <<endl;
}
void test(){
	set<int> s;
	//向set集合中添加元素
	s.insert(10);
	s.insert(20);
	s.insert(30);
	s.insert(40);
	s.insert(30);
	printSet(s);

	if(s.empty()){
		cout << "set is Null"<<endl;
	}else{
		cout << "set is Not Null"<<endl;
	}
	//删除元素为30的元素
	s.erase(30);
	printSet(s);
}

void test2(){
	set<int> s;
	s.insert(10);
	s.insert(20);
	s.insert(30);
	s.insert(40);
	s.insert(50);
	s.insert(60);

	set<int>::iterator pos = s.find(30);
	if(pos!=s.end()){
		cout << "I found element:"<<*pos<<endl;
	}else{
		cout <<"I Not Found Element"<<endl;
	}

	int num = s.count(40);
	cout <<"key=40 size is :"<<num<<endl;

	set<int>::iterator pos2 = s.lower_bound(30);

	if (pos2 != s.end())
	{
		cout << "lower_bound value is:" << *pos2 << endl;
	}
	else
	{
		cout << "lower_bound value not fond" << endl;
	}

	pos2 = s.upper_bound(30);
	if (pos2 != s.end())
	{
		cout << "upper_bound value is :" << *pos2 << endl;
	}
	else
	{
		cout << "upper_bound value not found" << endl;
	}
	//
	pair<set<int>::iterator,set<int>::iterator> ret = s.equal_range(30);
	if(ret.first!=s.end()){
		cout << "equal_range lower_bound value is:" << *ret.first << endl;
	}else
	{
		cout << "equal_range lower_bound value not found" << endl;
	}


	if (ret.second != s.end())
	{
		cout << "equal_range upper_bound value is:" << *ret.second << endl;
	}
	else
	{
		cout << "equal_range upper_bound value not found" << endl;
	}
}

void test3(){
	pair<string,int> p("tony",30);
	cout << "name: "<<p.first<< " age:"<<p.second<<endl;

	pair<string,int> p2 = make_pair("luoluoyang",3);
	cout << "name: "<< p2.first<<" age: "<<p2.second<<endl; 
}


void test4(){
	set<int> s;
	pair<set<int>::iterator,bool> ret = s.insert(10);
	if(ret.second){
		cout << "insert success"<<endl;
	}else{
		cout << "insert fail"<<endl;
	}

	ret = s.insert(10);
	if(ret.second){
		cout <<"second insert success"<<endl;
	}else{
		cout <<"second insert fail"<<endl;
	}
	printSet(s);


}

void test5(){
	
}

/**
 * 
 * set集合的特性:可以过滤掉重复的元素
 * */
int main(int argc, char const *argv[])
{
	// test();
	// test2();
	// test3();
	test4();
	return 0;
}

  

这篇关于C++ set集合测试的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!