gpt4 book ai didi

c++ - 为什么我们在 C++ 中使用返回数据结构的函数?

转载 作者:行者123 更新时间:2023-12-01 09:27:44 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Which is more efficient: Return a value vs. Pass by reference?

(7 个回答)


去年关闭。




我一直在学习 C++ 并遇到一个函数,但返回类型是一个 vector 。
这是代码:

vector<Name> inputNames() {
ifstream fin("names.txt");
string word;
vector<Name> namelist;

while (!fin.eof()) {
Name name;
fin >> name.first_name;
fin >> name.last_name;
namelist.push_back(name);
}

return namelist;
}
name是结构体的一部分,定义为:
struct Name {
string first_name;
string last_name;

bool operator<(const Name& d) const {
return last_name > d.last_name;
}

void display() {
cout << first_name << " " << last_name << endl;
}
};
使用 的目的是什么? vector <名称>输入名称() ?它在做什么?
为什么我不能创建一个空函数并通过它传递一个 vector ?
IE。:
void input(vector<Name>&v){
ifstream fin("names.txt");
string word;

while (!fin.eof()) {
Name name;
fin >> name.first_name;
fin >> name.last_name;
v.push_back(name);
}
}

最佳答案

您的问题基本上是:我是按值返回还是使用输出参数?
社区的普遍共识是按值返回,尤其是从 C++17 开始,保证复制省略。虽然,我也推荐它 C++11 以上。如果您使用旧版本,请升级。
我们认为第一个片段更具可读性和可理解性,甚至性能更高。
从调用者的角度:

std::vector<Name> names = inputNames();
很明显, inputNames 会在不更改程序现有状态的情况下返回一些值,假设您不使用全局变量(实际上是使用 cin 进行的)。
第二个代码将按以下方式调用:
std::vector<Name> names;
// Other code
inputNames(names);
这引发了很多问题:
  • inputNames 使用名称作为输入还是扩展它?
  • 如果名称中有值,函数用它做什么?
  • 函数是否有返回值表示成功?

  • 当计算机运行缓慢并且编译器在优化时遇到问题时,它曾经是一种很好的做法,但是,此时不要将它用于输出参数。
    你什么时候使用最后一种风格:如果你想要一个进出参数。在这种情况下,如果你打算追加, vector 已经有数据,这实际上是有道理的。

    关于c++ - 为什么我们在 C++ 中使用返回数据结构的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62528268/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com