C++ algorithm


알고리즘 시험 볼 때 유용하게 사용할 수 있는 STL이다.


레퍼런스 사이트에서 보면 각 함수들을 9가지 종류로 분류해 놓았다. 


이번 글에서는 그중 원소를 수정하지 않는 알고리즘(Non-modifying sequence) 중 몇가지를 알아본다.



1. count(begin, end, value) 

구간 [begin, end)에서 value의 원소 개수를 찾는다.


2. count_if(begin, end, f)

구간 [begin, end)에서 f 조건에 맞는 원소 개수를 찾는다.


count / count_if 예제


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>     // std::cout
#include <algorithm>    // std::count
#include <vector>       // std::vector
 
int main() {
    // counting elements in array:
    int myints[] = { 10,20,30,30,20,10,10,20 };   // 8 elements
    int mycount = std::count(myints, myints + 810); //10의 개수
    std::cout << "10 appears " << mycount << " times.\n";
 
    // counting elements in container:
    std::vector<int> myvector(myints, myints + 8);
    mycount = std::count(myvector.begin(), myvector.end(), 20); //20의 개수
    std::cout << "20 appears " << mycount << " times.\n";
 
    mycount = count_if(myvector.begin(), myvector.end(), [](int x) { return (x / 10) % 2 == 0; });//십의 자리 숫자가 짝수인 수의 개수
    std::cout << "myvector contains " << mycount << "\n";
 
    return 0;
}
cs




3. find(begin, end, value)

구간 [begin, end)에서 value와 같은 첫 번째 이터레이터를 찾는다.


4. find_if(begin, end, f)

구간 [begin, end)에서 f 조건에 해당하는 첫 번째 이터레이터


찾지 못하면 end를 반환


find / find_if 사용 예제


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// find_if example
#include <iostream>     // std::cout
#include <algorithm>    // std::find_if
#include <vector>       // std::vector
 
int main() {
    std::vector<int> myvector;
 
    myvector.push_back(10);
    myvector.push_back(25);
    myvector.push_back(40);
    myvector.push_back(55);
 
    std::vector<int>::iterator it;
 
    it = find(myvector.begin(), myvector.end(), 40);
    if (it != myvector.end())
        std::cout << "Element found in myvector: " << *it << '\n';
    else
        std::cout << "Element not found in myvector\n";
 
 
    it = find(myvector.begin(), myvector.end(), 100);
    if (it != myvector.end())
        std::cout << "Element found in myvector: " << *it << '\n';
    else
        std::cout << "Element not found in myvector\n";
 
    it = std::find_if(myvector.begin(), myvector.end(), [](int x) { return x % 2 == 1; });
    std::cout << "The first odd value is " << *it << '\n';
 
    return 0;
}
cs





5. max(a, b)

a와 b 중 더 큰 값 반환


6. min(a, b)

a와 b 중 더 작은 값 반환


max / min 사용 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>     // std::cout
#include <algorithm>    // std::min / std::max
 
int main() {
    std::cout << "max(1,2)==" << std::max(12<< '\n';
    std::cout << "max(2,1)==" << std::max(21<< '\n';
    std::cout << "max('a','z')==" << std::max('a''z'<< '\n';
    std::cout << "max(3.14,2.72)==" << std::max(3.142.72<< "\n\n";
 
 
    std::cout << "min(1,2)==" << std::min(12<< '\n';
    std::cout << "min(2,1)==" << std::min(21<< '\n';
    std::cout << "min('a','z')==" << std::min('a''z'<< '\n';
    std::cout << "min(3.14,2.72)==" << std::min(3.142.72<< '\n';
    return 0;
}
cs



7. min_element / max_element

구간 [begin, end)에서 최소/최대값의 이터레이터를 반환한다.


참조: http://www.cplusplus.com/reference/algorithm/

참고문헌: 뇌를 자극하는 C++ STL

'컴퓨터공학 > STL' 카테고리의 다른 글

[STL] C++ STL algorithm3  (0) 2018.07.30
[STL] C++ STL algorithm2  (0) 2018.07.30
[STL] C++ STL multimap  (0) 2018.07.22
[STL] C++ STL map  (0) 2018.07.22
[STL] C++ STL multiset  (0) 2018.07.22

입력받는 숫자에대해서, 증가하고 있는지 감소하고 있는지 카운트를 해준다.

감소하다가 다시 증가하는 상태가 되면

증가 개수 * 감소 개수 만큼의 조합이 나오게 되므로, 이 값을 더해준다.

1 3 5 4 1 의 경우 증가 카운트 =2, 감소 카운트 = 2로 1 3 5 4, 1 3 5 4 1, 3 5 4, 3 5 4 1 총 4가지의 경우가 있다.



0번째 부터 n번째 까지 필요한 사람의 수를 계산해주며

현재 몇명 박수 치고 있는지도 같이 계산해주어 

답을 구한다.



원래 기존에 사용하던 마우스는 맥스틸 TRON G10이었다.


언제 샀는지 기억은 안나지만 대략 3년정도 쓴것 같다.


이 마우스가 이제 왼쪽 클릭 버튼이 잘 안눌릴때가 있어서 바꿔야했다.


먼지는 한 2주 그냥 책상위에 놔뒀더니 자연스레 쌓였다



그래서 예전에 MSI엣서 공짜로 받은 DS B1으로 바꿨다.

전에도 연구실에서 쓴 적있었는데 별로 좋다고 느낀 마우스는 아녔다.

근데 사용하고 2주도 안돼서 가운데 휠이 잘 안먹힌다.

난 문서나 코드 볼일이 많아서 휠로 왔다갔다 해야하는데, 이게 제대로 페이지 이동이 안되니 엄청 불편했다 ㅡㅡ 

그래서 그냥 마우스 하나 사기로했다.



그래서 마우스 찾아보다가, 옛날 서든어택할 때 로지텍 G1 많이 썼었는데, 로지텍이 생각나서 이번엔 로지텍으로 바꿨다.

마우스야 어느정도 소모품이니까, 적당한 가성비 모델로 로지텍 G102가 있길래 이걸로 샀다.


가성비로 믿고 쓰는 로지텍이니 이건 괜찮겠지.?



다음엔 키보드 바꾸고 싶다 ㅋㅋ 2015년에 10만원 주고 산 제닉스꺼 청축 쓰고 있는데

일단 너무 시끄럽고

3이랑 T 버튼이 연속으로 눌릴때가 있다... 여유만 있다면 레오폴드 같은거 사고싶은데 빨리 그런날이 오길

'기타' 카테고리의 다른 글

레오폴드 FC900R PD 구매 후기  (0) 2018.08.07
대전 채용신체검사 후기  (0) 2018.07.26

채용신체검사서가 필요해서 구글링을 통해 대전에서 어디서 발급받을 수 있는지 알아봤다.


일부 동네 병원에서도 되는 것 같은데, 전화해서 알아보고 가는것이 좋은 것 같다.


나같은 경우는 한국건강관리협회로 갔다. 어차피 10분이면 갈 수 있는 곳이라...


위치는 롯데 백화점 맞은편에 있으며, 주차장도 있다.




1층에 들어가면 가운데에 안내가 있다.

사람이 엄청 많아서 예약하고 왔어야 했나 고민했는데, 공복 상태면 당일 검사 받을 수 있다.


안내엣서 일반 채용신체검사인지 공무원 채용신체검사인지 물어본다.

나는 일반 채용신체검사를 받았다.


기본 인적사항 작성하고, 신분증, 사진 1장이 있으면 된다.



인적사항을 작성하면 번호표를 뽑아주고 대기한다.

번호가 나오면, 언제까지 필요한지 물어봤다. 나는 다음주까지 필요하다고 했는데, 내일 8시 ~4시 사이에 와서 찾아가라고 한다.

그리고 문진실에서 잠깐 설명 듣고, 수납으로 가서 3만원 결제하면 된다.



결제가 끝나면 2층으로 가라고 안내해 준다..


가야하는 곳마다 안내해주시는 분이 바로바로 있기 때문에 큰 문제없이 찾아 다닐 수 있다.

2층 탈의실에서 옷을 갈아입고 나면 바로 옆에 치과 검진을 받는다. 

나는 아래치아에 치석이 조금 있다고 했는데, 나중에 스케일링 받아야겠다.

원하면 바로 스케일링도 가능한 것 같았다.


치과 검진이 끝나면 3층으로 이동해서 흉부 X-레이를 찍는다.


다음은 4층으로 이동해서 종이컵에 소변검사를 하고, (이때부터는 물 마셔도 된다고 말해줬다)


색약/혈압 검사했는데 정상 같았다.


키는 지난달 보건소에서 측정한 것보다 0.2 줄었다...ㅠ 0.2도 소중한데 


시력은 0.8 나왔다. 지금 쓰고있는 안경이 2~3년 됐는데 이제 바꾸러 가야할때가 된 것 같다.


청력은 이상 없었고


혈액 검사도 금방 끝났다.



치과-흉부 X-ray-소변검사-색약/혈압-가슴둘레/키/몸무게-시력-청력-혈액 순으로 검사를 받았고 대략 40분 정도 걸렸다.



검사 결과에 이상 없었으면 좋겠다...ㅋㅋ

'기타' 카테고리의 다른 글

레오폴드 FC900R PD 구매 후기  (0) 2018.08.07
마우스 바꿨다  (0) 2018.07.26

C++ multimap


multimap을 사용하기 위해서는 <map>을 인클루드 해야한다.


map에서 중복된 key가 가능하다는 차이점 외에는 다 같다.  라고 책에는 나와있는데 multimap은 중복된 key를 허용하기 때문에, 앞서 map과는 다르게 [] 사용시 multimap에서는 오류가 발생한다. 이 차이점 외에는 다 같은것이 맞는 것 같다.


생성자 사용 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <map>
#include <functional>
 
int main()
{
    std::multimap<charint> first;
 
    first.insert(std::pair<charint>('a'10));
    first.insert(std::pair<charint>('b'30));
    first.insert(std::pair<charint>('c'50));
    first.insert(std::pair<charint>('d'70));
 
    std::multimap<charint> second(first.begin(), first.end());
 
    std::multimap<charint> third(second);
 
    std::multimap<charintstd::greater<int> > fourth = { { 'a'10 },{ 'b'30 },{ 'c'50 },{ 'd'70 } };
    
    std::cout << "first : ";
    for (auto it = first.begin(); it != first.end(); it++)
        std::cout << (*it).first << ' ' << (*it).second << ' ';
    std::cout << '\n';
 
    std::cout << "second : ";
    for (auto it = second.begin(); it != second.end(); it++)
        std::cout << (*it).first << ' ' << (*it).second << ' ';
    std::cout << '\n';
 
    std::cout << "third : ";
    for (auto it = third.begin(); it != third.end(); it++)
        std::cout << (*it).first << ' ' << (*it).second << ' ';
    std::cout << '\n';
 
    std::cout << "fourth : ";
    for (auto it = fourth.begin(); it != fourth.end(); it++)
        std::cout << (*it).first << ' ' << (*it).second << ' ';
    std::cout << '\n';
 
    return 0;
}
 
cs


실행 결과


멤버 함수 사용 예제

insert()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <map>
 
int main ()
{
  std::multimap<char,int> mymultimap;
  std::multimap<char,int>::iterator it;
 
  // first insert function version (single parameter):
  mymultimap.insert ( std::pair<char,int>('a',100) );
  mymultimap.insert ( std::pair<char,int>('z',150) );
  it=mymultimap.insert ( std::pair<char,int>('b',75) );
 
  // second insert function version (with hint position):
  mymultimap.insert (it, std::pair<char,int>('c',300));  // max efficiency inserting
  mymultimap.insert (it, std::pair<char,int>('z',400));  // no max efficiency inserting
 
  // third insert function version (range insertion):
  std::multimap<char,int> anothermultimap;
  anothermultimap.insert(mymultimap.begin(),mymultimap.find('c'));
 
  // showing contents:
  std::cout << "mymultimap contains:\n";
  for (it=mymultimap.begin(); it!=mymultimap.end(); ++it)
    std::cout << (*it).first << " => " << (*it).second << '\n';
 
  std::cout << "anothermultimap contains:\n";
  for (it=anothermultimap.begin(); it!=anothermultimap.end(); ++it)
    std::cout << (*it).first << " => " << (*it).second << '\n';
 
  return 0;
}
cs


erase()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <map>
 
int main ()
{
  std::multimap<char,int> mymultimap;
 
  // insert some values:
  mymultimap.insert(std::pair<char,int>('a',10));
  mymultimap.insert(std::pair<char,int>('b',20));
  mymultimap.insert(std::pair<char,int>('b',30));
  mymultimap.insert(std::pair<char,int>('c',40));
  mymultimap.insert(std::pair<char,int>('d',50));
  mymultimap.insert(std::pair<char,int>('d',60));
  mymultimap.insert(std::pair<char,int>('e',70));
  mymultimap.insert(std::pair<char,int>('f',80));
 
  std::multimap<char,int>::iterator it = mymultimap.find('b');
 
  mymultimap.erase (it);                     // erasing by iterator (1 element)
 
  mymultimap.erase ('d');                    // erasing by key (2 elements)
 
  it=mymultimap.find ('e');
  mymultimap.erase ( it, mymultimap.end() ); // erasing by range
 
  // show content:
  for (it=mymultimap.begin(); it!=mymultimap.end(); ++it)
    std::cout << (*it).first << " => " << (*it).second << '\n';
 
  return 0;
}
cs


count()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <map>
 
int main ()
{
  std::multimap<char,int> mymm;
 
  mymm.insert(std::make_pair('x',50));
  mymm.insert(std::make_pair('y',100));
  mymm.insert(std::make_pair('y',150));
  mymm.insert(std::make_pair('y',200));
  mymm.insert(std::make_pair('z',250));
  mymm.insert(std::make_pair('z',300));
 
  for (char c='x'; c<='z'; c++)
  {
    std::cout << "There are " << mymm.count(c) << " elements with key " << c << ":";
    std::multimap<char,int>::iterator it;
    for (it=mymm.equal_range(c).first; it!=mymm.equal_range(c).second; ++it)
      std::cout << ' ' << (*it).second;
    std::cout << '\n';
  }
 
  return 0;
}
cs



참조: http://www.cplusplus.com/reference/map/multimap/

참고문헌: 뇌를 자극하는 C++ STL

'컴퓨터공학 > STL' 카테고리의 다른 글

[STL] C++ STL algorithm2  (0) 2018.07.30
[STL] C++ STL algorithm1  (0) 2018.07.30
[STL] C++ STL map  (0) 2018.07.22
[STL] C++ STL multiset  (0) 2018.07.22
[STL] C++ STL set  (0) 2018.07.22

C++ map


map을 사용하기 위해서는 <map 헤더를 인클루드 해야한다.


key와 value를 쌍으로 저장한다.


set과 마찬가지로 key를 중복으로 저장할 수 없으며, 중복된 key를 이용하려면 multimap을 이용하면 된다.


map은 []연산자를 이용하여 key에 접근할 수 있다.


map은 pair객체로 원소를 저장하기 때문에, 첫번째 key는 first로 두번째 value는 second로 접근할 수 있다.


생성자 사용 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <map>
#include <functional>
 
int main()
{
    std::map<charint> first;
 
    first['a'= 10;
    first['b'= 30;
    first['c'= 50;
    first['d'= 70;
 
    std::map<charint> second(first.begin(), first.end());
 
    std::map<charint> third(second);
 
    std::map<charintstd::greater<int> > fourth = { {'a'10}, {'b'30}, {'c'50}, {'d'70} }; 
 
    std::cout << "first : ";
    for (auto it = first.begin(); it != first.end(); it++)
        std::cout << (*it).first << ' ' << (*it).second << ' ';
    std::cout << '\n';
 
    std::cout << "second : ";
    for (auto it = second.begin(); it != second.end(); it++)
        std::cout << (*it).first << ' ' << (*it).second << ' ';
    std::cout << '\n';
 
    std::cout << "third : ";
    for (auto it = third.begin(); it != third.end(); it++)
        std::cout << (*it).first << ' ' << (*it).second << ' ';
    std::cout << '\n';
 
    std::cout << "fourth : ";
    for (auto it = fourth.begin(); it != fourth.end(); it++)
        std::cout << (*it).first << ' ' << (*it).second << ' ';
    std::cout << '\n';
 
    return 0;
}
cs


실행 결과


멤버함수 사용 예제

insert()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <map>
 
int main()
{
    std::map<charint> mymap;
 
    // first insert function version (single parameter):
    mymap.insert(std::pair<charint>('a'100));
    mymap.insert(std::pair<charint>('z'200));
 
    std::pair<std::map<charint>::iteratorbool> ret;
    ret = mymap.insert(std::pair<charint>('z'500));
    if (ret.second == false) {
        std::cout << "element 'z' already existed";
        std::cout << " with a value of " << ret.first->second << '\n';
    }
 
    // second insert function version (with hint position):
    std::map<charint>::iterator it = mymap.begin();
    mymap.insert(it, std::pair<charint>('b'300));  // max efficiency inserting
    mymap.insert(it, std::pair<charint>('c'400));  // no max efficiency inserting
 
                                                       // third insert function version (range insertion):
    std::map<charint> anothermap;
    anothermap.insert(mymap.begin(), mymap.find('c'));
 
    // showing contents:
    std::cout << "mymap contains:\n";
    for (it = mymap.begin(); it != mymap.end(); ++it)
        std::cout << it->first << " => " << it->second << '\n';
 
    std::cout << "anothermap contains:\n";
    for (it = anothermap.begin(); it != anothermap.end(); ++it)
        std::cout << it->first << " => " << it->second << '\n';
 
    return 0;
}
cs


find(), erase()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <map>
 
int main ()
{
  std::map<char,int> mymap;
  std::map<char,int>::iterator it;
 
  // insert some values:
  mymap['a']=10;
  mymap['b']=20;
  mymap['c']=30;
  mymap['d']=40;
  mymap['e']=50;
  mymap['f']=60;
 
  it=mymap.find('b');
  mymap.erase (it);                   // erasing by iterator
 
  mymap.erase ('c');                  // erasing by key
 
  it=mymap.find ('e');
  mymap.erase ( it, mymap.end() );    // erasing by range
 
  // show content:
  for (it=mymap.begin(); it!=mymap.end(); ++it)
    std::cout << it->first << " => " << it->second << '\n';
 
  return 0;
}
cs


count()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <map>
 
int main ()
{
  std::map<char,int> mymap;
  char c;
 
  mymap ['a']=101;
  mymap ['c']=202;
  mymap ['f']=303;
 
  for (c='a'; c<'h'; c++)
  {
    std::cout << c;
    if (mymap.count(c)>0)
      std::cout << " is an element of mymap.\n";
    else 
      std::cout << " is not an element of mymap.\n";
  }
 
  return 0;
}
cs


참조: http://www.cplusplus.com/reference/map/map/

참고문헌: 뇌를 자극하는 C++ STL

'컴퓨터공학 > STL' 카테고리의 다른 글

[STL] C++ STL algorithm1  (0) 2018.07.30
[STL] C++ STL multimap  (0) 2018.07.22
[STL] C++ STL multiset  (0) 2018.07.22
[STL] C++ STL set  (0) 2018.07.22
[STL] C++ STL string to int/float/double/long long  (0) 2018.07.19

C++ multiset


multiset을 사용하기 위해서는 <set> 헤더를 인클루드 해야한다.


중복된 데이터를 사용할 수 있는 것 외에는 set과 모두 같다.




 생성자

 

 set s

 빈 컨테이너 셋 s 생성

 set s(pred)

 s는 빈 컨테이너 이며, 정렬 기준은 pred 조건자를 사용

 set s(s2)

 셋 s는 셋 s2의 복사본

 set s(b, e)

 셋 s는 반복자 구간 [b, e)로 초기화된 원소를 가짐

 set s(b, e, pred)

 셋 s는 반복자 구간 [b, e)로 초기화된 원소를 가지며, 정렬 기준은 pred 조건자를 사용


생성자 사용 예제



#include <iostream>
#include <set>
#include <functional>
int main()
{
    std::multiset<int> first;                           // empty set of ints
 
    int myints[] = { 10203040502030405060 };
    std::multiset<int> second(myints, myints + 10);        // range
 
    std::multiset<int> third(second);                  // a copy of second
 
    std::multiset<int> fourth(second.begin(), second.end());  // iterator ctor.
 
    std::multiset<intstd::greater<int> > fifth = { 10203040502030405060 };
 
    std::cout << "first : ";
    for (auto it = first.begin(); it != first.end(); it++)
        std::cout << *it << ' ';
    std::cout << '\n';
 
    std::cout << "second : ";
    for (auto it = second.begin(); it != second.end(); it++)
        std::cout << *it << ' ';
    std::cout << '\n';
 
    std::cout << "third : ";
    for (auto it = third.begin(); it != third.end(); it++)
        std::cout << *it << ' ';
    std::cout << '\n';
 
    std::cout << "fourth : ";
    for (auto it = fourth.begin(); it != fourth.end(); it++)
        std::cout << *it << ' ';
    std::cout << '\n';
 
    std::cout << "fifth : ";
    for (auto it = fifth.begin(); it != fifth.end(); it++)
        std::cout << *it << ' ';
    std::cout << '\n';
 
    return 0;
}
cs


실행 결과




주요 멤버 함수

insert() 

 셋에 데이터 삽입

 erase()

 셋에서 원소 제거

 find()

 셋에서 원소의 위치 검색

 count()

 셋에서 원소의 개수 검색

 clear()

 셋의 모든 원소 제거


사용예제

insert()


#include <iostream>
#include <set>
 
int main()
{
    std::multiset<int> mymultiset;
    std::multiset<int>::iterator it;
 
    // set some initial values:
    for (int i = 1; i <= 5; i++) mymultiset.insert(i * 10);  // 10 20 30 40 50
 
    it = mymultiset.insert(25);
 
    it = mymultiset.insert(it, 27);    // max efficiency inserting
    it = mymultiset.insert(it, 29);    // max efficiency inserting
    it = mymultiset.insert(it, 24);    // no max efficiency inserting (24<29)
 
    int myints[] = { 5,10,15 };
    mymultiset.insert(myints, myints + 3);
 
    std::cout << "mymultiset contains:";
    for (it = mymultiset.begin(); it != mymultiset.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
 
    return 0;
}
cs



erase(), find()


#include <iostream>
#include <set>
 
int main ()
{
  std::multiset<int> mymultiset;
  std::multiset<int>::iterator it;
 
  // insert some values:
  mymultiset.insert (40);                            // 40
  for (int i=1; i<7; i++) mymultiset.insert(i*10);   // 10 20 30 40 40 50 60
 
  it=mymultiset.begin();
  it++;                                              //    ^
 
  mymultiset.erase (it);                             // 10 30 40 40 50 60
 
  mymultiset.erase (40);                             // 10 30 50 60
 
  it=mymultiset.find (50);
  mymultiset.erase ( it, mymultiset.end() );         // 10 30
 
  std::cout << "mymultiset contains:";
  for (it=mymultiset.begin(); it!=mymultiset.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';
 
  return 0;
}
cs


count()


#include <iostream>
#include <set>
 
int main ()
{
  int myints[]={10,73,12,22,73,73,12};
  std::multiset<int> mymultiset (myints,myints+7);
 
  std::cout << "73 appears " << mymultiset.count(73<< " times in mymultiset.\n";
 
  return 0;
}
cs



참조: http://www.cplusplus.com/reference/set/multiset/

참고문헌: 뇌를 자극하는 C++ STL

'컴퓨터공학 > STL' 카테고리의 다른 글

[STL] C++ STL multimap  (0) 2018.07.22
[STL] C++ STL map  (0) 2018.07.22
[STL] C++ STL set  (0) 2018.07.22
[STL] C++ STL string to int/float/double/long long  (0) 2018.07.19
[STL] C++ STL list  (0) 2018.07.19

C++ set


set을 사용하기 위해서는 <set> 헤더를 인클루드 해야한다.


key라 불리는 원소의 집합. key이므로 중복된 값을 가지지 않는다. 중복된 값이 필요하다면 multiset을 이용하면 된다.


set은 균형 이진트리로 구현되어있다.


insert()함수로 데이터를 추가할 수 있으며, 삽입된 데이터는 자동으로 정렬된다. (기본 오름차순)



 생성자

 

 set s

 빈 컨테이너 셋 s 생성

 set s(pred)

 s는 빈 컨테이너 이며, 정렬 기준은 pred 조건자를 사용

 set s(s2)

 셋 s는 셋 s2의 복사본

 set s(b, e)

 셋 s는 반복자 구간 [b, e)로 초기화된 원소를 가짐

 set s(b, e, pred)

 셋 s는 반복자 구간 [b, e)로 초기화된 원소를 가지며, 정렬 기준은 pred 조건자를 사용


생성자 사용 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <set>
#include <functional>
int main()
{
    std::set<int> first;                           // empty set of ints
 
    int myints[] = { 10,20,30,40,50 };
    std::set<int> second(myints, myints + 5);        // range
 
    std::set<int> third(second);                  // a copy of second
 
    std::set<int> fourth(second.begin(), second.end());  // iterator ctor.
 
    std::set<intstd::greater<int> > fifth = { 1020304050 };
 
    std::cout << "first : ";
    for (auto it = first.begin(); it != first.end(); it++)
        std::cout << *it << ' ';
    std::cout << '\n';
 
    std::cout << "second : ";
    for (auto it = second.begin(); it != second.end(); it++)
        std::cout << *it << ' ';
    std::cout << '\n';
 
    std::cout << "third : ";
    for (auto it = third.begin(); it != third.end(); it++)
        std::cout << *it << ' ';
    std::cout << '\n';
 
    std::cout << "fourth : ";
    for (auto it = fourth.begin(); it != fourth.end(); it++)
        std::cout << *it << ' ';
    std::cout << '\n';
 
    std::cout << "fifth : ";
    for (auto it = fifth.begin(); it != fifth.end(); it++)
        std::cout << *it << ' ';
    std::cout << '\n';
 
    return 0;
}
 
cs


실행 결과



주요 멤버 함수

insert() 

 셋에 데이터 삽입

 erase()

 셋에서 원소 제거

 find()

 셋에서 원소의 위치 검색

 count()

 셋에서 원소의 개수 검색

 clear()

 셋의 모든 원소 제거


사용예제

insert()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <set>
 
int main()
{
    std::set<int> myset;
    std::set<int>::iterator it;
    std::pair<std::set<int>::iteratorbool> ret;
 
    // set some initial values:
    for (int i = 1; i <= 5++i) myset.insert(i * 10);    // set: 10 20 30 40 50
 
    ret = myset.insert(20);               // no new element inserted
 
    if (ret.second == false) it = ret.first;  // "it" now points to element 20
 
    myset.insert(it, 25);                 // max efficiency inserting
    myset.insert(it, 24);                 // max efficiency inserting
    myset.insert(it, 26);                 // no max efficiency inserting
 
    int myints[] = { 5,10,15 };              // 10 already in set, not inserted
    myset.insert(myints, myints + 3);
 
    std::cout << "myset contains:";
    for (it = myset.begin(); it != myset.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
 
    return 0;
}
cs



erase(), find()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <set>
 
int main()
{
    std::set<int> myset;
    std::set<int>::iterator it;
 
    // set some initial values:
    for (int i = 1; i <= 5; i++) myset.insert(i * 10);    // set: 10 20 30 40 50
 
    //20, 40의 위치를 찾은 후 제거
    it = myset.find(20);
    myset.erase(it);
    myset.erase(myset.find(40));
 
    std::cout << "myset contains:";
    for (it = myset.begin(); it != myset.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
 
    return 0;
}
cs


count()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <set>
 
int main()
{
    std::set<int> myset;
 
    // set some initial values:
    for (int i = 1; i<5++i) myset.insert(i * 3);    // set: 3 6 9 12
 
    for (int i = 0; i<10++i)
    {
        std::cout << i;
        if (myset.count(i) != 0)
            std::cout << " is an element of myset.\n";
        else
            std::cout << " is not an element of myset.\n";
    }
 
    return 0;
}
cs



참조: http://www.cplusplus.com/reference/set/set/

참고문헌: 뇌를 자극하는 C++ STL

'컴퓨터공학 > STL' 카테고리의 다른 글

[STL] C++ STL map  (0) 2018.07.22
[STL] C++ STL multiset  (0) 2018.07.22
[STL] C++ STL string to int/float/double/long long  (0) 2018.07.19
[STL] C++ STL list  (0) 2018.07.19
[STL] C++ STL deque  (0) 2018.07.19

map을 따라 0이 아닌 숫자가 나오면 행렬이 있으므로, 행렬의 좌표를 계산한다.


그다음 벡터에 행렬의 넓이, 가로, 세로를 저장하고


크기 순으로 출력을 해야하기 때문에 소팅을 한 후, 작은 값부터 출력했다.



+ Recent posts