変更アルゴリズム
メニューを表示するにはスワイプしてください
C++標準ライブラリにおける修正アルゴリズムは、コンテナの内容を効率的かつ表現力豊かに変更するための重要なツール。最も一般的に使用される修正アルゴリズムには、std::copy、std::replace、および**std::remove**が含まれる。
これらのアルゴリズムはイテレータ範囲で動作し、柔軟性が高くコンテナに依存しない設計となっている。
main.cpp
1234567891011121314151617#include <iostream> #include <list> #include <algorithm> int main() { std::list<int> numbers = {1, 2, 3, 2, 4, 2, 5}; // Replace all occurrences of 2 with 99 std::replace(numbers.begin(), numbers.end(), 2, 99); // Remove all elements greater than 90 using remove_if numbers.remove_if([](int n){ return n > 90; }); for (int n : numbers) std::cout << n << " "; }
std::vector や std::deque などのコンテナを使用する場合、std::remove のようなアルゴリズムは実際には要素を削除しません。代わりに、残りの要素を前方に移動し、新しい論理的な末尾へのイテレータを返しますが、コンテナのサイズは変わりません。要素を完全に削除するには、そのイテレータを使ってコンテナの erase 関数を呼び出します。これは erase-remove イディオム として知られる一般的なパターンです。
main.cpp
1234567891011121314#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> numbers = {1, 2, 3, 2, 4, 2, 5}; // Remove all occurrences of 2 auto new_end = std::remove(numbers.begin(), numbers.end(), 2); numbers.erase(new_end, numbers.end()); for (int n : numbers) std::cout << n << " "; }
注意
コンテナの末尾に無効なデータが残らないように、必ず std::remove と erase を組み合わせて使用。
すべて明確でしたか?
フィードバックありがとうございます!
セクション 1. 章 9
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 1. 章 9