C_C++

vector 자료형에 pair, class pointer

junl 2022. 6. 30. 00:58

1. pair

#include<cstdio>
#include<vector>
using namespace std;

typedef pair<int, int> Pair;

class test
{
public:
	test() {};
	int a;
	int b;
	void setInt(int a, int b)
	{
		this->a = a;
		this->b = b;
		
	}
	 Pair getInt()
	{
		 return Pair(a, b);
	}
};
int main(void)
{
	vector<Pair>vect;
	test t;
	t.setInt(3, 5);
	vect.push_back(t.getInt()); // test().getInt 가 pair형이다. 이를 push할려면 그럼 vector의 자료형도 pair형이어야함.
	printf("%d %d", vect[0].first, vect[0].second);
}

 

2. vector 자료형으로 class pointer 사용해보기

#include<cstdio>
#include<vector>
using namespace std;
class test
{
public:
	int a;
	int b;
	int c;
	test() {};
	test(int a, int b, int c)
	{
		this->a = a;
		this->b = b;
		this->c = c;
	}
	void setVal(int a, int b, int c)
	{
		this->a = a;
		this->b = b;
		this->c = c;
	}
	const int get_sum()
	{
		return a + b + c;
	}
};

int main(void)
{
	/*1. vector 자료형이 클래스*/
	test t(1,1,1);
	vector<test>vect;
	vect.push_back(t);

	/*2. vector자료형이 클래스형 포인터*/
	test* tt;
	tt = &t;
	vector<test*>vect2;
	tt->setVal(1, 2, 3); // tt가 가리키는 클래스 t 내부의 값들을 setVal을 통해 변경/.
	vect2.push_back(tt); // tt클래스를 push. 

	vect.push_back(*tt); // *tt 는 tt가 가리키는 주소의 값 즉 클래스 t의 값들을 vect에 push.
	//vect 자료형은 클래스 포인터가 아닌, 클래스이다. 포인터 클래스 자료형인
	//tt가 가리키는 값의 자료형이 클래스포인터가 아닌, 클래스이다. 그래서 vect에 push가능하다.

	printf("%d %d", vect2[0]->get_sum(),vect[1].get_sum());
}