1

我尝试使用std::replace算法:

replace(out.begin(), out.end(), '\r', '\r\n');    // error
replace(out.begin(), out.end(), "\r", "\r\n");    // error
replace(out.begin(), out.end(), "\\r", "\\r\\n"); // error

我总是收到参数不明确的错误。我怎样才能指定\r\n所以编译器不会抱怨?

编辑:

错误:

 could not deduce template argument for 'const _Ty &' from 'const char [5]' 
 template parameter '_Ty' is ambiguous
'replace': no matching overloaded function found    
4

1 回答 1

3

虽然原则上这可以通过标准/Boost 函数的某种组合来解决,但它足够具体,可以获得自己的函数,因此也可以获得自己的 impl。这可能就像这样简单:

std::string cr_to_crlf(std::string const& s) {
    std::string result;
    result.reserve(s.size());

    for (char c : s) {
        result += c;
        if (c == '\r') {
            result += '\n';
        }
    }
    return result;
}
于 2018-07-12T10:22:46.853 回答