質問
Q:エラーを解消する方法を知りたい
実現したいこと
比較関数のbool comp1(pi a, pi b) {}
をtemplate化してsort()で使いたい
発生している問題・エラーメッセージ
sort +4 個のオーバーロード オーバーロードされた関数 "sort" のインスタンスが引数リストと一致しませんC/C++(304) q2.cpp(28, 3): 引数の型: (__gnu_cxx::__normal_iterator<pi *, std::vector<pi, std::allocator<pi>>>, __gnu_cxx::__normal_iterator<pi *, std::vector<pi, std::allocator<pi>>>, <unknown-type>)
該当のソースコード
C++17
C++
1#include <bits/stdc++.h> 2using namespace std; 3 4using pi = pair<int, int>; 5 6// template無し 7bool comp1(pi a, pi b) { return a.first != b.first ? a.first < b.first : a.second < b.second; } 8 9// template化したいがsort()関数で使うとエラーになる 10template<class T, class U> 11bool comp2(pair<T, U> a, pair<T, U> b) { 12 return a.first != b.first ? a.first < b.first : a.second < b.second; 13} 14 15void output(vector<pi> v) { 16 for (auto e : v) cout << e.first << " " << e.second << "/n"; 17} 18 19void solve() { 20 // input 21 vector<pi> v {{1, 3}, {2, 2}, {3, 1}, {9, 7}, {8, 8}, {7, 9}}; 22 23 // sort1 24 sort(v.begin(), v.end(), comp1); 25 output(v); 26 27 // sort2 28 // ↓※このsort()でエラーとなるが原因が分からない 29 sort(v.begin(), v.end(), comp2); 30 output(v); 31} 32 33int main() { (solve()); } 34
試したこと
・comp1のように比較関数の引数の型を明示するとエラーは出なかった
・comp2を使ったsort2をコメントアウトしてコンパイルすると通るのでtemplate化したcomp2は間違っていない気がする
・sort2のsort()の引数の指定の仕方がtemplate化したことによって違っているとエラーから推測出来るのですが
どのように指定したらエラーが解消するのか分からない
回答4件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
2023/03/09 15:32
2023/03/09 15:47