C++ <list> remove関数

C++ 容器类 <list>C++ コンテナクラス <list>


removelist内で使用され、指定された値と等しいすべての要素を削除する関数であり、リンクリスト特有の効率的な操作です。

removeコンテナクラスのメンバ関数であり、リンクリスト内の指定された値と等しいすべての要素を削除するために使用されます。

list内では、removeの時間計算量はO(n)です。

単語の意味: remove「取り除く」を意味し、つまり指定された値と等しいすべての要素を削除します。


基本構文とパラメータ

構文形式

void remove(const T& value);

パラメータの説明

  • パラメータ: value- 削除する要素の値

関数の説明

  • 戻り値: void(戻り値なし)。
  • 効果: リンクリスト内の value と等しいすべての要素を削除します。

例

例1:指定された値と等しいすべての要素を削除

例

#include <iostream>
#include <list>

int main() {
    std::list<int> numbers = {1, 2, 3, 2, 4, 2, 5};

    std::cout << 元:;
    for(int n : numbers) std::cout << n << " ";
    std::cout << std::endl;

    // 2 と等しいすべての要素を削除
    numbers.remove(2);

    std::cout << remove(2) 後:;
    for(int n : numbers) std::cout << n << " ";
    std::cout << std::endl;

    return 0;
}

実行結果の予想:

原始: 1 2 3 2 4 2 5
remove(2) 后: 1 3 4 5

例2:文字列を削除

例

#include <iostream>
#include <list>
#include <string>

int main() {
    std::list<std::string> words = {"apple", "banana", "apple", "cherry", "apple"};

    std::cout << 元:;
    for(const auto& w : words) std::cout << w << " ";
    std::cout << std::endl;

    words.remove("apple");

    std::cout << "remove(\"apple\") 後:;
    for(const auto& w : words) std::cout << w << " ";
    std::cout << std::endl;

    return 0;
}

実行結果の予想:

原始: apple banana apple cherry apple
remove("apple") 后: banana cherry

C++ 容器类 <list>C++ コンテナクラス <list>

その他の拡張