[英]What do I return to the main function from my string function?
我完成了我的实验室问题,但我有一个快速的问题来解决这个问题。 我在函数中有一个需要返回到 main 的向量,以便我可以输出向量的元素。 我把 return a; 在函数的末尾,因为 a 是函数中向量的名称,但出现错误。
*它说“cout << the names are”的地方应该是主要的,但我不知道要在回报中放什么。 *我也把 return 0 设置为我让整个程序工作的唯一方法,因为输出也在函数中,但我需要它返回 main 并更改 return 0; 对不起,如果这是一个不好的问题,我仍在学习,谢谢。
string switching(vector<string> a, int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] > a[j]) {
swap(a[i], a[j]);
}
}
}
cout << "The order of names are...\n";
for (int i = 0; i < n; i++) {
cout << a[i] << "\n";
}
return 0;
}
正如所建议的,您可以将函数签名更改为
std::vector<std::string> switching(std::vector<std::string> a, int n)
或者,您可以通过引用传递字符串向量参数:
void switching(std::vector<std::string>& a, int n)
这显示了主要调用第一个版本:
#include <iostream>
#include <string>
#include <vector>
std::vector<std::string> switching(std::vector<std::string> a, int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] > a[j]) {
swap(a[i], a[j]);
}
}
}
return a;
}
int main()
{
std::vector<std::string> strings{
"John",
"Fred",
"Alice"
};
auto sorted = switching(strings, strings.size());
std::cout << "The order of names are...\n";
for (auto const& name : sorted) {
std::cout << name << "\n";
}
return 0;
}
1.可以修改函数的返回类型;
vector<string> switching(vector<string> a, int n)
{
//Your core-code here;
return a;
}
void switching(vector<string> &a, int n)
{
//Your core-code here;
}
这样就可以在主函数中同时改变参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.