c++ - 在函数中返回 2 个值

标签 c++

我试图在读取文件时返回值(即行和列),并且由于我将读取多个文件并从每个文件中获取相同的变量,所以我认为编写一个函数会更好而不是复制和粘贴重复的代码。

无论如何,我正在尝试返回 2 个值并使用它们,请参阅下面的代码:

#include <iostream>
#include <fstream>

using namespace std;

int r(string fn);

int main()
{
    int a, b = r("input_a.txt");

    cout << "a --- " << a << endl;
    cout << "b --- " << b << endl;

}

int r(string fn)
{
    ifstream fin01;
    string file = fn;

    fin01.open(file.c_str());

    ...
    ...
    ...

    // Suppose I should be getting 2 for 'rows' and 3 for 'cols'
    return rows, cols;
}

我的输出是 0x7fff670778ec0x7fff670778e8...

有什么建议吗?

最佳答案

您不能从声明为具有单个 int 的函数返回两个值作为返回类型:

int r(string fn){
    /*...*/
    return rows,cols;  // <-- this is not correct
}

此外,您调用此函数的方式与您预期的不同:

int a, b = r("input_a.txt");

这声明了两个整数并用函数的返回值初始化第二个,但第一个保持未初始化(有关逗号运算符的更多解释,请参阅 TerraPass answer)。

您基本上有两个选择。第一个选项是将引用传递给函数,函数将结果分配给这些引用:

void r(string fn, int& rows,int& cols) {
    /*...*/
    rows = x;
    cols = y;
}

你可以这样调用它:

int a,b;
r("someString",a,b);

但是,通过这种方式,调用者必须“准备”那些返回值。恕我直言,使用返回值从函数返回结果更方便(听起来合乎逻辑,不是吗?)。为此,您只需定义一个封装两个整数的类型:

struct RowAndCol { int row;int col; };

RowAndCol r(string fn) {
    /*...*/
    RowAndCol result;
    result.row = x;
    result.col = y;
    return result;
}

并这样调用它:

RowAndCol rc = r("someString");

请注意,您还可以使用 std::pair<int,int>而不是定义您的自定义结构(参见例如 molbdnilos answer )。但是,恕我直言,只要您确切知道这对中包含的内容,最好给它一个合理的名称(例如 RowAndCol )而不是使用裸露的 std::pair<int,int> .如果您以后需要向该结构添加更多方法,这也会对您有所帮助(例如,您可能希望为您的结构重载 std::ostream& operator<< 以将其打印在屏幕上)。

PS:实际上您的输出看起来不像是由您显示的代码生成的。这些是一些内存地址,但在您的代码中既没有指针也没有地址运算符。

关于c++ - 在函数中返回 2 个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36645510/

相关文章:

lambda 表达式中的 C++ 模板仿函数

java - 计算机中有几级解释/编译?

c++ - 使用 Intel Intrinsics 时代码不会加速

.net - 如何在.net项目中使用C++类库

c++ - 我应该为我正在包装的结构使用转换运算符吗?

c++ - 计算大阶乘时间复杂度

javascript - 为 asm.js 编写优化的 JS

C++,模板参数错误

c++ - 警告 C5246 : the initialization of a subobject should be wrapped in braces

c++ - CMake:包含 vs add_subdirectory:相对头文件路径