How to define and use a list of objects in C++

1 Answer

0 votes
#include <iostream>
#include <list>

using std::cout;
using std::endl;
using std::list;

class Test {
public:
	char language[32];
	float salary;
	Test() {
		strcpy(language, "");
		salary = 0.0;
	}
	Test(char *l, float s) {
		strcpy(language, l);
		salary = s;
	}

	void add_to_salary(int percent) {
		salary += (salary * percent) / 100;
	}

	void print() {
		cout << language << ": " << salary << endl;
	}
};

int main()
{
	list<Test> lst;

	lst.push_back(Test("c++", 10000));
	lst.push_back(Test("c", 11000));
	lst.push_back(Test("java", 9000));

	list<Test>::iterator p = lst.begin();

	while (p != lst.end()) {
		p->print();
		p++;
	}
	cout << endl;

	p = lst.begin();
	p->add_to_salary(3);

	while (p != lst.end()) {
		p->print();
		p++;
	}
	cout << endl;

	return 0;
}

/*
run:

c++: 10000
c: 11000
java: 9000

c++: 10300
c: 11000
java: 9000

*/

 



answered Apr 20, 2018 by avibootz
edited Apr 20, 2018 by avibootz

Related questions

2 answers 208 views
5 answers 426 views
5 answers 321 views
1 answer 201 views
1 answer 198 views
...