c++ 自定义比较函数,运行时发生segmentation fault
生活随笔
收集整理的這篇文章主要介紹了
c++ 自定义比较函数,运行时发生segmentation fault
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?c++ map自定義比較函數,發生運行時越界。
#include <string> #include <iostream> #include <list> #include <vector> #include <set> #include <map> using namespace std; bool compareStr(const string &,const string &); int main() { vector<string> vstr{"abc","def","abcd","defgg","abcdef"}; set<string,decltype(compareStr)*> s1(compareStr);//s2類型定義提供比較操作函數類型指針如下,容器定義時候需要提供比較操作(一個用來比較的函數名字) set<string,decltype(compareStr)*> s2(vstr.begin(),vstr.end());s1 = {"abc","def","abcd","abcdef"}; for(auto i : s1)cout << i << " "; cout << endl; for (auto i : s2)cout << i << " "; cout << endl;return 0;} bool compareStr(const string & s1,const string & s2) {return (s1.size() > s2.size()); } r@r:~/coml/c++/11/11.2/11.2.2$ ./123 Segmentation fault (core dumped)為什么?
自定義比較操作要求定義類型時緊跟元素類型提供比較函數指針的類型,容器類型定義時候需要提供比較操作,如代碼中的s2,s2容器定義的時候缺少了比較的操作(缺少函數名字),所以代碼更改如下:
#include <string> #include <iostream> #include <list> #include <vector> #include <set> #include <map> using namespace std;bool compareStr(const string &,const string &); void print_set(const set<string,decltype(compareStr)*> &);int main() { vector<string> vstr{"abc","def","abcd","defgg","abcdef"};//注意:下面兩個set都是用了自定義的比較操作,每次定義類型的時候,尖括號中必須在元素類型之后 //緊跟比較操作的函數類型的指針,一般用decltype來實現,哪怕是定義打印函數時候,要求也是一樣 //也就是從此刻開始,所有的關于s1,s2的類型的操作的函數,都必須遵守這個規則:類型部分含有兩部分 //元素類型 + 比較函數的指針類型 set<string,decltype(compareStr)*> s1(compareStr); set<string,decltype(compareStr)*> s2(compareStr); s2 = {"abc","def","ghis","asdfasdf"}; s1 = {"abc","def","asdf","abcdef"}; cout << endl; for (auto i : s2)cout << i << " "; cout << endl; print_set(s1);return 0;} bool compareStr(const string & s1,const string & s2) {return (s1.size() > s2.size()); }//下面定義一個s1,s2的打印函數,切記類型里面緊跟元素類型有自定義比較函數的類型的指針,切不可丟棄 //不然則發生錯誤 void print_set(const set<string,decltype(compareStr)*> & s) { for(auto i : s)cout << i << " "; cout << endl;}本次運行就沒有問題了,運行結果如下:
asdfasdf ghis abc abcdef asdf abc如果打印函數的形式參數類型定義為? ?const set<string> &s 會發生什么情況呢,會造成如下錯誤:
2.cc:22:11: error: invalid initialization of reference of type ‘const std::set<std::__cxx11::basic_string<char> >&’ from expression of type ‘std::set<std::__cxx11::basic_string<char>, bool (*)(const std::__cxx11::basic_string<char>&, const std::__cxx11::basic_string<char>&)>’22 | print_set(s1);| ^~ 2.cc:10:16: note: in passing argument 1 of ‘void print_set(const std::set<std::__cxx11::basic_string<char> >&)’10 | void print_set(const set<string> &);錯誤的大題意思是用set<string> &對象,初始化set<string,decltype(compareStr)*> & 類型對象是不合法的,也就是形參中元素定義類型時候少了緊跟在元素類型之后的比較類型函數的指針了??
總結
以上是生活随笔為你收集整理的c++ 自定义比较函数,运行时发生segmentation fault的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python3 文件模式
- 下一篇: c++ 如何不用decltype获取一个