gpt4 book ai didi

c++ - 引用 vector 不通过函数

转载 作者:太空狗 更新时间:2023-10-29 23:42:42 25 4
gpt4 key购买 nike

函数的引用 vector 不在内存中保存信息。我必须使用指针吗?

谢谢。

#include <iostream>
#include <cstdlib>
#include <vector>
#include <string>

using namespace std;

void menu();
void addvector(vector<string>& vec);
void subvector(vector<string>& vec);
void vectorsize(const vector<string>& vec);
void printvec(const vector<string>& vec);
void printvec_bw(const vector<string>& vec);

int main()
{
vector<string> svector;

menu();

return 0;
}
//functions definitions

void menu()
{
vector<string> svector;
int choice = 0;

cout << "Thanks for using this program! \n"
<< "Enter 1 to add a string to the vector \n"
<< "Enter 2 to remove the last string from the vector \n"
<< "Enter 3 to print the vector size \n"
<< "Enter 4 to print the contents of the vector \n"
<< "Enter 5 ----------------------------------- backwards \n"
<< "Enter 6 to end the program \n";
cin >> choice;

switch(choice)
{

case 1:
addvector(svector);
menu();
break;
case 2:
subvector(svector);
menu();
break;
case 3:
vectorsize(svector);
menu();
break;
case 4:
printvec(svector);
menu();
break;
case 5:
printvec_bw(svector);
menu();
break;
case 6:
exit(1);
default:
cout << "not a valid choice \n";

// menu is structured so that all other functions are called from it.
}

}

void addvector(vector<string>& vec)
{
//string line;

//int i = 0;
//cin.ignore(1, '\n');
//cout << "Enter the string please \n";
//getline(cin, line);
vec.push_back("the police man's beard is half-constructed");

}

void subvector(vector<string>& vec)
{
vec.pop_back();
return;
}

void vectorsize(const vector<string>& vec)
{
if (vec.empty())
{
cout << "vector is empty";
}
else
{
cout << vec.size() << endl;
}
return;
}

void printvec(const vector<string>& vec)
{
for(int i = 0; i < vec.size(); i++)
{
cout << vec[i] << endl;
}

return;
}

void printvec_bw(const vector<string>& vec)
{
for(int i = vec.size(); i > 0; i--)
{
cout << vec[i] << endl;
}

return;
}

最佳答案

您的问题是每次调用 menu() 都会创建一个隐藏前一个的新 vector ,这就是为什么在您看来它们是空的。如果您真的想递归调用菜单,请将您在 main 中创建的 vector 引用传递给它。

综上所述,菜单系统很少递归。您可能希望围绕 main 中对 menu() 的调用进行循环,直到用户选择退出。

关于c++ - 引用 vector 不通过函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2813207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com