Line 5: Char 54: error: no matching function for call to 'min(int, std::__cxx11::basic_string<char>::size_type)'

点点圈 提交于 2021-02-02 09:54:40

问题


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;
    }
};

Line 5: Char 54: error: no matching function for call to 'min(int, std::__cxx11::basic_string::size_type)'


回答1:


As the compiler tries to tell you, the issue is that the types of start + k -1 and s.size() - 1 are different. So one way to fix this is to change the types of start and k to 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;
}

Alternatively you can just cast s.size() - 1 to int:

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

There is also the third way to explicitly specify the template parameter of std::min, but that might trigger signed-to-unsigned / unsigned-to-signed conversion warnings of your compiler:

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


来源:https://stackoverflow.com/questions/58779553/line-5-char-54-error-no-matching-function-for-call-to-minint-std-cxx11

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!