Mae*_*tro 1 c++ comparison pointers
我发现我应该std::less用来比较我的对象,以便能够比较 Unrelated 指针(来自不同的序列),因为<如果在那些不相关的指针上使用,只使用关系运算符会产生 UB。
所以为了练习,我已经实现了我的compare功能:
#include <iostream>
using namespace std;
#include <functional>
template <class T>
constexpr int compare(T const& x, T const& y)
{
if(std::less<T>()(x, y))
return -1;
if(std::less<T>()(y, x))
return 1;
return 0;
}
int main()
{
std::cout << compare(std::string("Hello"), std::string("hello")) << std::endl;
std::cout << compare(std::string("hello"), std::string("Hello")) << std::endl;
std::cout << compare(std::string("hello"), std::string("hello")) << std::endl;
std::cout << compare(-7, 1) << std::endl;
int* p1{new int(10)};
int* p2{new int{4}};
std::cout << compare(p2, p1) << std::endl;
std::cout << "\ndone!\n";
}
Run Code Online (Sandbox Code Playgroud)
输出:
-1
1
0
-1
1
Run Code Online (Sandbox Code Playgroud)
为什么我不应该<在这种情况下直接使用?
怎么可能std::less比 更安全<?我是说内功。谢谢!
怎么可能
std::less比 更安全<?
因为标准是这么说的。
我是说内功。
在所有 x64 和大多数现代架构上,std::less::operator()都只是对内置运算符的简单包装,<或者将指针转换为uinptr_t然后进行比较。
C++ 旨在适用于各种硬件架构,因此大概有一些架构(历史?,古老?,奇怪?)其中并非所有数据地址都(容易)比较。在那些架构上,操作员<将无法工作,而std::less需要实施工作方式。
作为旁注,您没有在示例中比较指针
我应该使用
std::less而不是<
对于指向(可能)不同对象或不同数组中的指针,是的,否则如果<在这种情况下使用,则会出现未定义行为。对于其他任何事情都没有。std::less当您需要为某些其他函数(例如std::sort)提供比较器函数时,这非常有用。
例如:
int a{}, b{}
int* p_a = &a;
int* p_aa = &a;
int* p_b = &b;
p_a < p_b; // technically Undefined Behavior, use std::less instead:
std::less<>{}(p_a, p_b);
p_a < p_a; // ok
p_a < p_aa; // ok
Run Code Online (Sandbox Code Playgroud)
int arr1[10]{}
int* p1_1 = &arr1[0];
int* p1_2 = &arr1[5];
int arr2[10]{};
int* p2_1 = &arr2[0];
int* p2_2 = &arr2[5];
p1_1 < p2_1; // technically Undefined Behavior, use std::less instead:
std::less<>{}(p_1_1, p_2_1);
p1_1 < p1_2; // ok
p2_1 < p2_2; // ok
Run Code Online (Sandbox Code Playgroud)
char str[] = "hello";
char* str_end = str + strlen(str);
for (char* p = str; p < str_end; ++p) // ok
// ...
Run Code Online (Sandbox Code Playgroud)
对于任何其他用途 <
int a{}, b{};
a < b; // ok
std::string s1{}, s2{};
s1 < s2; // ok
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
92 次 |
| 最近记录: |