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

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

#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;
}
  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值