0

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.

kvrier
  • 23
  • 7
  • 4
    Continue to use a reference: `std::vector & foo {readData()};`? – NathanOliver Oct 26 '22 at 15:02
  • Or `for (const auto& element : readData())`? – Yksisarvinen Oct 26 '22 at 15:03
  • 1
    Why you are using 2 different person object to store `name` and `age`? You should use a single object: `Person p; std::cin >> p.name; std::cin >> p.age;` – Aamir Oct 26 '22 at 15:07
  • Thank you guys for prompt answer. Both NathanOliver's and Yksisarvinen's solutions work. Aamir is right, I'm just really tired. – kvrier Oct 26 '22 at 15:16
  • Please avoid encapsulation breakdown such as `static` variables exposed via (non-`const`) references; your future self will thank you. – Andrej Podzimek Oct 26 '22 at 16:00
  • If you make the vector non-static and return it by value, there will still not be any copies. C++ Magic! [What are copy elision and return value optimization?](https://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization) – BoP Oct 26 '22 at 16:05

0 Answers0