#include <std_lib_facilities_4.h>
usingnamespace std;
struct Item {
string name;
int iid;
double value;
};
//***************************
int main()
{
vector<Item> vi;
ifstream rfile("input.txt");
if (!rfile) {
cout << " Failar on opening the file!\n\n";
system("pause");
return 1;
}
string s;
int id;
double value;
for (size_t i = 0; i < 10; ++i) {
rfile >> s >> id >> value;
vi.push_back({ s, id, value });
}
for (constauto& v : vi)
cout << v.name << " " << v.iid << " " << v.value << endl;
cout << "\n";
system("pause");
return 0;
}
We have a vector of Items. First we read the data (s, id, value) and then push back them to populate each object of the Item in the vector. The question is, how does the vector put each data (s, id, value) into their corresponding values in the each struct object, because we don't have a constructor for the struct to populate its data (name, iid, value) using a list of arguments.
Thank you.
So, as long as, the values are in order of the declared variables in the struct/class, there is no need to define a constructor for the struct/class.
I'm not sure what the #include file is, but you only need to #include <vector>, <string>, <fstream>, and <iostream> for this program. The file you're using might have facilities you don't need.
@lastchance, thank you a lot for your clarification, since my answer about structs could indeed be deceitful deceptive. [<-- Edit: corrected]
@Frank14, to my knowledge, as a morsel of consolation :-) , you should always being able to ‘default’ all members, regardless it’s public or not (if they admit a default value, of course):
Your example (and link) was good, @Enoizat. On the whole it's what I tend to expect when using a struct (where, out of force of habit, I tend to leave everything public).
It was the later (not yours) assumption that it was equally good for classes that was troubling me.