C++STL常用アルゴリズム


STLアルゴリズムが多すぎて、ここでよく使うものをいくつか整理します.
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;


void printC(vector &v)
{
	for(vector::iterator it = v.begin(); it
class ShowE
{
public:
	void operator()(T t)
	{
		cout << t << " ";
	}
};


//     
// for_each
void func6_1()
{
	vector  v;
	v.push_back(1);
	v.push_back(3);
	v.push_back(5);
	v.push_back(7);
	v.push_back(9);
	printC(v);

	for_each(v.begin(), v.end(), ShowE());
	cout << endl;
}

int increase(int a)
{
	return a+100;
}


//     
// transfrom
void func6_2()
{
	vector v;
	v.push_back(1);
	v.push_back(3);
	v.push_back(5);
	v.push_back(7);
	v.push_back(9);

	// transform           , for_each                
	transform(v.begin(), v.end(), v.begin(), increase);
	printC(v);

	//   
	transform(v.begin(), v.end() , v.begin(), negate());
	printC(v);

	//        
	list ls;
	ls.resize(v.size());

	//transform(v.begin(), v.end(), ls.begin(), increase);
	transform(v.begin(), v.end() , ls.begin(), bind2nd(multiplies(), 100));
	for_each(ls.begin(), ls.end(), ShowE());
	cout << endl;
}

//     
// adjacent_find
void func6_3()
{
	vector v;
	v.push_back(1);
	v.push_back(3);
	v.push_back(5);
	v.push_back(5);
	v.push_back(7);
	v.push_back(7);
	v.push_back(9);

	//               ,               
	//       5
	vector :: iterator it = adjacent_find(v.begin(), v.end());
	if(it != v.end())
		cout << *it << endl;
}

//binary_search
void func6_4()
{
	vector v;
	v.push_back(1);
	v.push_back(3);
	v.push_back(5);
	v.push_back(5);
	v.push_back(7);
	v.push_back(9);

	// binary_search      ,   :            ,     
	bool b = binary_search(v.begin(), v.end(), 7);
	if(b)
		cout << "  " << endl;
	else 
		cout << "    " << endl;
}


//     
// merge     
// random_shuffle     
// reverse     
void func6_5()
{
	vector v1;
	v1.push_back(1);
	v1.push_back(3);
	v1.push_back(5);

	vector v2;
	v2.push_back(2);
	v2.push_back(4);
	v2.push_back(6);

	vector v3;
	v3.resize(v1.size() + v2.size());

	merge(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());
	printC(v3);

	srand((unsigned int)time(NULL));

	//     ,         
	random_shuffle(v3.begin(), v3.end());
	printC(v3);

	//     
	reverse(v3.begin(), v3.end());
	printC(v3);

	//     
	vector v4(v3.size()); //     0
	copy(v3.begin(), v3.begin()+5, v4.begin()); 
	v4[2] = 0;
	v4[3] = 0;
	printC(v4);

	//     
	//       10
	replace(v4.begin(), v4.end(), 0 ,10);
	printC(v4);

	replace_if(v4.begin(), v4.end(), bind2nd(greater(), 2), 7);
	printC(v4);

	//               
	vector v5;
	swap(v3,v5);

	cout << "v3:" << endl;
	printC(v3);

	printC(v4);
	//     
	int sum = accumulate(v4.begin(), v4.end(), 100);
	cout << sum << endl;

	//     
	//              
	fill(v4.begin(), v4.begin()+2, 100);
	printC(v4);
}






int main()
{
	//func6_1();
	//func6_2();
	//func6_3();
	//func6_4();
	func6_5();
	system("pause");
	return 0;
}