-1

I have a vector with a bunch of People structs inside of it. These People structs have information about the individual person. It's basically a huge tree. It would look like this if it were drawn out:

    Joe        Bob
    / \        / \
  Age Weight Age Weight
   |    |     |    |
  14   140   22   160

The people at the top are structs, and they are stored inside of a vector<People>. However, these people are generated while the program runs.

I can have the program generate the name (like "Bob"), but how can I create a new instance of the People struct that way?

This is similar to Automatically generate struct instances but that doesn't have an answer that works.

Alexey Frunze
  • 61,140
  • 12
  • 83
  • 180
Cheryl
  • 17
  • 1
  • 4
    With your previous question and this one, it sounds like you could use a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). IMHO a good reference book would answer most of your questions. – NathanOliver Mar 14 '19 at 21:42
  • Are you aware of `new`? – Yunnosch Mar 14 '19 at 21:45
  • 3
    Take a look at [`std::vector::emplace_back`](https://en.cppreference.com/w/cpp/container/vector/emplace_back). Nathan Oliver is right. C++ is an unforgiving language to learn without a good set of references. You can't even count on the Internet for most of it because until you have a good grasp of what good C++ looks like you can't filter out the bad information that makes up the vast majority of C++ tutorials and help sites. – user4581301 Mar 14 '19 at 21:46
  • It seems to be another homework assignment, learning to use dynamic memory, it seems. – U. Windl Mar 15 '19 at 01:27
  • 1
    That tree diagram isn’t very representative of the code. It makes it look like there are *strings* that ’own’ integers. That’s not how structs (in a vector) work. I’d forget the whole ’tree’ thing. – Biffen Mar 15 '19 at 11:06
  • @user4581301 Thanks! That worked for me! – Cheryl Mar 15 '19 at 17:16

1 Answers1

0

Suppose you defined Person as:

typedef struct {
    std::string name;
    unsigned int age;
    unsigned int weight;
} Person;

You can then create an instance like so:

Person p = {"Bob", 22, 70};
Vitor
  • 151
  • 6