c++ max() 报错 error: no matching function for call to ‘max’

  • Post author:
  • Post category:其他


先举个小例子哈,我要统计字符串数组中最长字符串的长度。

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

int main() {
    int res = 0;  // 记录最长字符串的长度
    vector<string> words = {"abcd", "efg", "hijklmn"};
    for (string& word: words) {
        res = max(res, word.size());
    }
    cout << res << endl;  // 7
    return 0;
}

这个时候,运行代码是会报错的:error: no matching function for call to ‘max’

为什么???

原来是因为 size() 函数的返回值是size_t。什么是size_t ?

在c++中,size_t 被定义为 unsigned long int。

而max函数中的两个值一个是int型,一个是size_t型的,比不了!

那我做一点小改变,把res的定义改成size_t,或者是把res = max(res, word.size())改成res = max(res, int(word.size()))就解决了。

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

int main() {
    size_t res = 0;  // 记录最长字符串的长度
    vector<string> words = {"abcd", "efg", "hijklmn"};
    for (string& word: words) {
        res = max(res, word.size());
    }
    cout << res << endl;  // 7
    return 0;
}



版权声明:本文为weixin_43967256原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。