1つ、並べ替え
機能の説明:
- コンテナ内の要素を並べ替える
関数プロトタイプ:
-
sort(iterator beg, iterator end, _Pred);
//値で要素を検索し、指定された位置に戻るイテレータを検索し、最後に戻るイテレータを検索します
// begがイテレータを開始します
//終了はイテレータを終了します
// _ Pred述語
例:
#include <algorithm>
#include <vector>
void myPrint(int val)
{
cout << val << " ";
}
void test01() {
vector<int> v;
v.push_back(10);
v.push_back(30);
v.push_back(50);
v.push_back(20);
v.push_back(40);
//sort默认从小到大排序
sort(v.begin(), v.end());
for_each(v.begin(), v.end(), myPrint);
cout << endl;
//从大到小排序
sort(v.begin(), v.end(), greater<int>());
for_each(v.begin(), v.end(), myPrint);
cout << endl;
}
int main() {
test01();
system("pause");
return 0;
}
**概要:** sortは開発で最も一般的に使用されるアルゴリズムの1つであり、習熟度が必要です
二、random_shuffle
機能の説明:
- 指定された範囲内の要素をシャッフルし、順序をランダムに調整します
関数プロトタイプ:
-
random_shuffle(iterator beg, iterator end);
//指定された範囲内の要素の順序をランダムに調整します
// begがイテレータを開始します
//終了はイテレータを終了します
例:
#include <algorithm>
#include <vector>
#include <ctime>
class myPrint
{
public:
void operator()(int val)
{
cout << val << " ";
}
};
void test01()
{
srand((unsigned int)time(NULL));
vector<int> v;
for(int i = 0 ; i < 10;i++)
{
v.push_back(i);
}
for_each(v.begin(), v.end(), myPrint());
cout << endl;
//打乱顺序
random_shuffle(v.begin(), v.end());
for_each(v.begin(), v.end(), myPrint());
cout << endl;
}
int main() {
test01();
system("pause");
return 0;
}
概要:random_shuffleシャッフルアルゴリズムの方が実用的です。使用するときは、乱数シードを追加することを忘れないでください。
3、マージ
機能の説明:
- 2つのコンテナ要素がマージされ、別のコンテナに格納されます
関数プロトタイプ:
-
merge(iterator beg1, iterator end1, iterator beg2, iterator end2, iterator dest);
//コンテナ要素はマージされ、別のコンテナに保存されます
//注:2つのコンテナは順番に並んでいる必要があります
// beg1コンテナ1開始イテレータ
// end1コンテナ1終了イテレータ
// beg2コンテナ2開始イテレータ
// end2コンテナ2終了イテレータ
// destターゲットコンテナ開始イテレータ
例:
#include <algorithm>
#include <vector>
class myPrint
{
public:
void operator()(int val)
{
cout << val << " ";
}
};
void test01()
{
vector<int> v1;
vector<int> v2;
for (int i = 0; i < 10 ; i++)
{
v1.push_back(i);
v2.push_back(i + 1);
}
vector<int> vtarget;
//目标容器需要提前开辟空间
vtarget.resize(v1.size() + v2.size());
//合并 需要两个有序序列
merge(v1.begin(), v1.end(), v2.begin(), v2.end(), vtarget.begin());
for_each(vtarget.begin(), vtarget.end(), myPrint());
cout << endl;
}
int main() {
test01();
system("pause");
return 0;
}
概要:マージによってマージされる2つのコンテナーは、順序どおりに並べられている必要があり、スペースを開く必要があります。
四、逆
機能の説明:
- コンテナ内の要素を逆にします
関数プロトタイプ:
-
reverse(iterator beg, iterator end);
//指定された範囲の要素を反転します
// begがイテレータを開始します
//終了はイテレータを終了します
例:
#include <algorithm>
#include <vector>
class myPrint
{
public:
void operator()(int val)
{
cout << val << " ";
}
};
void test01()
{
vector<int> v;
v.push_back(10);
v.push_back(30);
v.push_back(50);
v.push_back(20);
v.push_back(40);
cout << "反转前: " << endl;
for_each(v.begin(), v.end(), myPrint());
cout << endl;
cout << "反转后: " << endl;
reverse(v.begin(), v.end());
for_each(v.begin(), v.end(), myPrint());
cout << endl;
}
int main() {
test01();
system("pause");
return 0;
}