vector<struct>

Hello i have made this struct and want to create a vector of its type.

1
2
3
4
5
6
7
struct Dog{
string name;
string type;
int age;
string color;
//...
};


vector<dog> family(5);
now i don't understand how to access the name, for example, or age to drop in some data.

x[0].name doesn't seem to work. and how can i use family.push_back( //what to type here? a function call would work? ).
Thank you
Why are you trying x[0].name when you clearly named your vector of dogs family?

And you put vector<dog> not vector<Dog> when your struct is Dog.

This works fine for me.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <vector>
using namespace std;
struct Dog{
	string name;
	string type;
	int age;
	string color;
};


int main()
{
	vector<Dog> family(5);
	family[0].name = "John";
	family[0].type = "Corgi";
	family[0].age = 5;
	family[0].color = "black";
	family[1].name = "blah";
	//etc.....
	return 0;
}
Additionally:
how can i use family.push_back( //what to type here?
1
2
3
4
5
6
std::vector<Dog> family;
Dog dog;
dog.name = "Fido"; dog.type = "Golden Retriever"; dog.age = 3; dog.color = "Golden";
family.push_back(dog); //copy
family.push_back(Dog("Mike", "Husky", 4, "Gray")); //explicit construction
family.push_back({"Wolf", "Poodle", 4, "Pink"}); //implicit construction 
Why are you trying x[0].name when you clearly named your vector of dogs family?

And you put vector<dog> not vector<Dog> when your struct is Dog.


These were typos while writing the example.
Thanks everyone i got it, i need to work with vectors more.
Topic archived. No new replies allowed.