C++ステップSTL-2

21217 ワード

目次
 
基本理論容器——アルゴリズム——反復器
string容器
swapテクニック
Dequeコンテナ基本操作
deque採点事例
set容器
グループ練習
map容器
mutimap従業員グループ
深いコピーと浅いコピーの問題
関数オブジェクト
一元二元関数オブジェクトと一元二元述語
定義済み関数オブジェクト
基本理論容器——アルゴリズム——反復器
コンテナにはコンテナをネストすることができ、コンテナはシーケンスコンテナと関連コンテナに分けることができます.
シーケンスコンテナ:コンテナの要素の位置は、コンテナに入るタイミングと場所によって決まります.
関連コンテナ:コンテナにはルールがあり、コンテナに入る要素の位置はタイミングや場所によって決まりません.
反復器:ポインタと理解でき、ポインタの操作は基本的に反復器に対して操作できます.実際、反復器はポインタをカプセル化するクラスです.
アルゴリズム:限られたステップで問題を解決します.
STL容器、アルゴリズム、反復器分離事例
//  :           
int mycount(int* start,int* end, int val){
    int num = 0;
    while(start != end){
        if(*start == val){
            num++;
        }
        start++;
    }
    return num;
}
int main(){
    int arr[] = {0,7,5,4,9,2,0};
    int* pBegin = arr;
    int* pEnd = &(arr[szeof(arr)/sizeof(int)]);
    int num = mycount(pBegin,pEnd,0);
    cout<
//STL    
void test01(){
    //      ,                Int;
    vector v;
    v.push_back(10);
    v.push_back(20);
    v.push_back(30);
    v.push_back(40);

    //  STL   for_each  
    //        
    //vector::iterator      
    vector::iterator pBegin = v.begin();
    vector::iterator pEnd = v.end();
    
    //              ,             。
    for_each(pBegin,pEnd,PrintVector);
    
}

//              
class Person{
public:
    Person(int age, int id):age(age),id(id){}
public:
    int age;
    int id;
}
void test02(){
    
    //    ,            Person;
    vector v;
    Person p1(10,20), p2(30,40), p3(50,60);
    v.push_back(p1);
    v.push_back(p2);
    v.push_back(p3);

    //  
    for(vector::iterator it = v.begin(); it!=v.end(); it++){
        cout<

string容器
char*とstringの対比:stringはchar*をカプセル化し、この文字列を管理し、char*型のコンテナです.
stringはfind,copy,delete,replace,insertの多くの実用的なメンバーメソッドをカプセル化している.
メモリの解放と境界を考慮する必要はありません.
stringとchar*は互いに変換できます:stringはchar*を回転してstringを通じて提供するc_を回転しますstrメソッド.
string操作
#include
#include
using namespace std;
//char*  string  
void test01(){
    //string     char*   
    string s = "abc";
    const char* str = s.c_str();
    
    //char*     string     
    char* str2 = "abcd";
    string s2(str2);
}

//string   
void test02(){
    string s;//  
    string s2 = "abcd";
    string s3(s2);
    string s4(10,'c');
    cout< s2"<

swapテクニック
#include
#include
using namespace std;

void print(vector& v){
    for(vector::iterator it = v.begin(); it != v.end(); it++){
        cout< v1,v2;
    for(int i = 0; i < 5; i++){
        v1.push_back(i);
    }
    for(int i=6; i < 10; i++){
        v2.push_back(i);
    }
    print(v1);
    print(v2);
    v1.swap(v2);
    cout< v;
	v.resize(100);

	cout << "  :" << v.capacity() << endl;
	cout << "  :" << v.size() << endl;

	v.clear();
	v.push_back(2);
	v.push_back(3);

	cout << "  :" << v.capacity() << endl;
	cout << "  :" << v.size() << endl;

	vector(v).swap(v);

	cout << "  :" << v.capacity() << endl;
	cout << "  :" << v.size() << endl;
	

	system("pause");
	return EXIT_SUCCESS;
}

Dequeコンテナ基本操作
#niclude
#include
using namespace std;

//deque     
void test01(){
    deque d1;//      
    deque d2(10,5);//       
    deque d3(d2..begin(),d2.end());
    deque d4(d3);//    
}

//deque    
void test02(){
    deque d1(10,3);
    deque d;
    d.assign(10,5);//d.assign(d1.begin(),d1.end());
    d = d1;
}

//    
void test03(){
    deque d1(10,3);
    cout<::iterator it = d.begin(); it != d.end(); it++){
		cout << *it << " ";
	}
	cout << endl;
    //    
	/*
		while (d.size() > 0){
		cout << d.back() << "   !" << endl;
		d.pop_back();
	}
	cout << "  :" << d.size() << endl;
	*/

    //   
	while (!d.empty()){
		cout << d.front() << "   !" << endl;
		d.pop_front();
	}
//deque    
void test06(){
	
	deque d;
	d.insert(d.begin(),100); //   
	d.insert(d.end(), 200); //   

	for (deque::iterator it = d.begin(); it != d.end(); it++){
		cout << *it << " ";
	}
	cout << endl;
}

int main(){


	//test03();
	//test04();
	test06();

	system("pause");
	return EXIT_SUCCESS;
}

deque採点事例
#include
#include
#include
#include
#include
using namespace std;
//      (sort    )
//  5   (  ,  ),10    5       
//    :     ,     ,     
//    5       

//   
class Player{
public:
    Player(){}
    Player(string name,int score):mName(name),mScore(score){}
public:
    string mName;
    int mScore;
}

//    
void Create_Player(vector& v){
    string nameSeed = "ABCDE";
    for(int i = 0; i < 5; i++){
        Player p;
        p.mName = "  ";
        p.mName+=nameSeed[i];
        p.mScore = 0;

        v.push_back(p);
    }
}

void PrintScore(int val){
    cout<& v){
    for(vector::iterator it = v.begin();it!=v.end();it++){
        //        
        deque dScore;
        for(int i=0;i<10;i++){
            int score = rand()%41+60;
            dScore.push_back(score);
        }
        //     ,      
        sort(dScore.begin(),dScore.end());
        //for_each(dScore.begin(),dScore.end(),PrintScore);
        //cout<::iterator dit = dScore.begin();dit!=dScore.end();dit++){
            totalScore+=(*dit);
        }
        int aveScore = totalScore/dScore.size();
        //    
        (*it).mScore = aveScore;
    }
}

set容器
#include
#include//       
#include
#include
#include
using namespace std;

//   
void test01(){
    set myset;//    
    set myset2(myset)//    
}

void printSet(set& myset){
    for(set::iterator it = myset.begin();it!=myset.end();it++){
        cout< myset;//    
    myset.insert(4);
    myset.insert(2);
    myset.insert(1);
    myset.insert(5);
    myset.insert(2);

    printSet(myset);

    //  
    myset.erase(myset.begin());//       
    myset.erase(2);//       
    printSet(myset);
    myset.erase(myset.begin();myset.end());//myset.clear();
    cout<
class mycompare03{
public:
    bool operator()(T v1,T v2){
        return v1>v2;
    }
};

//set    
void test03(){
    //    
    //mycompare03 mycom;
    //mycom(10);//    ,   
    set> myset;//        
    myset.insert(4);
    myset.insert(2);
    myset.insert(1);
    myset.insert(5);

    for(set>::iterator it = myset.begin();it!=myset.end();it++){
        cout<t2.id;
    }
};
void test04(){
    set myset;
    Teacher t1(1,2),t2(3,4),t3(5,6);

    myset.insert(t1);
    myset.insert(t2);
    myset.insert(t3);

    for(set::iterator it=myset.begin();it!=myset.end();it++){
        cout<id<age< myset;
	myset.insert(10);
	myset.insert(5);
	myset.insert(1);
	myset.insert(8);

	set::iterator pos = myset.lower_bound(5);  //      5    
	if (pos == myset.end()){
		cout << "    !" << endl;
	}
	else{
		cout << "  :" << *pos << endl;
	}

	pos = myset.upper_bound(5);
	if (pos == myset.end()){
		cout << "    !" << endl;
	}
	else{
		cout << "  :" << *pos << endl;
	}

	pair::iterator, set::iterator> pos2 =  myset.equal_range(5);
	if (pos2.first == myset.end()){
		cout << "meiyouzhaodao!" << endl;
	}
	else{
		cout << "zhaodao!" << *(pos2.first) << endl;
	}

	if (pos2.second == myset.end()){
		cout << "meiyouzhaodao!" << endl;
	}
	else{
		cout << "zhaodao!" << *(pos2.second) << endl;
	}

}



グループ練習
#include
#include
using namespace std;

int main(){
    //          pair
    pair mypair(10,"aaa");
    cout< mypair2 = make_pair("aaa","bbb");
    //auto mypair2 = make_pair("aaa","bbb");
    cout< mypair3 = mypair;//    

    system("pause");
    return EXIT_SUCCESS;
}

map容器
#include
#include
#include
using namespace std;

//map     
void test01(){
    //map       ,    key   value  
    map mymap;//    
    map mymap2(mymap);//    
}

//map    
void test02(){
    map mymap;
    //       
    mymap.insert(pair(1,5));
    //   
    pair::iterator,bool> ret = mymap.insert(make_pair(2,10));
    if(ret.second){
        cout<::value_type(3,15));
    //   
    //mymap[4] = 20;

    //        :
    //  Key  ,       key    
    
    for(map::iterator it=mymap.begin();it!=mymap.end();it++){
        cout<first<second<::value_type(2,10));
    if(ret.second){
        cout<& mymap){
    for (map::iterator it = mymap.begin(); it != mymap.end();it++){
		cout << it->first << " " << it->second << " ";
    }
    cout< mymap;
	mymap.insert(make_pair(1, 2));
	mymap.insert(make_pair(2, 3));
	mymap.insert(make_pair(3, 4));

    //  
    map::iterator pos = mymap.find(3);
    if(pos == mymap.end()){
        cout<first<>second<first << " value:" << pos->second << endl;
	}

	pos = mymap.upper_bound(2);
	if (pos == mymap.end()){
		cout << "    !" << endl;
	}
	else{
		cout << "   :" << pos->first << " value:" << pos->second << endl;
	}

	pair::iterator, map::iterator> pos2 = mymap.equal_range(2);
	if (pos2.first == mymap.end()){  //      
		cout << "    !" << endl;
	}
	else{
		cout << "   :" << pos2.first->first << " value:" << pos2.first->second << endl;
	}

	if (pos2.second == mymap.end()){ //      
		cout << "    !" << endl;
	}
	else{
		cout << "   :" << pos2.second->first << " value:" << pos2.second->second << endl;
	}
}

mutimap従業員グループ
#include
#include
#include
#include
using namespace std;
#define SALE_DEPARTMENT  1 //   
#define DEVELOP_DEPARTMENT 2 //   
#define FINACIAL_DEPARTMENT 3 //   
class Yuangong{
public:
    string name;
    int age;
    string tele;
    double salary;
};

//    5 
void Create_Yuangong(vector& v){
    string namesed = "ABCDE";
    for(int i=0;i<5;i++){
        Yuangong yg;
        yg.name = "  ";
        yg.name += nameseed[i];

        yg.age = rand()%30;
        yg.salary = rand()%10000+10000;
        yg.tele = "86-88888888";

        v.push_back(yg);
    }
}

//       
void Set_YG_Group(vector& v,mutimap& group){
    for(vector::iterator it = v.begin(); it!=v.end();it++){
        cout<name<age<salary<tele;<& group){
    int departmentID = -1;
    while(true){
        cout<3){
            continue;
        }

        mutimap::iterator pos = group.find(departmentId);
        int ygcount = group.count(departmentID);
        int num = 0;
        while(pos != group.end()&&numsecond.name << "   :" << pos->second.age <<  "   " << pos->second.salary << "   " << pos->second.tele <<  endl;
			num++;
			pos++;
		}
    }
} 

int main(){

	//multimap   
	//        5    ,5          ,             
	//     :               
	//   Multimap              
	//                  

	vector v;  //           
	multimap Ygroup;  //          
	Create_Yuangong(v); //    
	Set_YG_Group(v, Ygroup); //    
	Show_YG_Info(Ygroup); //         

	system("pause");
	return EXIT_SUCCESS;
}

深いコピーと浅いコピーの問題
#include
#include
using namespace std;

class Teacher{
public:
    Teacher(char* name,int age){
        int len = strlen(name)+1;
        this->name = new char[len];
        strcpy(this->name,name);

        this->age = age;
    }
    //    
    Teacher(const Teacher& t){
        int len = strlen(t.name)+1;
        this->name = new char[len];
        strcpy(this->name,t.name);

        this->age = t.age;
    }

    //  
    Teacher& operator=(Teacher& t){
        int len = strlen(t.name)+1;
        if(this->name!=NULL){
            delete[] this->name;
        }
        this->name = new char[len];
        strcpy(this->name,t.name);

        this->age = t.age;
        return *this;
    }
    ~Teacher(){
        if(this->name!=NULL){
            delete[] this->name;
        }
        this->age = 0;
    }
    
    char* name;
    int age;
};
void test01(){
    Teacher t1("aaa",20);
    vector v;
    v.push_back(t1);
}
int main(){
    test01();
    system("pause");
    return EXIT_SUCCESS;
}

関数オブジェクト
#include
#include
#include
#include
using namespace std;

void print(){
    cout< v;
	for (int i = 0; i < 10;i++){
		v.push_back(i);
	}

	myprint04 myp04;
	myprint04 myp05 = for_each(v.begin(), v.end(), myp04); //       
	cout << "count:" << myp04.count << endl; cout << endl;
	cout << "count:" << myp05.count << endl; cout << endl;
}

一元二元関数オブジェクトと一元二元述語
#include
#include
#include
using namespace std;


//               ,           
//               ,          

//                     ,      Bool,     
//                     ,      Bool,     



//            : for_each
class print{
public:
	void operator()(int v){
		cout << v << " ";
	}
};

void print2(int v){
	cout << v << " ";
}
void test01(){
	
	vector v;
	for (int i = 0; i < 10;i++){
		v.push_back(i);
	}

	//print p;
	//for_each(v.begin(), v.end(), print());  //    
	for_each(v.begin(), v.end(), print2); //    
	cout << endl;
}


//         :find_if
class mycompare{
public:
	bool operator()(int v){
		if (v > 7){
			return true;
		}
		else{
			return false;
		}
	}
};
void test02(){
	
	vector v;
	for (int i = 0; i < 10; i++){
		v.push_back(i);
	}


	/*
		
		template inline
		_InIt find_if(_InIt _First, _InIt _Last, _Pr _Pred)
		{	// find first satisfying _Pred
		_DEBUG_RANGE(_First, _Last);
		_DEBUG_POINTER(_Pred);
		return (_Rechecked(_First,
		_Find_if(_Unchecked(_First), _Unchecked(_Last), _Pred)));
		}


		template inline
		_InIt _Find_if(_InIt _First, _InIt _Last, _Pr _Pred)
		{	// find first satisfying _Pred
		for (; _First != _Last; ++_First)
		if (_Pred(*_First))
		break;
		return (_First);
		}

	
	*/

	vector::iterator pos = find_if(v.begin(), v.end(), mycompare()); //      
	if(pos == v.end()){
		cout << "   " << endl;
	}
	else{
		cout << "  :" << *pos << endl;
	}

}

//            : transform
class myplus{
public:
	int operator()(int v1,int v2){
		return v1 + v2;
	}

};
void test03(){
	
	vector v1,v2,v3;
	for (int i = 0; i < 10; i++){
		v1.push_back(i);
		v2.push_back(i + 1);
	}


	/*
		
		template inline
		_OutIt transform(_InIt1 _First1, _InIt1 _Last1,
		_InIt2 _First2, _OutIt _Dest, _Fn2 _Func)
		{	// transform [_First1, _Last1) and [_First2, ...) with _Func
		_DEBUG_RANGE(_First1, _Last1);
		_DEBUG_POINTER(_Dest);
		_DEBUG_POINTER(_Func);
		if (_First1 != _Last1)
		return (_Transform2(_Unchecked(_First1), _Unchecked(_Last1),
		_First2, _Dest, _Func,
		_Is_checked(_Dest)));
		return (_Dest);
		}


		template inline
		_OutIt _Transform(_InIt1 _First1, _InIt1 _Last1,
		_InIt2 _First2, _OutIt _Dest, _Fn2 _Func)
		{	// transform [_First1, _Last1) and [_First2, ...) with _Func
		for (; _First1 != _Last1; ++_First1, ++_First2, ++_Dest)
		*_Dest = _Func(*_First1, *_First2);
		return (_Dest);
		}
	
	*/

	v3.resize(v1.size());

	for_each(v1.begin(), v1.end(), print2); //    
	cout << endl;
	for_each(v2.begin(), v2.end(), print2); //    
	cout << endl;
	for_each(v3.begin(), v3.end(), print2); //    
	cout << endl;

	
	transform(v1.begin(), v1.end(), v2.begin(), v3.begin(), myplus()); //      

	cout << "------------------------------" << endl;

	for_each(v1.begin(), v1.end(), print2); //    
	cout << endl;
	for_each(v2.begin(), v2.end(), print2); //    
	cout << endl;
	for_each(v3.begin(), v3.end(), print2); //    
	cout << endl;

}
//          : sort

class mycompare04{
public:
	bool operator()(int v1,int v2){
		return v1 > v2; //    
	}
};
void test04(){

	vector v;
	v.push_back(5);
	v.push_back(2);
	v.push_back(7);
	v.push_back(9);


	/*
	
	template inline
	void sort(_RanIt _First, _RanIt _Last, _Pr _Pred)
	{	// order [_First, _Last), using _Pred
	_DEBUG_RANGE(_First, _Last);
	_DEBUG_POINTER(_Pred);
	_Sort(_Unchecked(_First), _Unchecked(_Last), _Last - _First, _Pred);
	}


	*/
	for_each(v.begin(), v.end(), print2); //    
	cout << endl;
	sort(v.begin(), v.end(), mycompare04());
	for_each(v.begin(), v.end(), print2); //    
	cout << endl;
	
}


int main(){


	//test01();
	//test02();
	//test03();
	test04();

	system("pause");
	return EXIT_SUCCESS;
}

定義済み関数オブジェクト
#include
#include
#include
#include
#include
using namespace std;
/*
	
	template T plus//     
	template T minute//     
	template T multiplies//     
	template T divides//     
	template T modulus//     
	template T negate//     
*/
void test01(){
    plus myplus;
    int ret = myplus(10,20);
    cout< myplus2;
    string s1 = "aaa";
    string s2 = "bbb";
    string ret2 = myplus2(s1,s2);
    cout<()(10,20)< v1,v2,v3;
    for(int i=0;i<10;i++){
        v1.push_back(i);
        v2.push_back(i+1);
    }
    v3.resize(v1.size());
    //plus myplus;
    for_each(v3.begin(),v3.end(),print);
    cout<());

    for_each(v3.begin(),v3.end(),print);
    cout<