避免帮助函数进行比较

时间:2012-06-15 23:37:32

标签: c++ stl comparison

假设我有一个带有成员函数的类型:

class Thing {
    std::string m_name;
public:
    std::string & getName() {
        return m_name;
    }
};

并说我有这种类型的集合:

std::vector<Thing> things;

我希望按名称保持秩序。为此,我使用std :: lower_bound来确定放置它的位置:

bool thingLessThan(Thing const& thing, std::string const& name) {
    return thing.getName() < name;
}

void addThing(std::string const& name) {
    vector<Thing>::iterator position = lower_bound(
        things.begin(), things.end(),
        name,
       thingLessThan);
    if (position == things.end() || position->getName() != name) {
        position = things.insert(position, Thing());
        position->getName() = name;
    }
}

有没有办法与thingLessThan函数做同样的事情而不实际创建函数,可能使用std :: mem_fun,std :: less等?

5 个答案:

答案 0 :(得分:4)

除了lambda之外,你可以简单地定义一个符合严格弱排序的operator<,以允许你的对象的容器被STL算法与默认谓词std::less

进行比较
class whatever
{
public:
   bool operator<(const whatever& rhs) const { return x < rhs.x; }

private:
   int x;
};

std::vector<whatever> v;
std::sort(v.begin(), v.end());

答案 1 :(得分:2)

不确定。您可以使用lambda表达式(假设您的编译器支持它):

vector<Thing>::iterator position = lower_bound(
    things.begin(), things.end(),
    name,
   [](Thing const& thing, std::string const& name) { return thing.getName() < name; });

当然,替代选项只是为类定义operator<,如果没有为std::lower_bound指定另一个比较器函数,则默认情况下将使用它。

答案 2 :(得分:0)

取决于您的目的是什么?如果你只是喜欢在一个地方没有声明要使用的语法,那就用lambda表达式创建一个匿名函数。

答案 3 :(得分:0)

如果您不想编写谓词,可以重载operator<()并使用std::less<T>。你也可以使用lambda表达式,它会更好,因为operator<()在逻辑上只与事物连接,可以用明显的方式按顺序放置,如数字或字符串。

答案 4 :(得分:0)

如果使用std :: map,字符串将自动按字母顺序排列。如果要进一步修改排序,请创建自己的密钥比较功能。我认为这是最简单的选择。

要使用std :: list,您可以在addThing()函数内编写自己的比较代码,该函数遍历列表,查看每个字符串并在适当的位置插入新的字符串。