第5行:字符54:错误:没有匹配的函数调用“ min(int,std :: __ cxx11 :: basic_string <char> :: size_type)”

class Solution {
public:
    string reverseStr(string s,int k) {
        for (int start = 0; start < s.size(); start += 2 * k) {
            int end = min(start + k - 1,s.size() - 1);
            while (start < end) {
                swap(s[start],s[end]);
                start++;
                end--;
            }
        }
        return s;
    }
};

第5行:字符54:错误:没有用于调用'min(int,std :: __ cxx11 :: basic_string :: size_type)'的匹配函数

PINGPING456 回答:第5行:字符54:错误:没有匹配的函数调用“ min(int,std :: __ cxx11 :: basic_string <char> :: size_type)”

编译器试图告诉您,问题在于start + k -1s.size() - 1的类型不同。因此,解决此问题的一种方法是将startk的类型更改为std::size_t

std::string reverseStr(std::string s,std::size_t k) {
    for (std::size_t start = 0; start < s.size(); start += 2 * k) {
        std::size_t end = std::min(start + k - 1,s.size() - 1);
        while (start < end) {
            swap(s[start],s[end]);
            start++;
            end--;
        }
    }
    return s;
}

或者,您也可以将s.size() - 1强制转换为int

int end = std::min(start + k - 1,static_cast<int>(s.size() - 1));

还有第三种方法来显式指定std::min的模板参数,但是这可能会触发编译器的有符号/无符号/无符号/有符号转换警告:

int end = std::min<int>(start + k - 1,s.size() - 1);
本文链接:https://www.f2er.com/3132814.html

大家都在问