在 Visual C++中使用 list::remove、list::remove_if STL 函数

本文提供了有关如何在 Visual C++ 中使用 list::removeSTL list::remove_if 函数的信息。

原始产品版本: Visual C++
原始 KB 数: 168047

总结

下面的示例代码演示如何在 Visual C++中使用 list::removeSTL list::remove_if 函数。

注意

Visual C++ 版本 4.2 与更高版本修订中标准C++库组件的实现存在一些差异。 以下代码的相关部分根据值 _MSC_VER有条件地编译。

必需的标头

<list>
<string>
<iostream>

原型

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

注意

原型中的类/参数名称可能与头文件中的版本不匹配。 一些已修改以提高可读性。

说明

此示例演示如何使用 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的详细信息,请访问以下网站: