C++字符串,通过引用传递从编译器生成错误

c++ string , pass by reference generates error from compiler

本文关键字:编译器 错误 字符串 引用 C++      更新时间:2023-10-16
void gp(vector<string>& res, string str, int l, int r, int n){
    if(l == n) {
        string right = string( n-r, ')');
        str += right;
        res.push_back(str);
        return;
    }
    gp(res, str+'(', l+1, r,n);
    if (l > r) {
        gp(res, str+')', l, r+1,n);
    }
}
vector<string> generateParenthesis(int n) {
    vector<string> res;
    gp(res, "", 0, 0, n);
    return res;
}

对于此代码如果我将第一行更改为

 void gp(vector<string>& res, string& str, int l, int r, int n){

没有用于调用的匹配函数 '解决方案::gp(std::vector>&, std::basic_string, int, int&, int&)'

的问题,为什么我不能通过这个 std::string 的引用传递?

谢谢!

你的字符串实际上是一个const char *,你在调用函数时从该const char *构造一个右值字符串,但你的函数需要一个左值,因为引用不是常量。这将起作用:

string mystring("");
gp(res, mystring, 0, 0, n);