Поделиться через


Использование функций list::remove, list::remove_if STL в Visual C++

В этой статье содержатся сведения об использовании list::removelist::remove_if функций STL в Visual C++.

Исходная версия продукта: Visual C++
Исходный номер базы знаний: 168047

Итоги

В приведенном ниже примере кода показано, как использовать list::removelist::remove_if функции STL в Visual C++.

Примечание.

Существуют некоторые различия в реализации компонентов библиотеки C++ уровня "Стандартный" в Visual C++ версии 4.2 и более поздних редакций. Соответствующие разделы кода ниже компилируются условно на основе значения _MSC_VER.

Обязательный заголовок

<list>
<string>
<iostream>

Прототип

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

Примечание.

Имена классов и параметров в прототипе могут не совпадать с версией в файле заголовка. Некоторые из них были изменены, чтобы улучшить удобочитаемость.

Description

В этом примере показано, как использовать list::remove и list::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::remove list::remove_ifсведения см. на следующих веб-сайтах: