Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

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 164 views
5 answers 369 views
5 answers 290 views
1 answer 167 views
2 answers 179 views
...