Skip to content

Instantly share code, notes, and snippets.

@LusainKim
Last active August 29, 2015 14:22
Show Gist options
  • Save LusainKim/9583948c1e13842bac62 to your computer and use it in GitHub Desktop.
Save LusainKim/9583948c1e13842bac62 to your computer and use it in GitHub Desktop.
Study_STL
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Monster{
private:
string m_strName;
int m_iHP;
public:
// explicit : 딱 이대로만 만들어!
explicit Monster(string name, int hp) : m_strName(name), m_iHP(hp) { }
string name(){ return m_strName; }
int HP(){ return m_iHP; }
void AddHP(int hp){ m_iHP += hp; }
};
int main()
{
vector<Monster> vMonster;
// 랜덤하게 몬스터 생성
for (int i = 0; i < 10; ++i)
{
string str;
char strnum[10];
// 번호를 표시하기 위해 설정
sprintf_s(strnum, "%03d_",i + 1);
str += strnum;
for (int i = 0; i < 5; ++i) str += rand() % ('Z' - 'A') + 'A';
vMonster.push_back(Monster(str, rand() % 15 + 15));
}
// 생성된 몬스터 확인
cout << endl << "몬스터 확인" << endl;
// 범위 기반 for 문 : begin()과 end()가 있는 자료구조라면 뭐든 사용 가능!
// 자료구조의 처음부터 끝까지 전부 체크해줍니다.
for (auto p : vMonster)
cout << "몬스터 이름 : " << p.name() << "(HP : " << p.HP() << ")" << endl;
// 몬스터 체력 증가
// 위의 for문은 내용을 호출하지만 바꿀 수는 없는데요. 바꾸고 싶다면 &(레퍼런스)를 씁니다.
for (auto &p : vMonster)
p.AddHP(rand() % 15 + 15);
cout << endl << "체력 증가 " << endl;
for (auto p : vMonster)
cout << "몬스터 이름 : " << p.name() << "(HP : " << p.HP() << ")" << endl;
// 만약 4번째 녀석이 마음이 안 듭니다. 지우고 싶다면 erase() 함수를 사용해봅시다.
// vector는 배열처럼 쓸 수 있도록 연산자 오버로딩이 돼 있습니다. 어때요. 쓸만하죠?
cout << endl << vMonster[3].name() << " 사망! " << endl;
// erase()는 반복자를 인자로 받아요. 그리고 반복자는 엄청난 연산자 오버로딩이 돼 있죠.
vMonster.erase(vMonster.begin() + 3);
for (auto p : vMonster)
cout << "몬스터 이름 : " << p.name() << "(HP : " << p.HP() << ")" << endl;
// 몰살을 시키고 싶다면 list를 사용해봅시다. 여기서는 생략하구요.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment