我从我的字符串函数返回到主函数

What do I return to the main function from my string function?

本文关键字:函数 返回 字符串 我的      更新时间:2023-10-16

我完成了我的实验室问题,但我有一个快速的问题要解决。我在函数中有一个向量,需要返回到 main,以便我可以输出向量的元素。我把返回 a;在函数的末尾,因为 a 是函数中向量的名称,但我收到错误。

*它说"cout <<名字是"应该在主要位置,但我无法弄清楚在退货中放什么。*我也放了 return 0,因为这是我让整个程序工作的唯一方法,因为输出也在函数中,但我需要它回到 main 并更改返回 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;    
}
  1. 参数可以通过引用传递。
void switching(vector<string> &a, int n)
{
     //Your core-code here;
}

这样,参数可以在主函数中同时更改。