【发布时间】:2021-08-31 03:50:18
【问题描述】:
我在stackoverflow上问了这个问题STL passing object
我知道我们传递的对象在 tern 中调用比较运算符并比较我们的值并给我们一个结果。都很好。
现在在这段代码中:
class Compare {
public:
bool operator ()(const int &a, const int &b) { return a < b;}
};
void solve(){
set<int, Compare> s;
vector<int> arr = {1,4,6,3,7,2,8,588,5};
for(int e : arr) s.insert(e);
for(auto it = s.rbegin();it!=s.rend();it++) cout << *it << ' '; cout << endl;
}
如果我执行 Compare() 会出错,这是我认为必须完成的(传递对象)。为什么这样?我们如何通过比较?
同样在这段代码中,我无法传递如下函数:
bool comp(const int &a, const int &b) { return a < b; }
void solve(){
set<int, comp> s;
vector<int> arr = {1,4,6,3,7,2,8,588,5};
for(int e : arr) s.insert(e);
for(auto it = s.rbegin();it!=s.rend();it++) cout << *it << ' '; cout << endl;
}
这是我所期望的。不传递函数。
现在在这段代码中:
bool comp(const int &a, const int &b) { return a < b; }
void solve(){
vector<int> arr = {1,4,6,3,7,2,8,588,5};
nth_element(arr.begin(), arr.begin()+3, arr.end(), comp);
for(int e : arr) cout << e << " "; cout << endl;
}
我能够传递一个函数并且没有错误。我的意思是发生了什么事?从我的角度来看,我们应该只传递对象,它们会调用它们的 () 重载运算符并比较值,但有时我们传递函数,有时传递对象会出错,有时我们只传递类名。 c++到底发生了什么
【问题讨论】:
-
能否提供每种情况的错误信息?
-
很多错误,比如函数返回函数。没有已知的参数 2 从“比较”到“布尔”的转换。等等,但基本上说我无法比较我的做法
-
STL 是一个库,它是 c++ 标准库的前身。您的标题表明您正在谈论 STL 和标准库,但我认为您的意思是标准库
标签: c++ templates stl set function-object