[英]c++ std::map compare function leads to runtime "bad_function_call"
我正在聲明我的 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++ 標准將如何處理這個問題?
感謝您的解釋。
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);
該問題與模板參數無關,而是您在構建地圖時沒有為其提供實際值。
請注意,在地圖構造函數的文檔中,有一個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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.