簡體   English   中英

為什么不能比較 c++ 中的 int 和 size_t

[英]Why can't compare int and size_t in c++

問題是,如果我在 for 循環中比較 int 和 size_t 它工作正常。

vector<int> v;
for (int i = 0; i < v.size(); ++i)

但是,如果我這樣做,它不起作用:

vector<int> v;
int max_num = max(3, v.size());
Line 13: Char 24: error: no matching function for call to 'max'

/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/algorithmfwd.h:370:5: note: candidate template ignored: deduced conflicting types for parameter '_Tp' ('int' vs. 'unsigned long')
    max(const _Tp&, const _Tp&);
    ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_algo.h:3462:5: note: candidate template ignored: could not match 'initializer_list<type-parameter-0-0>' against 'int'
    max(initializer_list<_Tp> __l, _Compare __comp)
    ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_algo.h:3456:5: note: candidate function template not viable: requires single argument '__l', but 2 arguments were provided
    max(initializer_list<_Tp> __l)
    ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/algorithmfwd.h:375:5: note: candidate function template not viable: requires 3 arguments, but 2 were provided
    max(const _Tp&, const _Tp&, _Compare);
    ^
1 error generated.

在最壞的情況下,我必須將 size_t 轉換為 int 才能使其工作。

為什么在 for 循環中我不需要這樣做? 只是好奇。

在 C++ 中,當二元運算符的類型不同時,有各種(復雜的)規則來控制二元運算符使用的實際類型:

i < v.size()

其中之一是int 另一個是size_t 沒關系,有一些規則可以確定用於比較的實際類型( int值被類型轉換為size_t ,然后<運算符進行比較。

max(3, v.size());

std::max的定義在功能上要求它的兩個參數是相同的類型。 他們不是。 因此編譯錯誤。

現在您了解了原因,請嘗試重新閱讀以下錯誤消息,看看您現在是否理解編譯器告訴您的確切信息:

推斷參數“_Tp”的沖突類型(“int”與“unsigned long”) max(const _Tp&, const _Tp&);

正如您在此處看到的,編譯器正在努力消化帶有兩個參數的 function,這兩個參數的類型相同: const _Tp & 這就是max()的定義:它的兩個參數都是相同的類型。

好吧,可憐的編譯器看到這些參數之一是int ,另一個是size_t (又名“unsigned long”)並放棄了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM