반응형

cpp map

키, 값의 쌍으로 구성된 연관 컨테이너.

#include <map>


+constructor

std::map<char, int> first ;

first['a']=10 ;

first['b']=30 ;

first['c'] = 50 ;

std::map<char,int> second (first.begin(), first.end() ) ;

std::map<char,int> thrid (second) ;


std::map<char, int, classcomp> fourth ;

struct classcomp {

 bool operator() (const char&lhs, const char& rhs) const {  return lhs<rhs ; }

} ;


+일반적인 함수

begin(), end(), cbegin, cend, rbegin, rend, crbegin, crend, size(), clear(), empty() 


+at()

키값으로  요소를 찾아 값을 참조로 반환한다. []와 다르게 키가 없으면 익셉션(out_of_range) 발생.

std::map<std::string, int> mymap = { {"alpha", 0}, {"beta", 0}, {"gamma", 0} } ;

mymap.at("alpha") = 10 ;

mymap.at("beta") = 20 ;

mymap.at("gamma")=30 ;

mymap["alpha"]=40 ;


+count()

키 값이 일치하는 요소의 개수를 리턴한다. 따라서 0 또는 1만 리턴된다. 

mymap.count( "alpha" )    ; 해당 키가 존재하면 1, 없으면 0


+emplace()  (C++11)

새로운 요소를 맵에 추가한다. 중복된 키가 존재하면 추가나 업데이트가 되지 않는다. 

std::map<char,int> map1 ;

map1.emplace('x', 100) ;

map1.emplace('y', 200) ;

for (auto x : map1 ) {

std::cout << x.first << ' ' << x.second << std::endl ;

}

+insert()

map1.insert( std::pair<char,int>('a', 100) ) ;


+find()

키로 이터레이터를 찾는다.

std::map<char,int>::iterator it ;

it = map1.find('b') ;

if ( it!= map1.end() ) map1.erase(it) ;    // 키 'b'를 찾아 요소를 삭제한다.


+lower_bound, upper_bound

키로 범위를 정할 때 사용.

키가 a,b,c,d,e 가 있을 때

b~d까지의 범위

itlow = map1.lower_bound('b') ;    // point to 'b'

itup = map1.upper_bound('d') ;    // point to 'e' 주의!

map1.erase(itlow, itup) ;    // 'b'~'d'까지 삭제함. 

남은 요소는 a, e

+erase() ; 요소 삭제

erase(const_iterator pos) ;

erase(const key_type &k) ;

erase(const_iterator first, last) ;








'Develop > C&CPP' 카테고리의 다른 글

string function  (0) 2018.05.31
string  (0) 2018.05.30
List 1  (0) 2018.05.28
Array 1  (0) 2018.05.25
Vector 3  (0) 2018.05.23
반응형

cpp list class

리스트는 순서있는 컨테이너. 어느 위치라도 추가/삭제가 용이함. 더블 링크드 리스트로 구현.

#include <list>


+constructor

-empty container constructor

list(const allocator_type& alloc=allocator_type()) ;

-fill constructor

list(size_type n, const value_type& val, const allocator_type& alloc =allocator_type())

-range constructor

list(inputiterator first, last, alloc=allocator_type()) ;

-copy const.

list(const list& x, alloc=null) ;

-move const.

list(list &&x, alloc=null) ;

-initializer list const.

list(initializer_list<value_type> il, alloc=allocator_type()) ;


std::list<int> first ;

std::list<int> second (4, 100) ;    // 4개, 100의 값으로 채움.

std::list<int> third( second.begin(), second.end() ) ;

std::list<int> fourth (third ) ;

int arr1[]={1,2,3,4} ;

std::list<int> fifth( arr1, arr1+sizeof(arr1)/sizeof(int) ) ;


+일반적인 메소드

size() ; 요소 개수

back(), front() ; 마지막, 처음 원소 값.

begin(), end() ; iterator, 앞에 c를 붙이면 const type.

rbegin(), rend() ; reverse iterator, 앞에 c를 붙이면 const.

insert()

erase()


+수정

push_back(), pop_back()

push_front(), pop_front() ; 앞에서 추가할 수도 있다. (벡터는 앞에 추가하려면 .insert( .begin() , ..)을 사용해야 한다. )

emplace(), emplace_back(), emplace_front()

std::list< std::pair<int, char> > mylist ;

mylist.emplace_back( 10, 'a') ;

mylist.emplace_front( 20, 'b') ;

mylist.emplace( mylist.begin(), 100, 'x') ;

for (auto &x : mylist)  std::cout << x.first << ":" << x.second <<  "\n" ;

+reverse()

순서를 뒤집는다.


+sort()

정렬 ; 파라미터를 주지 않으면 디폴트로 오름차순 정렬된다.


bool compare_nocase(const std::string &first, const std::string &second) {

unsigned int i=0; 

while ( (i<first.length()) && (i<second.length()) ) {

  if ( tolower(first[i]) < tolower(second[i])) return true ;

  else if ( tolower(first[i]) > tolower(second[i]) ) return false ;

  ++i ;

}

return ( first.length() < second.length() ) ;

}

mylist.sort( compare_nocase ) ;



+unique()

중복 값을 가진 노드들을 제거한다.

mylist.sort() ;

mylist.unique() ;

mylist 출력 : 중복된 값들이 제거되고 오름차순으로 출력됨. 


중복의 범위를 정하는 함수 사용.

struct is_near { 

  bool operator() (double first, double second) {  return  (fabs(first-second) < 5.0 ) ; } 

} ;

mylist.unique( is_near() ) ; // 5.0 미만의 차이는 중복으로 보고 중복 제거한다. 


+=operator

내용을 모두 복사함.


+assign()

할당. 새로운 리스트의 내용으로 덮어쓴다. 

assign( inputiterator first, last)

assign(size_type n , const value_type &val) ;

assign( initializer_list<value_type> il) ;

std::list<int> first ;

first.assign(7, 100) ;    // 7개를 100으로 채움.

second.assign( first.begin(), first.end() ) ;


+ remove() ;특정 값을 찾아 요소를 삭제한다.

remove( const value_type & val) ;

erase()는 위치를 파라미터로 주고 삭제하는 것이고, remove()는 값을 찾아 삭제해 준다.


+remove_if() ; 조건에 따른 삭제.

struct is_odd {

bool operator() ( const int&value ) {  return (value%2)==1; } 

} ;

mylist.remove_if(is_odd()) ;        // 홀수를 제거한다.



+splice() ; 리스트를 다른 리스트로 이동. (copy가 아님)

-전체 ; splice( const_iterator position, list &x) ;

    splice(const_iterator position, list && x) ;

-한 개 ; splice( position, list &x, const_iterator i) ;

-범위 ; splice( position, x, first, last) ;

x에서 지정된 위치의 범위를 지정된 위치로 전송/삽입한다.

mylist = 1,2,3,4

mylist2 = 10,20,30

it = mylist.begin()+1 ;

mylist1.splice(it, mylist2) ;    // 1 10 20 30 2 3 4 , mylist2는  empty가 된다. (전송되었으므로.) 위에서 지정한 it는 여전히 2를 가리키므로 위치가 begin()+4 위치로 된다. 

mylist2.splice(mylist2.begin(), mylist1, it) ; // mylist2=2  ,   mylist=1 10 20 30 3 4 (2가 이동됨.)

it = mylist.begin()+3 ;

mylist.splice( mylist.begin(), mylist, it, mylist1.end() ) ; // 30 3 4 1 10 20


+merge() ; 병합. x의 데이터가 transfer 이동 됨.  splice()와 비슷하나 순서에 맞게 들어간다.

merge(list& x) ;

merge(list &x, Compare comp) ;

first.sort() ;

second.sort() ;

first.merge(second) ;    // second는 empty가 된다. second의 요소들이 first에 순서에 맞게 전부 추가됨.

first.merge(second, mycomparison) ;

bool mycomparison(double first, double second) {  return ( int(first) < int(second)) ; }














'Develop > C&CPP' 카테고리의 다른 글

string  (0) 2018.05.30
map  (0) 2018.05.29
Array 1  (0) 2018.05.25
Vector 3  (0) 2018.05.23
Vector 2  (0) 2018.05.18
반응형

cpp array class

fixed size의 순서있는 컨테이너. 선형적 연속으로 순서있게 요소들이 배열된다.

다른 표준 컨테이너들과는 달리 고정된 크기이고 요소들의 메모리 할당을 관리하지 않는다.

동적인 확장이 불가능하다. zero-size 도 가능하지만 dereference할 수는 없다.

#include <array>


+이터레이터 함수.

begin(), end(), rbegin(), rend(), cbegin(), cend(), crbegin(), crend()

사용 방법은 벡터와 같다.

+용량 함수

size() ; 요소 개수

max_size(); 최대 개수. array에서는 size()와 같다. 

empty() ; 비었는지 확인. true/false

+요소 접근

[] operator

at()

front(); 처음 요소값을 참조로 리턴

back() ; 마지막 요소값을 참조로 리턴

data() ; 데이터 포인터를 얻어온다.

+수정

fill() ; 특정 값으로 채운다.

swap() ; 같은 타입인 두 개의 배열을 서로 바꾼다. (같은 크기여야 한다. 다른 크기면 컴파일 에러)


+at과 []의 차이점.

둘 다 주어진 인덱스의 요소를 참조로 리턴한다. at은 파라미터로 주어진 인덱스가 범위를 벗어나면 out_of_range exception이 발생한다. [] operator에서는 범위를 벗어나면 프로그램이 죽는다.(범위체크가 없음. 수동으로 해줘야 함.)


std::array<int, 10> arr1 ;

for (int i=0; i<10; i++) arr1.at(i)=i+1 ;    // 1부터 10까지 할당

std::cout << arr1.front() << std::endl ;    // 첫 번째 요소 값 출력. 1

std::cout << arr1.back() << std::endl ;    // 마지막 요소 값 출력. 10

arr1.front() =100 ;    // 첫 번째 요소에 100을 할당. 1 대신 100으로 덮어씀.

arr1.back() = 50 ;    // 마지막 요소에 50을 할당. 10대신 50으로 덮어씀.


const char* cstr="Test string";    // 11자 alpha+1 null char.

std::array<char,12> arr2 ;

std::memcpy(arr2.data(), cstr, 12) ;

std::cout << arr2.data() << std::endl ;    // 위 스트링이 출력됨.


std::array<int, 6> arr1 ;    // int 타입 6개 크기 배열을 생성.

arr1.fill(5) ;    // 5로 전부 채움.


std::array<int, 5> f = {1,2,3,4,5} ;

std:;array<int, 5> g={10,20,30,40,50} ;

f.swap(g) ;    // f, g를 바꿈.

for (int &x : f) std::cout << x << '  ' ;        // 모든 원소 출력. 10 20 30 40 50

std::cout<<'\n' ;


참고) std::fill_n( 위치, 개수, 값) ; 특정 위치에서 n개를 특정 값으로 채움.

fill_n( OutputIterator first, Size n , const T & val) ;

std::vector<int> v1(8, 10) ;    // 8개 10으로 다 채움.

std::fill_n(v1.begin(), 4, 20) ;    // 처음부터 4개를 20으로 채움. 20,20,20,20,10,10,10,10

std::fill_n(v1.begin()+3, 3, 33 ) ;    // 인덱스3번 위치부터 3개를 33으로 채움. 20, 20, 20, 33, 33, 33, 10, 10





'Develop > C&CPP' 카테고리의 다른 글

map  (0) 2018.05.29
List 1  (0) 2018.05.28
Vector 3  (0) 2018.05.23
Vector 2  (0) 2018.05.18
Vector 1  (0) 2018.05.16

+ Recent posts