태터데스크 관리자

도움말
닫기
적용하기   첫페이지 만들기

태터데스크 메시지

저장하였습니다.

쭈중이 교육용 STL 예제를 만들어봄.

2010/04/09 11:44
결과는 http://codepad.org/e8w9rAF8

그냥 간단하게 vector/list/map/pair 조금 써서 삽입삭제/이터레이터 정도만.

그냥 맛보기용 샘플.

// Made by YuriHan. 2010.04.09.
// YuriHan's Dream Factory(TM)
// http://blog.yurihan.net/

#include<vector>
#include<string>
#include<list>
#include<map>
#include<utility>	// pair
#include<algorithm>

using namespace std;

void usingVector();
void usingList();
void usingMap();
void usingPair();

int main(void)
{
	usingVector();
	usingList();
	usingMap();
	usingPair();
}

void usingVector()
{
	printf("----------vector----------\n");

	vector<int> vec;
	vec.push_back(123);
	vec.push_back(456);
	vec.push_back(789);

	for(unsigned int i=0;i<vec.size();i++)		// size는 내부 데이터의 갯수.
		printf("vec[%d] = %d\n",i,vec[i]);	// 배열처럼 접근 가능.
	
	// iterator 는 반복자. 이터레이터를 이용해 내부 데이터를 순회할 수 있음.
	// vec.begin()은 첫번째 객체의 이터레이터를 리턴.
	// vec.end()은 마지막 객체 +1의 이터레이터를 리턴.
	// 역방향 이터레이터도 존재함. rbegin / rend
	// 이터레이터로 다음 객체에 접근할때는 증감연산자 사용. --는 이전. ++는 다음.
	// ++it 는 내부에서 복사가 일어나지 않지만 it++는 내부에서 복사가 한번 일어나니 오버헤드가 좀 있음. (모든 연산자 오버로딩에 해당.)
	int i=0;
	for(vector<int>::iterator it = vec.begin() ; it != vec.end() ; ++it ) // 전체 데이터 순회
		printf("vec[%d] = %d\n",i++,*it); // *연산자가 오버로딩 되어있음. 요소를 꺼냄.

	vec.clear();

	return;
}

void usingList()
{
	printf("---------- list ----------\n");

	list<int> lst;
	lst.push_back(123);
	lst.push_back(456);
	lst.push_back(789);

	// 배열처럼 접근 불가.
	int i=0;
	for(list<int>::iterator it = lst.begin() ; it != lst.end() ; ++it ) // 전체 데이터 순회
		printf("list[%d] = %d\n",i++,*it); // *연산자가 오버로딩 되어있음. 요소를 꺼냄.

	// 두번째 요소 삭제
	list<int>::iterator iterase = lst.begin();
	++iterase; // advance(iterase,1);
	lst.erase(iterase);
	i=0;
	for(list<int>::iterator it = lst.begin() ; it != lst.end() ; ++it ) // 전체 데이터 순회
		printf("list[%d] = %d\n",i++,*it);

	//삽입
	list<int>::iterator itinsert = lst.begin();
	advance(itinsert,1);	//++itinsert; 
	lst.insert(itinsert,456);
	i=0;
	for(list<int>::iterator it = lst.begin() ; it != lst.end() ; ++it ) // 전체 데이터 순회
		printf("list[%d] = %d\n",i++,*it);

	lst.clear();

	return;
}

void usingMap()
{

	printf("---------- map ----------\n");

	// 선언은 map<key,value> 
	map<string,int> mapp;

	// 맵에 추가
	// 배열처럼 추가하면 됨. [] 안에는 키, 뒤쪽에는 값. map[key] = value;
	mapp["abc"] = 123;
	mapp["def"] = 456;
	mapp["ghi"] = 789;

	//배열처럼 접근하면됨
	printf("abc : %d\n",mapp["abc"]); // 키가 abc 인것을 리턴
	printf("def : %d\n",mapp["def"]); // 키가 def 인것을 리턴
	printf("ghi : %d\n",mapp["ghi"]); // 키가 ghi 인것을 리턴
	// 주의할점.
	// 추가되어있지 않은 키값을 리턴받으려고 할 경우,
	// ( 예 - printf("asdf : %d",mapp["asdf"]); )
	// map은 asdf라는 키값을 "생성"하고 value 는 기본 값을 리턴한다. (value가 int 이면 0을 리턴)

	// 그래서 요소가 있는지 찾을때는 find 를 사용. find는 이터레이터 리턴.
	
	map<string,int>::iterator itfind;
	itfind = mapp.find("abc");
	if(itfind != mapp.end()) // 요소가 없으면 map.end()를 리턴.
		printf("%s : %d\n",itfind->first.c_str(),itfind->second);	//first 가 key값 second 가 value값
	itfind = mapp.find("def");
	if(itfind != mapp.end())
		printf("%s : %d\n",itfind->first.c_str(),itfind->second);
	itfind = mapp.find("ghi");
	if(itfind != mapp.end())
		printf("%s : %d\n",itfind->first.c_str(),itfind->second);
	
	// it->first 는 (*it).first

	for(map<string,int>::iterator it = mapp.begin() ; it != mapp.end() ; ++it ) // 전체 데이터 순회
		printf("%s : %d\n",it->first.c_str(),it->second); // 내부에서 검색을 위해 마음대로 정렬해놓음. 넣은순서와는 관계없이 나옴.

	mapp.clear();

	return;
}

void usingPair()
{
	//구조체 만들기 귀찮을때 씀.
	//두가지의 데이터를 하나로 묶어서 관리.
	printf("---------- pair ----------\n");

	vector<pair<string,int> > vecpair; // 이렇게 선언할때는 vector<pair<string,int>> 로 하면 끝부분 >> 를 연산자로 판단해서 에러 남.. 그래서 > > 로 한칸 띄어줌.

	vecpair.push_back(make_pair("abc",123));
	vecpair.push_back(make_pair("def",456));
	vecpair.push_back(make_pair("ghi",789));

	for(unsigned int i=0;i<vecpair.size();i++)		
		printf("%s = %d\n",vecpair[i].first.c_str(),vecpair[i].second);	// first , second 로 접근.	

	for(vector<pair<string,int> >::iterator it = vecpair.begin() ; it != vecpair.end() ; ++it ) // 이터레이터도 마찬가지.
		printf("%s = %d\n",it->first.c_str(),it->second);	// first , second 로 접근.

	vecpair.clear();

	return;
}




진리는 http://www.cplusplus.com/reference/stl/
크리에이티브 커먼즈 라이선스
Creative Commons License

유리한 땜쟁이/저작

  1. 어머 친절한 오빠네~

  2. 코딩셔틀

  3. Blog Icon
    잘난코

    어머 친절한 아빠네~

  4. Blog Icon
    Formal Dresses

    Couldn't be written any better. Reading this post reminds me of my old room mate! He always kept talking about this <a href="http://www.dressaler.com/shoes.html" title="wedding shoes">wedding shoes</a>. This way even more people can enjoy your posts <a href="http://www.dressaler.com/wedding-accessories.html" title="Cheap Wedding Accessories">Cheap Wedding Accessories</a> and nothing beats a big audiance ;).I’m very certain they will understand lots of new stuff here than anybody else. I do appreciate that youve added relevant and intelligent commentary here though.<a href="http://www.dressaler.com/special-sale-wedding-dress-in-stock.html" title="wedding dress on sale">wedding dress on sale</a> Thank you!