次の方法で共有


Visual C++ で list::remove、list::remove_if STL 関数を使用する

この記事では、Visual C++ で STL 関数list::remove_iflist::removeを使用する方法について説明します。

元の製品バージョン: Visual C++
元の KB 番号: 168047

まとめ

次のサンプル コードは、Visual C++ で STL 関数list::remove_iflist::removeを使用する方法を示しています。

Note

Visual C++ バージョン 4.2 での標準 C++ ライブラリ コンポーネントの実装と以降のリビジョンには、いくつかの違いがあります。 以下のコードの関連セクションは、 _MSC_VERの値に基づいて条件付きでコンパイルされます。

必須ヘッダー

<list>
<string>
<iostream>

プロトタイプ

void remove(const T& x);
void remove_if(binder2nd< not_equal_to<T> > pr);

Note

プロトタイプのクラス名またはパラメーター名が、ヘッダー ファイルのバージョンと一致しない可能性があります。 読みやすさを向上させるために変更されたものもあります。

説明

この例では、 list::removelist::remove_ifの使用方法を示します。 また、独自の関数で list::remove_if を使用する方法も示します。

サンプル コード

//////////////////////////////////////////////////////////////////////
// Compile options needed: -GX
// remove.cpp : This example shows how to use list::remove and
// list::remove_if. It also shows how to use
// list::remove_if with your own function.
// Functions:
// list::remove
// list::remove_if
// Copyright (c) 1996 Microsoft Corporation. All rights reserved.
//////////////////////////////////////////////////////////////////////

#pragma warning(disable:4786) // disable spurious C4786 warnings

#include <list>
#include <string>
#include <iostream>
using namespace std;

#if _MSC_VER > 1020 // if later than revision 4.2
    using namespace std; // std c++ libs are implemented in std
#endif

typedef list<string, allocator<string> > LISTSTR;

// Used to customize list::remove_if()
class is_four_chars
    : public not_equal_to<string>
{
    bool operator()(const string& rhs, const string&) const
    { return rhs.size() == 4; }
};

void main()
{
    LISTSTR test;
    LISTSTR::iterator i;

    test.push_back("good");
    test.push_back("bad");
    test.push_back("ugly");

    // good bad ugly
    for (i = test.begin(); i != test.end(); ++i)
        cout << *i << " ";
    cout << endl;

    test.remove("bad");

    // good ugly
    for (i = test.begin(); i != test.end(); ++i)
        cout << *i << " ";
    cout << endl;

    // remove any not equal to "good"
    test.remove_if(binder2nd<not_equal_to<string> >
        (not_equal_to<string>(), "good"));

    // good
    for (i = test.begin(); i != test.end(); ++i)
        cout << *i << " ";
    cout << endl;

    // Remove any strings that are four characters long
    test.remove_if(binder2nd<not_equal_to<string> >
        (is_four_chars(), "useless parameter"));

    if (test.empty())
        cout << "Empty list\n";
}

プログラムの出力

good bad ugly
good ugly
good
Empty list

関連情報

list::removelist::remove_ifの詳細については、次の Web サイトを参照してください。