헤더파일

알고리즘 함수 본문

C++

알고리즘 함수

헤더파일 2018. 5. 31. 12:22

---------------------------------

강의기록시간 - Thu May 31 11:31:56 2018

---------------------------------


//-------------------------------------------------------------------

//2018.1학기 STL   5/28 월요일   월56목23 (15주 2)

//7장 반복자(iterator) - Category

//input iterator / output iterator - 반드시 입출력 객체와 연결되어 있어야한다.

//forward iterator - 원소를 전진하는 방향으로만 순회

//bidirectional iterator - 양방향으로 순회

//random iterator - 임의의 위치에 access,[] 연산자게 제공됨


//반복자의 행동

//* : dereferencing(역참조)

//== : comparison(비교)

//= : assignment(배정)

//반복자의 종류를 판단하고 이용하는 프로그램

//사용자가 반복자를 정의하는 방법


//STL 표준컨테이너와 반복자를 만들어 보자

//   myString 클래스를 만들어 

//-------------------------------------------------------------------


#include<iostream>

#include<algorithm>

#include<string>

#include<vector>

#include<iterator>

#include"Model.h"

#include"save.h"

using namespace std;


int main()

{

   int a[]{ 1,3,5,7,9 };


   bool r = all_of(begin(a), end(a), [](int n) {

      return n&1;

   });

   if (r == true) {

      cout << "모든 원소가 홀수입니다" << endl;

   }

   save();

}


---------------------------------

강의기록시간 - Thu May 31 11:51:45 2018

---------------------------------


//-------------------------------------------------------------------

//2018.1학기 STL   5/28 월요일   월56목23 (15주 2)

//7장 반복자(iterator) - Category

//input iterator / output iterator - 반드시 입출력 객체와 연결되어 있어야한다.

//forward iterator - 원소를 전진하는 방향으로만 순회

//bidirectional iterator - 양방향으로 순회

//random iterator - 임의의 위치에 access,[] 연산자게 제공됨


//반복자의 행동

//* : dereferencing(역참조)

//== : comparison(비교)

//= : assignment(배정)

//반복자의 종류를 판단하고 이용하는 프로그램

//사용자가 반복자를 정의하는 방법


//STL 표준컨테이너와 반복자를 만들어 보자

//   myString 클래스를 만들어 

//-------------------------------------------------------------------


#include<iostream>

#include<algorithm>

#include<string>

#include<vector>

#include<iterator>

#include"Model.h"

#include"save.h"

using namespace std;

//all_of -  컨테이너의 모든 원소가 조건에 맞는가?

template <typename Iter,class unpre>

bool my_all_of(Iter b, Iter e, unpre p){

   while (b != e) {

      if (!p(*b))

         return false;

      ++b;

   }

   return true;

}

//count - 값이 같은원소의 갯수가 몇개이니?

//count_if - 조건에 맞는 원소의 갯수

int main()

{

   Model a[]{ 1,3,5,7,9 };


   bool r = my_all_of(begin(a), end(a), [](const Model& n) {

      return n.getSize()<10;

   });

   if (r == true) {

      cout << "모든 원소의 사이즈가 10보다 작다." << endl;

   }

   save();

}


---------------------------------

강의기록시간 - Thu May 31 11:56:29 2018

---------------------------------


//-------------------------------------------------------------------

//2018.1학기 STL   5/28 월요일   월56목23 (15주 2)

//7장 반복자(iterator) - Category

//input iterator / output iterator - 반드시 입출력 객체와 연결되어 있어야한다.

//forward iterator - 원소를 전진하는 방향으로만 순회

//bidirectional iterator - 양방향으로 순회

//random iterator - 임의의 위치에 access,[] 연산자게 제공됨


//반복자의 행동

//* : dereferencing(역참조)

//== : comparison(비교)

//= : assignment(배정)

//반복자의 종류를 판단하고 이용하는 프로그램

//사용자가 반복자를 정의하는 방법


//STL 표준컨테이너와 반복자를 만들어 보자

//   myString 클래스를 만들어 

//-------------------------------------------------------------------


#include<iostream>

#include<algorithm>

#include<string>

#include<vector>

#include<iterator>

#include"Model.h"

#include"save.h"

using namespace std;

//all_of -  컨테이너의 모든 원소가 조건에 맞는가?

template <typename Iter,class unpre>

bool my_all_of(Iter b, Iter e, unpre p){

   while (b != e) {

      if (!p(*b))

         return false;

      ++b;

   }

   return true;

}

//count - 값이 같은원소의 갯수가 몇개이니?

//count_if - 조건에 맞는 원소의 갯수

int main()

{

   int a[]{ 1,3,5,7,9,3,4,2 };

   //홀수가 몆개이니?

   int num = count_if(begin(a), end(a), [](int n) {

      return n & 1;

   });

   cout << num;

   save();

}


---------------------------------

강의기록시간 - Thu May 31 11:57:21 2018

---------------------------------


//-------------------------------------------------------------------

//2018.1학기 STL   5/28 월요일   월56목23 (15주 2)

//7장 반복자(iterator) - Category

//input iterator / output iterator - 반드시 입출력 객체와 연결되어 있어야한다.

//forward iterator - 원소를 전진하는 방향으로만 순회

//bidirectional iterator - 양방향으로 순회

//random iterator - 임의의 위치에 access,[] 연산자게 제공됨


//반복자의 행동

//* : dereferencing(역참조)

//== : comparison(비교)

//= : assignment(배정)

//반복자의 종류를 판단하고 이용하는 프로그램

//사용자가 반복자를 정의하는 방법


//STL 표준컨테이너와 반복자를 만들어 보자

//   myString 클래스를 만들어 

//-------------------------------------------------------------------


#include<iostream>

#include<algorithm>

#include<string>

#include<vector>

#include<iterator>

#include"Model.h"

#include"save.h"

using namespace std;

//all_of -  컨테이너의 모든 원소가 조건에 맞는가?

template <typename Iter,class unpre>

bool my_all_of(Iter b, Iter e, unpre p){

   while (b != e) {

      if (!p(*b))

         return false;

      ++b;

   }

   return true;

}

//count - 값이 같은원소의 갯수가 몇개이니?

//count_if - 조건에 맞는 원소의 갯수

int main()

{

   Model a[]{ 1,3,5,7,9,3,4,2 };

   //홀수가 몆개이니?

   int num = count(begin(a), end(a), Model(3));

   cout << num;

   save();

}


---------------------------------

강의기록시간 - Thu May 31 12:08:24 2018

---------------------------------


//-------------------------------------------------------------------

//2018.1학기 STL   5/28 월요일   월56목23 (15주 2)

//7장 반복자(iterator) - Category

//input iterator / output iterator - 반드시 입출력 객체와 연결되어 있어야한다.

//forward iterator - 원소를 전진하는 방향으로만 순회

//bidirectional iterator - 양방향으로 순회

//random iterator - 임의의 위치에 access,[] 연산자게 제공됨


//반복자의 행동

//* : dereferencing(역참조)

//== : comparison(비교)

//= : assignment(배정)

//반복자의 종류를 판단하고 이용하는 프로그램

//사용자가 반복자를 정의하는 방법


//STL 표준컨테이너와 반복자를 만들어 보자

//   myString 클래스를 만들어 

//-------------------------------------------------------------------


#include<iostream>

#include<algorithm>

#include<string>

#include<vector>

#include<iterator>

#include"Model.h"

#include"save.h"

using namespace std;

//all_of -  컨테이너의 모든 원소가 조건에 맞는가?

template <typename Iter,class unpre>

bool my_all_of(Iter b, Iter e, unpre p){

   while (b != e) {

      if (!p(*b))

         return false;

      ++b;

   }

   return true;

}

//search

int main()

{

   int a[]{ 1,3,5,7,9,3,3,3,6,5,7,9,3,1,2,9,7,8,3 };

   int b[]{ 7,9,3 };

   //a에서 "3,3,3"이라는 부분을 찾고싶다

   auto p = search_n(begin(a), end(a),2,3);

   if (p != end(a)) {

      cout << "찾았다" << endl;

      cout << *(p-1) << endl;

   }

   else

      cout << "없음" << endl;

   save();

}




COPY 함수


직접 만들면 이런 식의 형태가 됩니다.

처음과 끝의 반복자를 받고 


template<class InIt, class OutIt>

void mycopy(InIt b, InIt e, OutIt o)

{

for (; b != e; ++b,++o)

{

*o = *b;

}

}


int a[]{ 1,3,5,7,9 ,3,3,3};

vector<int> v;

v.resize(_countof(a));

mycopy(begin(a), end(a), v.begin());


stl copy 함수를 쓰면 이렇게 씁니다.


copy(begin(a), end(a), v.begin());



COPY_IF 함수


범위와 목적지를 정해주고 함수객체로 판단합니다.


ifstream in("Lecture.cpp");

vector<char> answer;

copy_if(istream_iterator<char>(in), istream_iterator<char>(),ostream_iterator<char>              (cout) ,[](char param)

{

return isalpha(param);

});



ROTATE 함수


string s("영원히 옆으로 가는 전광판");

while (true)

{

system("cls");

cout << "\t\t\t" << s << endl;

rotate(s.begin(), s.begin()+1 , s.end());

this_thread::sleep_for(33ms);

}






PARTITION 함수


해당 조건으로 정리를 하고 마지막 반복자를 반환합니다. 대신 정렬된 형태는 아닙니다.


int a[100];

for (int i = 0; i < 100; i++)

{

a[i] = i + 1;

}


auto p = partition(begin(a),end(a), [](int i)

{

return i&1;

});




정렬된 버전은 stable_partition 입니다.


int a[100];

for (int i = 0; i < 100; i++)

{

a[i] = i + 1;

}


auto p = stable_partition(begin(a),end(a), [](int i)

{

return i&1;

});




iota는 값을 하나씩 증가 시키며 컨테이너에 값을 넣어줍니다.

random_shuffle은 값을 랜덤으로 섞어줍니다.


iota(begin(a), end(a), 1);

random_shuffle(begin(a), end(a));


partition이나 sort함수는 비싼 연산이기 때문에 이미 파티션이 되거나 정렬됬는지 물어보는 함수가 있습니다. 

is_partitioned() , is_sorted() 입니다.


알고리즘의 종류

1. 원소를 수정하지 않는 알고리즘 - Non-modifying

2. 원소를 수정하는 알고리즘 - Mutating

3. 정렬 관련 알고리즘

partition - 기준에 맞는 것과 그렇지 않은 것을 분리한다. 귤을 썩은 것과 정상인걸 분류

sort - 기준에 따라 전체원소를 정렬. 귤을 1등부터 꼴찌까지 분류.

partial_sort - 앞에서부터 몇개만 기준에 따라 정렬. 

stable_sort - 기준의 순서를 유지하면서 새 기준에 따라 정렬

nth_element - n번째까지와 나머지로 분리. 앞에서부터 10명까지 통과.


SORT함수


정렬할 값을 준비합니다.


  int a[25];

iota(begin(a), end(a), 1);

random_shuffle(begin(a), end(a));


일반적인 정렬입니다. 해당 범위에서 해당 조건으로 정렬합니다.


sort(begin(a), end(a), less<int>());


1~n등까지만 정렬합니다. 가운데 넣는 게 범위입니다.


partial_sort(begin(a), begin(a)+10,end(a));


딴 순서는 상관 없고 n번째 등수만 n번째 위치에 있게 하는 정렬입니다.

nth_element(begin(a), begin(a)+10,end(a));


FIND 함수


auto p = find(v.begin(), v.end(), string{ "game" });

cout <<"몇번째에?"<< distance(v.begin(), p)+1 << endl;


컨테이너에서 game이라는 단어를 찾을 때이렇게 쓸 수 있지만 옳지 않는 답입니다.

정렬됬다면 이진 탐색으로 찾는 것이 빠릅니다. 


binary_search(v.begin(), v.end(), string{ "game" })



'C++' 카테고리의 다른 글

C++ 정리  (0) 2019.10.29
문자열 함수  (0) 2018.06.11
반복자  (0) 2018.05.21
Map을 이용한 파일입출력  (0) 2018.05.14
연관 컨테이너  (0) 2018.04.30
Comments