我正在宣告我的 std::map 并在下面使用它:
map<int, int, function<bool (int, int)>> m;
m.insert(make_pair(12,3));
m.insert(make_pair(3,4));
for(auto & p : m){
cout << p.first << "," << p.second << endl;
}
g 編譯,沒有錯誤。模板引數只需要型別,不需要函式體,通過編譯。我想知道這個空的比較器會如何表現。運行時:
terminate called after throwing an instance of 'std::bad_function_call'
what(): bad_function_call
我只在呼叫純虛函式時看到這個錯誤。但是我的代碼使用的是 stl 模板,沒有多型性。
那么這是一個 c 設計問題,編譯不檢查函式是否只有宣告但沒有函式體可以運行?另外,c 標準將如何處理這個問題?
感謝您的解釋。
uj5u.com熱心網友回復:
該問題與模板引數無關,而是您在構建地圖時沒有為其提供實際值。
請注意,在地圖建構式的檔案中,有一個const Compare&引數。正是通過這個引數,你必須為你的比較器提供一個值,在這種情況下是一個 lambda。
explicit map( const Compare& comp,
const Allocator& alloc = Allocator() );
例如:
#include <functional>
#include <iostream>
#include <map>
using namespace std;
int main()
{
auto comp = [](int a, int b) { return a > b; };
map<int, int, function<bool (int, int)>> m(comp);
m.insert(make_pair(12,3));
m.insert(make_pair(3,4));
for(auto & p : m){
cout << p.first << "," << p.second << endl;
}
}
輸出:
12,3
3,4
uj5u.com熱心網友回復:
map<int, int, function<bool (int, int)>> m;
您宣告std::map使用自己的比較器,其簽名為bool(int, int),但未提供可呼叫函子。
您應該宣告一個真正的可呼叫物件并將其傳遞給建構式,以便您的地圖可以在需要時呼叫它。
auto order_by_asc = [](int n1, int n2)->bool {return (n1 < n2); };
std::map<int, int, std::function<bool(int, int)>> m(order_by_asc);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/492683.html
上一篇:如何反轉字典中鍵的值?
