<分区>
我一直在搜索很多网站并浏览了一些关于这方面的书籍,但未能找到关于如何动态地(在程序执行期间)比较类中不同数据类型的良好来源 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.
}
};
编辑:
由于这里的大多数好心人都不理解这个问题,这里有一个你希望得到的场景。
假设我们要创建一个接受字符串、整数和浮点类型的 map 。我们在 OP 类中创建一个函数,它接受所有给定的数据类型并将它们保存在创建的类数组中。所以我们的类数组中有 15 条记录。
我该怎么做才能使用小于运算符按升序动态冒泡排序(借助 < 运算符)、别名(字符串)locatorX(float) 和坐标(int)(无论我选择哪个)?
例如,我有点需要在运行时对坐标或别名(如果需要)进行排序。我该怎么做?
示例输出:
(数组中的第一个位置):
“阿尔伯特街 5 号”
坐标:1691
定位器X:19.52165
(数组中的第二个位置):
"大街七巷"
坐标:59
定位器X:8175.12
(数组中的第三个位置):
“榆树/肯塔基”
坐标:9517
定位器X:271.41