Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
680 views
in Technique[技术] by (71.8m points)

c++ - Line 5: Char 54: error: no matching function for call to '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;
    }
};

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...