如何传递vector的vector作为函数的默认实参,c++



IDE显示最后一个参数错误。我是c++的新手,无法理解它。请帮助。提前谢谢。

void Box_2(vector<vector<int>> &v,
string text1 = "", 
string text2 = "",  
vector<vector<int>> &trace = {}
)

问题不能将对非const对象的左值引用绑定到相应类型的临时对象。

例如,

int &ref = 5; //THIS WILL NOT WORK
const int &REF = 5; //THIS WILL WORK 

解决如果出现此错误,可以将最后一个参数name设置为对const对象的左值引用,该对象可以绑定到一个临时对象,如下所示:

void Box_2(vector<vector<int>> &v,
string text1 = "", 
string text2 ="",  
//---------vvvvv------------------------------------->low level const added here
const vector<vector<int>> &trace = {}
);

请注意,使用上述方法您将无法更改name。这是添加低级const的结果。


您也可以完全省略默认参数,如下所示:

void Box_2(vector<vector<int>> &v, string text1, string text2, vector<vector<int>> &trace);

现在您将能够更改name绑定的底层向量。

最新更新