I'd like to print members of structure from static vector created inside a function. It might sound convoluted, so lets bring an example.
struct Person
{
std::string name{};
int age{};
};
std::vector <Person>& readData()
{
int length{2};
static std::vector<Person> listOfPeople(length);
for(int i{0}; i<length; ++i)
{
std::cout << "Enter name: ";
Person Name;
std::cin >> Name.name;
std::cout << "Enter age: ";
Person Age;
std::cin >> Age.age;
listOfPeople[i] = { Name.name, Age.age };
}
return listOfPeople;
}
So far so good, snippet above works as expected. I can use function readData to input 2 'people'.
main() function is the place where I struggle. I want to print 2 'people' I've just put into the function. To do that I initialize std::vector foo with call to readData.
std::vector <Person> foo {readData()};
and loop to print the results
for (const auto& element : foo)
{
std::cout << element.name << ' ' << element.age << '\n';
}
But that defeats the whole purpose of returning function via reference. It creates foo and copies listOfPeople. How can I directly access listOfPeople? I've tried pointers, but it just messes up my program and makes compiler to throw bunch of errors. I tried to decipher them without success.