如何声明运算符重载<以在需要时在类变量之间动态切换?

How to declare an operator overloading < to dynamically shift between class variables whenever needed?

本文关键字:类变量 之间 动态 声明 何声明 运算符 lt 重载      更新时间:2023-10-16

我搜索了很多网站,浏览了一些关于这方面的书籍,但未能找到关于如何动态(在程序执行中)比较类中不同数据类型的良好来源,less-<大于>运算符。

假设我们有以下代码片段:

#include <iostream>
using namespace std;
class OP
{
private:
    string alias;
    float locatorX;
    int coordinate;
public:
    bool operator<(const OP& rhs)
    {
        return (this->locatorX < rhs.locatorX);
        //Here! How do I do to make the compiler understand that
        //I compare i.e alias or coordinate whenever I need? 
        //I tried with:
            return (this->coordinate < rhs.coordinate, this->alias < rhs.alias);
        //But it didn't really do the trick when implemented 
        //a sort algorithm inside main as it failed to sort a string array.
    }
};

编辑:

由于这里的大多数好心人都不理解这个问题,所以这里有一个你希望得到的场景。

假设我们想要创建一个接受字符串、int和float类型的映射。我们在类OP中创建一个函数,该函数接受所有给定的数据类型,并将它们保存在创建的类数组中。因此,我们在类数组中有15条记录。

我该如何做才能用小于运算符的升序动态冒泡排序(在<运算符的帮助下)、别名(字符串)locatorX(float)和坐标(int)(无论我选择哪个)?

例如,我需要在运行时对坐标或别名(如果需要的话)进行排序。我该怎么做?

示例输出:

(数组中的第一个位置):

"阿尔伯特街5号";

坐标:1691

定位器X:19.52165

(数组中的第二个位置):

"Main street 7th alley";

坐标:59

定位器X:8175。12

(阵列中的第三个位置):

"Elm/Kentucky";

坐标:9517

定位器X:271.41

通常,您会为想要实现的每个比较创建一个单独的比较器。你不能把它们分解成一个operator<,尽管从技术上讲,你可以根据一些新的第三个参数的值产生一个不同的函数来执行不同的比较,但它与目前几乎所有知道如何使用比较器的函数都不兼容。

在这种情况下,操作员重载是错误的作业工具。

似乎有几种方法可以做到这一点:

在呼叫站点的比较功能之间切换

您必须为不同的字段定义单独的比较函数。

std::vector<Object> v;
enum class OrderBy
{
    alias,
    coordinate
}
OrderBy order_by = get_orderBy_from_user();
switch (order_by)
{
case OrderBy::alias:
    std::sort(v.begin(), v.end(), compare_by_alias());
    break;
case OrderBy::coordinate:
    std::sort(v.begin(), v.end(), compare_by_coordinate());
    break;
}

在比较函数中进行选择

您必须以某种方式将排序字段的选择传达到函数中。选项包括:全局或单例"配置"对象,比较类中的成员变量。我会避免任何全局,因此第二种选择:

struct compare_by_field
{
    OrderBy order_by_;
    compare_by_field(OrderBy order_by) : order_by_(order_by)
    {}
    bool operator()(const Object & lhs, const Object & rhs) const
    {
        switch (order_by_)
        {
        case OrderBy::alias:
            return lhs.alias < rhs.alias;
        case OrderBy::coordinate:
            return lhs.coordinate < rhs.coordinate;
        }
    }
}
std::sort(v.begin(), v.end(), compare_by_field(get_order_by_from_user()));