我从我的字符串函数返回到主函数
What do I return to the main function from my string function?
我完成了我的实验室问题,但我有一个快速的问题要解决。我在函数中有一个向量,需要返回到 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;
}
- 参数可以通过引用传递。
void switching(vector<string> &a, int n)
{
//Your core-code here;
}
这样,参数可以在主函数中同时更改。
相关文章:
- 从函数返回const char*数组
- 检查函数返回类型是否与STL容器类型值相同
- 从 c 或 cpp 系列子函数返回到主函数
- 从函数返回任意简单类型的数据
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 从 C++ 中的函数返回数组地址问题
- VirtDisk.h QueryChangesVirtualDisk() 函数返回 RangeCount 为 0
- 为什么glGetSubroutineIndex为不同的函数返回相同的值?
- 在 c++ 中将函数返回类型指定为模板参数
- 从封装在对象中的函数 C++ 返回时为空的列表
- 为什么向量内部的指针在从函数返回时会发生变化?
- 函数返回的 rvalue 引用(表达式)是 xvalue - 但没有标识?
- 程序中的布尔函数返回输入的范围无论如何都是无效的
- 寿命延长从函数返回引用
- 程序不向函数返回值
- 字符串函数返回奇怪的值
- 类的大问题,以及从空函数c++返回
- 为什么在尝试测量函数返回所需的时间时,我的运行时编号是错误的?
- C++二叉搜索树模板从函数返回节点
- NVCC 错误:string_view.h:constexpr 函数返回是非常量