![](/img/trans.png)
[英]How do you declare a pointer to a function that returns a pointer to an array of int values in C / C++?
[英]C++: How do you create a return function that returns a vector/array?
這就是代碼背后的動機。 有一個男孩叫鮑勃,今天是他的生日。 他邀請50個以上的朋友,但並非所有的朋友都想給他買禮物。 鮑勃收到了50份禮物,盡管其中有些是空的。 他的好朋友告訴他關閉第二個盒子。 對於第三個盒子,他應該將每個關閉狀態更改為打開狀態,並將每個打開狀態更改為關閉狀態。 他繼續對第n個小於50的第n個框執行此操作。最后打開的框將具有禮物。
本來可以幫助我為數學課解決一個問題,但是我並不了解C ++編程的所有復雜方面。 我希望我的字符串getValue(vector&arr)返回一個數組/向量。 這段代碼沒有編譯,但是顯示了我正在嘗試執行的操作。
#include <iostream>
#include <vector>
#include<algorithm>
using namespace std;
string getValue(vector<string> &arr);
int main()
{
vector<string> myArr(2);
vector<string> newArr(2);
for(int i=2; i <= 50; i++)
{
if(i%2==0)
{
myArr.push_back("close");
}
else
{
myArr.push_back("open");
}
}
newArr = getValue(myArr);
for(int i=2; i <=50; i++)
{
cout << i << " " << newArr[i] << endl;
}
}
string getValue(vector<string> &arr)
{
for(int i=2; i <=50; i++)
{
if(arr[i]=="close")
{
arr[i]="open";
}
else if(arr[i]=="open")
{
arr[i]="close";
}
}
return arr;
}
您是通過引用將向量傳遞給getValue()
的,這意味着您對該函數所做的更改將影響原始向量(換句話說,您不是在向量的副本上進行操作-實際上是在向量)。
因此,您不需要從getValue()
返回任何內容-只需使其void
,它就可以執行您想要的操作。
string getValue(vector&arr)-返回類型是字符串,而不是vector。 您需要更改其返回類型或將其設置為none。
PS:newArr = getValue(myArr); 它在SCOPE后面,並且定位錯誤...該死,第三個PS,分配了錯誤的代碼規則
您不能使string getValue(vector<string> &arr)
返回數組/向量。 它只能返回一個string
。 如果要讓函數返回數組/向量,則必須在函數簽名中這樣說。
對於語法部分:
函數的返回類型是字符串。 將其更改為vector,以使您的功能正常工作。
您可以簡單地全局聲明向量。 這將消除將其傳遞給函數以及將其返回的需要。
對於邏輯部分:
您的問題是,Bob切換了每個第三個框,但是在程序中,Bob更改了每個框(如果關閉)的打開狀態以及每個框(如果打開的關閉)狀態。 如果您在問題中所寫的內容正確,則您的代碼應如下所示。
#include <iostream>
#include <vector>
using namespace std;
void getValue();
vector<string> myArr(2);
int main()
{
for(int i=2; i <= 50; i++)
{
if(i%2==0)
{
myArr.push_back("close");
}
else
{
myArr.push_back("open");
}
}
getValue();
for(int i=2; i <=50; i++)
{
cout << i << " " << myArr[i] << endl;
}
}
void getValue()
{
for(int i=3; i <=50; i+=3)
{
if(myArr[i]=="close")
{
myArr[i]="open";
}
else if(myArr[i]=="open")
{
myArr[i]="close";
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.