Printing from a vector of structs

Hello, I'm trying to print values from a vector of a struct and I don't really know how to do that. Here is a simple code that I have for now to test how to add data to the vector then attempt to print it out.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <vector>
#include <string>
#include <deque>
#include <fstream>

using namespace std;

struct Employee							//employee data
{
	int ID;
	string fname;
	string lname;
	double salary;
	int hpw;
	string work;
	int flag;
};
struct Employee a;
vector<Employee> AddEmployee;			//for adding employees
deque<Employee> ListEmployee;			//for listing in a sort() function later on

void Addemployee()
{
	
}

int main()
{
	
	a.ID = 1;
	a.fname = "A";
	a.lname = "A";
	a.salary = 20;
	a.hpw = 40;
	a.work = "m";
	a.flag = 1;
	AddEmployee.push_back(a);
	cout << AddEmployee.ID << endl;

	return 0;
}


Any help would be appreciated.
The compiler shall issue an error for this statement

cout << AddEmployee.ID << endl;

AddEmployee is an object of type std::vector<Employee>. The record AddEmployee.ID means that you are trying to call method ID declared in class std::vector. However class std::vector has no such a method. So before accessing ID you should get an object of type Employee where this data member is declared. The simplest way is to use the subscripting operator of class std::vector

cout << AddEmployee[0].ID << endl;


AddEmployee[0] returns an object of type Employee that has data member ID.
Last edited on
If you do not want to bother how many elements are contained in the vector and display all its alement you can use the range-based for statement

1
2
3
4
for ( const Employee &e : AddEmployee )
{
   std::cout << e.ID << std::endl;
}
Topic archived. No new replies allowed.