[英]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.