Re: [问题] sort vector 问题

楼主: loveme00835 (发箍)   2020-10-27 04:04:29
※ 引述《ucrxzero (RX-0)》之铭言:
: 第一点 compare function 只有在class里面定义才需要static
: 因为 sort默认是 用<比的所以拿这个举例
: 你只会看到别人在class这样定义
: class{
: bool operator<(Foo const& other) { }
: 或
: static bool operator<(Foo const& other, Foo const& another) { }
: }
以上两者能接受的算子型别是不同的, 这表示它们算是不同的 overloaded
operator<():
struct Foo {
bool operator<(const Foo&); // (1)
};
bool operator<(const Foo&, const Foo&); // (2)
Foo lhs, rhs;
lhs < rhs; // call (1)
std::as_const(lhs) < rhs; // call (2)
如果可以呼叫到不同版本, 你怎么确定在 std::sort() 里行为会合乎预期?
: 而不是
: class{
: bool operator<(Foo const& other, Foo const& another) { }
: }
如果我加上 friend 呢? 这个用法称为 friend definition, 可将函式限定为
只能透过 ADL (Argument Dependent Lookup) 来呼叫, 避免产生额外的隐式转
型成本, 还有其他好处在这里就不提了.
: 因为这样会有三个东西
: a.operator<(b,c) 等于你比三个欸
: static就是没有物件这个主人
: 顺便科普一下
: static member function(用于存取static member)
static member function 是在没有物件存在的情况下, 也可以提供特定服务,
如 Meyers Singleton:
class Foo {
Foo();
public:
static Foo& get() {
static Foo foo;
return foo;
}
int i;
};
Foo::get().i = 0;
请问上面的程式码是在存取 static data member 吗?
: static member variable (用于counter)
: static global function(用于不给别的source拿来include,跟extern相反,Kernel driver常用)
你确定在写 C++ 吗?
: static global variable(用于不给别人拿来用,extern的相反,Kernel driver常用到)
我如果用一个函式回传参考, 这样算不算给别人用?
static int i;
int& get() { return i; }
: 然后static都不能递回
是不是有什么魔法导致加上 static 行为就会改变?
: static都要
: 都放在data segment跟着整个process的生命周期存活
: 这书上写的
: 但是没有初始化则放在bss而且都是零(如果像stl的string就是""空字串)
如果 std::string 没有做 SOO (Small Object Optimzation), 那它拥有的字
元会存放在哪里?
: 第二点 这样写没报错
: #include<vector>
: #include<algorithm>
: using namespace std;
C++ Core Guidelines
SF.6: Use using namespace directives for transition, for foundation
libraries (such as std), or within a local scope (only)
: struct Info{
: float score;
: float rank;
: };
: bool comp(const Info &Info1, const Info &Infor2){
: return Info1.score>Infor2.score;
: }
: void MyFunction(){
: vector<Info>my;
: std::sort(my.begin(), my.end(), comp); //error here
: }
: int main(){
: MyFunction();
: return 0;
: }
虽然不知道你看的是什么书, 但是你可能需要换一本新的
作者: F04E (Fujitsu)   2020-10-27 14:55:00
作者: ucrxzero (RX-0)   2020-10-27 17:36:00
我错了吗
作者: nh60211as   2020-10-27 18:59:00
推这篇
作者: ucrxzero (RX-0)   2020-10-27 19:49:00
推推
作者: CoNsTaR ((const *))   2020-11-01 23:58:00
不是啊,学习本来就是这样 build up 的过程,要是你能够先去了解设计目的,再去了解是怎么达成的,那代表你本来就会了,只是需要认知和记忆而已真正的学习是你突然能够区分你原本无法区分的概念了(可能两个概念都可以理解,但就是无法区分),而这要能够发生一定是因为发现了观察的对象有行为上的不同要是每个人都可以不需要借由写程式和观察程式行为来学程式语言,那我推荐不用学 C/C++ 了,直接学抽象代数、几何学、类型论、证明论、计算理论、型式语言就好了

Links booklink

Contact Us: admin [ a t ] ucptt.com