I have been learning C++ and came across a function, but the return type was a vector.
Here is the code:
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
is part of a struct defined as:
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;
}
};
What is the purpose of using vector< Name>inputName()? What is it doing?
And why can I just not create a void function and pass a vector through it?
I.e.:
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);
}
}
You can return a structure from a function (or use the = operator) without any problems. It's a well-defined part of the language.
At a low level a parameter pass by reference is implemented using a pointer whereas primitive return values are typically passed literally in registers. So return values are likely to perform better.
Data structures handle four main functions for us: Inputting information. Processing information. Maintaining information. Retrieving information.
Q: How are structure passing and returning implemented? A: When structures are passed as arguments to functions, the entire structure is typically pushed on the stack, using as many words as are required. (Programmers often choose to use pointers to structures instead, precisely to avoid this overhead.)
Your question is basically: Do I return by value or do I use an output argument?
The general consensus in the community is to return by value, especially from C++17 on with guaranteed copy elision. Although, I also recommend it C++11 onwards. If you use an older version, please upgrade.
We consider the first snippet more readable and understandable and even more performant.
From a callers perspective:
std::vector<Name> names = inputNames();
It's clear that inputNames returns you some values without changing the existing state of the program, assuming you don't use global variables (which you actually do with cin
).
The second code would be called the following way:
std::vector<Name> names;
// Other code
inputNames(names);
This raises a lot of questions:
It used to be good practice when computers were slow and compilers had troubles optimizing, though, at this point, don't use it for output arguments.
When do you use the last style: if you want an in-out argument. In this case, if you intend to append, the vector already had data, and that actually makes sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With