简体   繁体   中英

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

I finished my lab problem, but I have a quick question to fix the end. I have a vector in the function that needs to be returned to main so I can output the elements of the vector. I put return a; at the end of the function since a is the name of the vector in the function but I'm getting an error.

*Where it says "cout << the names are " should be in the main but I can't figure out what to put in the return. *I also put return 0 because it was the only way I had the whole program working since the output is also in the function, but I need it back in main and change the return 0; Sorry if this is a bad question I'm still learning, thanks.

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;
}

As has been suggested, you can change the function signature to

std::vector<std::string> switching(std::vector<std::string> a, int n)

Or, you could pass the string vector argument by reference:

void switching(std::vector<std::string>& a, int n)

This shows a main calling the first version:

#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.You could modify the return type of the function;

   vector<string> switching(vector<string> a, int n)
{
     //Your core-code here;
     return a;    
}
  1. The parameters could be pass by reference.
void switching(vector<string> &a, int n)
{
     //Your core-code here;

}

In this way, the parameters could change simultaneously in main function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM