[英]What function data type should I use to return a vector.push_back()?
string yesno(string holder ,vector<string> symptom)
{
if(holder == "Y" || holder == "y"){
return symptom.push_back("Y");
}
else if(holder == "N" || holder == "n"){
return symptom.push_back("N");
}
else{
cout <<"Wrong input" << endl;
return symptom.push_back("-");
}
}
So this is my function for when I'm asking a user are they experiencing a certain symptom and then ask for Y/y or N/n for an answer.所以这是我的功能,当我问用户他们是否遇到某种症状,然后询问 Y/y 或 N/n 以获得答案时。
The if
blocks in the function detects the upper and lower case of Y or N and then I'm returning symptom.push_back()
as "Y" or "N" but I'm getting this error:函数中的
if
块检测 Y 或 N 的大写和小写,然后我将symptom.push_back()
返回为“Y”或“N”,但出现此错误:
error: could not convert 'symptom.std::vectorstd::__cxx11::basic_string<char ::push_back(std::__cxx11::basic_string(((const char*)"Y"), std::allocator()))' from 'void' to 'std::__cxx11::string' {aka 'std::__cxx11::basic_string'}|
错误:无法转换 'symptom.std::vectorstd::__cxx11::basic_string<char ::push_back(std::__cxx11::basic_string(((const char*)"Y"), std::allocator()) )' 从 'void' 到 'std::__cxx11::string' {aka 'std::__cxx11::basic_string'}|
The std::vector.push_back()
function has a void
return type, so there is no way you can convert what it returns to any type (because it doesn't return anything).该
std::vector.push_back()
函数有一个void
返回类型,所以也没有办法,你能将它返回到任何类型的(因为它不返回任何东西)。
However, there is the std::vector.back()
function, which returns a reference to the last element;但是,有
std::vector.back()
函数,它返回对最后一个元素的引用; so, you could make your conditional push_back()
calls in the relevant blocks, then have a single return statement that 'retrieves' the element that was pushed:因此,您可以在相关块中进行有条件的
push_back()
调用,然后使用单个return 语句“检索”被推送的元素:
string yesno(string holder, vector<string> symptom)
{
if (holder == "Y" || holder == "y") {
symptom.push_back("Y");
}
else if (holder == "N" || holder == "n") {
symptom.push_back("N");
}
else {
cout << "Wrong input" << endl;
symptom.push_back("-");
}
return symptom.back();
}
Also, as noted in the comments, you are passing your symptom
vector by value , which means that a local copy will be used and any changes made to that will be lost when the function returns (the copy will be deleted).此外,如评论中所述,您通过 value传递
symptom
向量,这意味着将使用本地副本,并且在函数返回时对其所做的任何更改都将丢失(副本将被删除)。 You may want to consider passing symptom
by reference:您可能需要考虑通过引用传递
symptom
:
string yesno(string holder, vector<string>& symptom) // Pass by reference!
{
//...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.