STL容器的集合操作:
1.二叉树类型的或者其它序列类型的容器可以将集合运算结果放置到vector中,vector可以resize下大小(string也可以resize)。
2.自定义类型的结构体进行集合运算,那么需要重载operator <运算符,记得该成员函数是const的。
3.常用的集合操作
1)交集 set_intersection
2)并集 set_union
3) 差集 set_difference
差是A-B那么是:
vector<tagstudent> result;
result.resize( A.size() + B.size() );
vector<tagstudent>:iterator retEndPos = set_difference( A.begin(), A.end(), B.begin(), B.end() , result.begin());
4)对称差 set_symmetric_difference
对称差指只属于A或B,但不同时属于A和B的.实际上就是A和B的并集 与 A和B交集的 差集。
A差B是:
retEndPos = set_symmetric_difference( A.begin(), A.end(), B.begin(), B.end() , result.begin());
差集代码示例:
#include <iostream> #include <vector> #include <map> #include <set> #include <utility> #include <string> #include <algorithm> using namespace std; struct tagstudent { int m_nid; int m_nscore; /*tagstudent& operator =(const tagstudent &b) { this->m_nid = b.m_nid; this->m_nscore = b.m_nscore; return *this; }*/ /*tagstudent( const tagstudent &b) { this->m_nid = b.m_nid; this->m_nscore = b.m_nscore; }*/ tagstudent( int nid, int nscore ) { this->m_nid = nid; this->m_nscore = nscore; } // 用于resize时候用的默认构造函数 tagstudent() { this->m_nid = 0; this->m_nscore = 0; } // 小于运算符用于集合运算 bool operator<(const tagstudent &b) const { if( this->m_nid < b.m_nid ) { return true; } else if(this->m_nid == b.m_nid ) { if( this->m_nscore < b.m_nscore ) { return true; } else { return false; } } else { return false; } } }; int main() { set<tagstudent> one; one.insert(tagstudent(1,10)); one.insert(tagstudent(2,20)); one.insert(tagstudent(3,30)); one.insert(tagstudent(4,40)); //one.insert(33); set<tagstudent> two; two.insert(tagstudent(1,10)); two.insert(tagstudent(4,40)); two.insert(tagstudent(5,50)); vector<tagstudent> result; //result是用来保存one和two的交,并,差集的.自然要保定它的大小.要能装得下one,two两者元素之和. result.resize( one.size() + two.size() ); vector<tagstudent>::iterator retEndPos; //这是那些算法函数返回的结果 retEndPos = set_difference( one.begin(), one.end(), two.begin(), two.end() , result.begin()); result.resize( retEndPos - result.begin() ) ; //此时result中元素为 22 33 system("pause"); return 0; };