【问题标题】:Erase–remove idiom c++ (without friend function)擦除——删除成语 c++(无友元函数)
【发布时间】:2025-12-21 12:05:16
【问题描述】:

我有两个班级:

#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
#include <algorithm>
#include <cmath>
#include <list>
using namespace std;

enum class Programm{Koch, Normal, Bunt, Fein};

class KleidSt {
private:
    string bezeichnung;
    int gewicht;
    Programm Pflegehinweis;

public:
    KleidSt(string bezeichnung, int gewicht);
    KleidSt(string bezeichnung, int gewicht, Programm Pflegehinweis);
    int get_gewicht() const;
    bool vertraeglich(Programm)const;
    int get_Pflegehinweis() const;
    friend ostream& operator<<(ostream& os, const KleidSt& kleid);
};


class WaschM{
private:
    int ladungsgewicht;
    vector<KleidSt> wasch;
public:
    WaschM(int ladungsgewicht);
    void zuladen(const vector<KleidSt>& z);
    void waschen(Programm);
    friend ostream& operator<<(ostream& os, const WaschM& kleid);
    int programme() const;
    vector<KleidSt> aussortieren(Programm pr);
};

我想创建函数vector&lt;KleidSt&gt; aussortieren(Programm),它将删除wasch向量中的所有元素,如果这些元素具有更高的Pflegehinweis属性(通过使用static_cast&lt;int&gt;(elem)函数)然后由aussortieren函数定义并将返回一个已删除元素的向量。

我的第一次尝试是使用 Erase-remove idiom:

vector<KleidSt> WaschM::aussortieren(Programm pr){
    wasch.erase(remove_if(begin(wasch), end(wasch), vertraeglich(pr)), end(wasch));
    return wasch;
}

这里vertraeglich(pr) 完成了我上面描述的工作。 但它显然返回错误,因为vertraeglich 函数被定义在类WaschM 的范围之外。问题是:我怎样才能使用 Erase–remove idiom(或其他一些变体),这样代码才能工作?

【问题讨论】:

    标签: c++


    【解决方案1】:

    看起来像是 lambda 函数的工作

    vector<KleidSt> WaschM::aussortieren(Programm pr){
        wasch.erase(
            remove_if(
                begin(wasch),
                end(wasch), 
                [&](const KleidSt& k){ return k.vertraeglich(pr); }), 
            end(wasch));
        return wasch;
    }
    

    未经测试的代码。

    【讨论】:

    • @john 再看一遍。该页面上的任何地方都没有提到^ 字符。 lambda 捕获可以使用=&amp;,但不能使用^。在这种情况下,使用&amp;,所以pr 是通过引用而不是值来捕获的
    • 我相信你的意思是&amp;(或=)。 ^ 是按位异或。
    • 天哪,我完全失明了,现在已经修好了,谢谢大家。
    【解决方案2】:

    您可以使用 lambda 函数。

    vector<KleidSt> WaschM::aussortieren(Programm pr){
        wasch.erase(remove_if(begin(wasch),
                              end(wasch),
                              [pr](KleidSt const& item) {return item.vertraeglich(pr);},
                              end(wasch));
        return wasch;
    }
    

    【讨论】:

    • 为什么在捕获列表中使用= 而不是&amp;=pr 合法吗?
    • @RemyLebeau,这是一个疏忽。