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,933 questions

51,870 answers

573 users

How to store a class object in a vector with C++

1 Answer

0 votes
#include <iostream>
#include <vector>

using std::cout;
using std::endl;
using std::vector;

class Test {
	int n;
public:
	Test() { n = 0; }
	Test(int _n) { n = _n; }
	Test &operator=(int _n) {
		n = _n; 
		return *this;
	}
	int get() { return n; }
};

int main()
{
	vector<Test> vec;

	for (int i = 0; i < 5; i++)
		vec.push_back(Test(i * 2));

	for (int i = 0; i < vec.size(); i++)
		cout << vec[i].get() << " ";
	cout << endl;

	for (int i = 0; i < vec.size(); i++)
		vec[i] = vec[i].get() * 5;

	for (int i = 0; i < vec.size(); i++)
		cout << vec[i].get() << " ";
	cout << endl;

	return 0;
}


/*
run:

0 2 4 6 8
0 10 20 30 40

*/

 



answered May 17, 2018 by avibootz

Related questions

1 answer 433 views
1 answer 86 views
1 answer 163 views
1 answer 118 views
...