별의 공부 블로그 🧑🏻‍💻

🗒️ Programming/C++ (117)

728x90
  1. 2022.11.01 [C++] 벡터 내부의 중복된 문자 제거 방법

    벡터 내부의 중복된 문자 제거 방법 알고리즘 문제를 풀 때, 벡터 내부의 중복된 문자를 제거하고 싶을 때가 있다. 다음과 같이 간단하게 중복되는 문자를 공백(" ")으로 바꿔주고, 출력할 때 공백(" ")이 아닌 문자만 출력하도록 하는 방법을 사용할 수 있다. #include #include using namespace std; int N; string word; vector words; int main() { cin >> N; for (int i = 0; i > word; words.push_back(word); } // 벡터 내의 중복된 단어 제거 for (int i = 0; i < words.size(); i++) { for (int j = i + 1; j < word..

  2. 2022.07.09 [C++] 동적 할당(Dynamic Allocation) 방법 (malloc, calloc, new)

    C++ 에서의 동적 할당(Dynamic Allocation) 방법 동적 할당(Dynamic Allocation) 실행 시간 동안 사용할 메모리 공간을 할당하는 것 동적 메모리 할당을 이용하면 배열의 크기를 가변적으로 생성할 수 있다. 메모리 영역 중 힙(Heap) 영역에 저장된다. 사용자가 원할 때 메모리에 등록시키고, 원할 때 해제시킬 수 있다. 동적 할당한 메모리를 해제하지 않을 경우 메모리 누수가 발생한다. 프로그램을 종료해도 메모리에 계속해서 상주한다. 동적 할당은 C 방식과 C++ 방식으로 나뉜다. C 기반 동적 할당 C 기반 동적 할당 방법으로는 malloc(), calloc() 함수를 이용한 방법이 있다. 동적 할당을 해제할 때는 free() 함수를 사용한다. C++ 기반 동적 할당 C++ ..

  3. 2022.07.09 [C++] 입력 함수 : cin(), getline() (and cin.ignore())

    입력 함수 : cin(), getline() (and cin.ignore()) 들어가며 C++의 입력 함수인 cin()과 getline() 함수에 대해 알아보자. 그리고 입력 버퍼를 비우는데 사용되는 cin.ignore() 함수에 대해 간단히 알아보자. cin() 헤더에 정의되어 있다. 표준 입력 버퍼에서 공백 혹은 개행 문자(\n) 이전 까지의 값만을 받아들인다. >> 연산자를 사용하여 공백이 포함된 문자열을 입력 받을 경우, 공백 전의 문자만 입력된다는 단점이 존재한다. 공백이 포함된 문자열을 입력받으려면 getline() 함수를 사용해야 한다. #include int str; cin >> str; // "My Blog" 입력 cout > val; getline(cin, str); cout

  4. 2022.07.09 [C++] 범위 기반 for 문(Range-based for Statement)

    범위 기반 for 문(Range-based for Statement) 개념 더 간단하고 안전하게 배열 등의 모든 요소를 반복할 수 있다. 범위(Range)를 통해 실행되어야 하는 루프를 생성한다. C++11 부터 사용 가능 구문 attr(optional) for ( init-statement(optional)range-declaration : range-expression ) loop-statement 속성 설명 attr any number of attributes init-statement either (since C++20) ▶ an expression statement (which may be a null statement ";") ▶ a simple declaration, typically a d..

  5. 2022.07.07 [C++] 자료형(Data Type)

    C++의 자료형(Data Type) C++ 의 자료형에는 기본형, 문자형, 정수형, 실수형(부동 소수점형)이 있다. 기본형 void 문자형 (singed) char unsigned char wchar_t 정수형 bool (signed) short (int) unsigned short (int) (signed) int unsigned int (signed) long (int) unsigned long (int) __int8 __int16 __int32 __int64 실수형(부동 소수점형) float (long) double 정수 자료형의 크기 및 범위 (LLP64/IL32P64, Windows) 자료형 크기 범위 비고 char signed char 1 Byte 8 Bits -128 ~ 127 unsigne..

  6. 2022.07.07 [C++] 이스케이프 시퀀스(Escape Sequence)

    C++ 이스케이프 시퀀스(Escape Sequence) 이스케이프 시퀀스(Escape Sequence, 확장열)란? 컴퓨터와 주변 기기의 상태를 바꾸는 데에 쓰이는 일련의 문자열로, 제어 시퀀스(Control Sequence)라고도 한다. 일부 제어 시퀀스는 늘 같은 의미를 지니고 있는 특수 문자이다. 이스케이프 시퀀스는 이스케이프 문자를 이용하여 이를 따르는 문자들의 뜻을 바꿀 수 있는데, 여기서 문자들은 데이터가 아닌 실행 명령어로 해석할 수 있다. - Wikipedia 이스케이스 시퀀스의 종류 이스케이프 시퀀스 설명 \a 경고(Alert) \n 줄바꿈(New Line) \t 수평 탭(Horizontal Tab) \v 수직 탭(Vertical Tab) \b 백스페이스(Backspace) \f 폼 피드..

  7. 2021.10.31 [C++] 공백을 기준으로 문자열 나누기 (substr() 사용)

    [C++] 공백을 기준으로 문자열 나누기 (substr() 사용) substr() 함수를 사용하여 공백(스페이스)을 기준으로 문자열 나눌 수 있다. 또한 atoi() 함수를 사용하여 string형 숫자를 int형으로 바꿀 수 있다. #include #include using namespace std; int main() { string cmd, cmd1, cmd2; int input; getline(cin, cmd);// getline() 함수를 사용하여 공백을 포함한 문자열 입력 받기 cmd1 = cmd.substr(0, cmd.find(" "));// 공백의 앞에 있는 단어를 cmd1 변수에 저장 cmd2 = cmd.substr(cmd.find(" ") + 1, cmd.length());// 공백의 ..

  8. 2021.05.28 [C++] std::unordered_map 에서 [] 연산자

    std::unordered_map 에서 [] 연산자 키와 값의 쌍을 저장한 후, [] 연산자와 키를 이용하여 값을 받아올 수 있음. [] 연산자는 참조 를 반환하므로 이를 이용하여 저장된 값을 변경 할 수도 있음. 만약 해당 키가 없다면 해당 위치에 기본값을 추가하여 반환함. 예제 코드 #include #include void print(const std::unordered_map& container) { for (const auto& element : container) { std::cout

  9. 2021.01.29 main(int argc, char* argv[])

    1 2 3 4 5 6#include using namespace std; int main(int argc, char* argv[]) { } main 함수는 프로그램에서 최초로 실행이 된다.main 함수의 매개변수로는 int형의 argc, char* 형의 argv[]가 있다. main 함수의 매개변수에 대한 설명은 각각 다음과 같다. int argc : main 함수에 전달되는 데이터의 개수char* argv[] : main 함수에 전달되는 실제적인 데이터, char형 포인터 배열로 구성됨. argv[0]에는 프로그램의 절대 경로가, argv[1] 부터는 입력받은 문자가 대입됨. > example.cpp 1 2 3 4 5 6 7 8 9 10 11#include using namespace std; int ..

  10. 2021.01.12 비교/관계 연산자 오버로딩 예

    123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114#include #include #include // using namespace std; class String { char* _chars;public: String(const char* chars) : _chars(new char[strlen(chars) + 1]) { strcpy(_cha..

  11. 2020.12.28 프로그램 실행 시간 측정 방법 (clock())

    12345678910#include // clock() : ms 단위로 시간 측정 void main() { clock_t start = clock(); // algorithm clock_t end = clock(); std::cout

  12. 2020.12.26 단축 평가 논리 계산법(Short-Circuit Evaluation)

    *단축 평가 논리 계산법(Short-Circuit Evaluation) AND 혹은 OR의 연산에 있어서 결과가 확실하게 예측이 되었을 때 뒤에 나머지 연산을 실행하지 않고 답을 내버리는 것AND 연산의 경우false가 우선 나와버리면 AND 뒤에 나오는 연산은 생략OR 연산의 경우true가 우선 나와버리면 OR 뒤에 나오는 연산은 생략#include using namespace std; int main() { bool result; // AND result = printf("") && printf("ABC"); result = printf("1") && printf("ABC"); cout

  13. 2020.10.25 scanf() 입력 버퍼 비우는 방법

    *scanf() 입력 버퍼 비우는 방법 scanf()를 사용하다 보면, 입력을 정상적으로 받지 못할 경우가 생기게 된다.이러한 종류의 문제는 입력 버퍼(stdin Buffer)와 관련된 문제가 대부분이며, 이 문제를 해결하기 위해서는 입력 버퍼를 비워줘야 한다.입력 버퍼를 비우는 방법을 이 글에 총정리 해보았다. #pragma warning(disable: 4996) #include int main() { char ch; scanf("%c", &ch); printf("1, %c\n", ch); scanf("%c", &ch); printf("2, %c\n", ch); return 0; } a 1, a 2, ab 1, a 2, b 무슨 일이 일어났는지 확인해 보기 위하여 다음과 같이 코드를 수정해서 프로그램..

  14. 2019.05.06 Dynamic Memory (동적 메모리)

    Static & Dynamic Memory To be successful as a C++ programmer, it's essential to have a good understanding of how dynamic memory works. In a C++ program, memory is divided into two parts: The stack: All of your local variables take up memory from the stack. The heap: Unused program memory that can be used when the program runs to dynamically allocate the memory. Many times, you are not aware in a..

  15. 2019.05.06 Pointers (포인터)

    Pointers Every variable is a memory location, which has its address defined. That address can be accessed using the ampersand (&) operator (also called the address-of operator), which denotes an address in memory. For example:int score = 5; cout

  16. 2019.05.06 Naming Rules for Variables (변수 이름 생성 규칙)

    *Naming Rules for Variables (변수 이름 생성 규칙) The names of variables in the C++ language are referred to as identifiers. The best naming convention is to choose a variable name that will tell the reader of the program what the variable represents. Variables that describe the data stored at that particular memory location are called mnemonic variables. Rules for naming variables: (1) Variable names i..

  17. 2018.11.17 sort 함수 정렬 기준

    std::sortdefault (1)template void sort (RandomAccessIterator first, RandomAccessIterator last); custom (2)template void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);Sort elements in rangeSorts the elements in the range [first,last) into ascending order. The elements are compared using operator b.length(); // 내림차순 정렬 } int main(){ string ip[N]; int num; cin >> num; c..

  18. 2018.10.07 랜덤 함수/난수 생성 함수 (Random Function)

    123456789101112131415161718192021#include #include // rand()#include // time()using namespace std; int main() { int MAX, RANGE; cout MAX; cout RANGE; cout

  19. 2018.09.24 입력된 문자열에서 공백을 제거하여 출력하기

    공백 없애기 문제의 입력값은 각 언어의 표준입력(stdin) 함수를, 출력값은 표준출력(stdout) 함수를 사용해주세요.이 문제는 입력된 문자열에서 공백을 제거하여 출력하는 프로그램을 작성하는 것 입니다.예를 들어 "This is Kim !" 가 입력 되었다면 "ThisisKim!"가 출력되도록 하면 되는 것 입니다. 입력50자 이내의 문장출력입력에서 공백이 제거된 문장 ( 입출력 예시 참고 ) 입/출력 예시⋇ 입출력 형식을 잘 지켜주세요.␣ : 공백↵ : 줄바꿈−⇥ : 탭보기 입력 1I ␣am ␣Goorm ␣!Hello World !출력 1IamGoorm!HelloWorld! 보기 입력 2This ␣is ␣SpartaNice to meet you출력 2ThisisSpartaNicetomeetyou 입..

  20. 2017.11.26 Pair Vector

    *Pair Vector - 벡터 안에 두 쌍의 데이터를 넣는 방법.- 벡터 선언 : vector 벡터명- 벡터에 데이터 삽입 : 벡터명.push_back(std::make_pair(데이터1, 데이터2))- 코드 사용 예123456789101112131415161718#include #include #define N 500000using namespace std; int main(){ long long int n, a, b, area, ary[N]; vector vec; // 벡터 선언 scanf("%lld", &n); for (int i = 0; i

  21. 2017.11.17 [header][container] queue : priority_queue

    *[header][container] queue : priority_queue std::priority_queuetemplate class priority_queue;Priority queuePriority queues are a type of container adaptors, specifically designed such that its first element is always the greatest of the elements it contains, according to some strict weak ordering criterion. This context is similar to a heap, where elements can be inserted at any moment, and only..

  22. 2017.11.17 [header][container] queue : queue

    *[header][container] queue : queue std::queuetemplate class queue;FIFO queuequeues are a type of container adaptor, specifically designed to operate in a FIFO context (first-in first-out), where elements are inserted into one end of the container and extracted from the other. queues are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container ..

  23. 2017.11.15 string형 변수 길이 구하기

    *string형 변수 길이 구하기 - (string형 변수).length()를 길이를 나타내는 변수에 대입해준다.- 예)123string base = "hello world!"; base.length(); base.size();cs - size()와 length()는 이름만 다를 뿐, 같은 일을 하는 멤버 함수다.- 내용 출처 : http://makerj.tistory.com/127#string-길이

  24. 2017.11.12 vector 안의 원소들의 순서를 역순으로 바꾸는 방법

    *vector 안의 원소들의 순서를 역순으로 바꾸는 방법 1) 헤더를 include하여 reverse 함수를 사용한다.12345678#include #include int main() { std::vector a; std::reverse(a.begin(), a.end()); return 0;}Colored by Color Scriptercs 2) rbegin()과 rend()를 사용한다.12345678910111213141516171819#include #include templatevoid print_range(InIt first, InIt last, char const* delim = "\n"){ --last; for(; first != last; ++first){ std::cout

  25. 2017.11.08 정렬 알고리즘의 시간 복잡도 비교

    Array Sorting Algorithms AlgorithmTime ComplexitySpace ComplexityBestAverageWorstWorstQuicksortΩ(n log(n))Θ(n log(n))O(n^2)O(log(n))MergesortΩ(n log(n))Θ(n log(n))O(n log(n))O(n)TimsortΩ(n)Θ(n log(n))O(n log(n))O(n)HeapsortΩ(n log(n))Θ(n log(n))O(n log(n))O(1)Bubble SortΩ(n)Θ(n^2)O(n^2)O(1)Insertion SortΩ(n)Θ(n^2)O(n^2)O(1)Selection SortΩ(n^2)Θ(n^2)O(n^2)O(1)Tree SortΩ(n log(n))Θ(n log(n))O(n^2)..

  26. 2017.11.08 데이터 형식 범위

    데이터 형식 범위Visual Studio 2015 게시 날짜: 2016년 6월Visual Studio 2017 에 대한 최신 설명서는 Visual Studio 2017 설명서를 참조하세요.Visual C++ 32비트 및 64비트 컴파일러는 이 문서의 뒷부분의 표에 나온 형식을 인식합니다.int (unsigned``int)__int8 (unsigned``__int8)__int16 (unsigned``__int16)__int32 (unsigned``__int32)__int64 (unsigned``__int64)short (unsigned``short)long (unsigned``long)long long (unsigned``long``long)이름이 두 개의 밑줄(__)로 시작하는 경우 데이터 형식은 비표준..

  27. 2017.11.08 [header][C library] cwctype (wctype.h)

    *[header][C library] cwctype (wctype.h) (wctype.h)Wide character typeThis header declares a set of functions to classify and transform individual wide characters. For more info on how the standard ASCII character set is classified using the "C" locale, see . FunctionsCharacter classification functionsThey check whether the character passed as parameter belongs to a certain category: iswalnumChec..

  28. 2017.11.08 [header][C library] cwchar (wchar.h)

    *[header][C library] cwchar (wchar.h) (wchar.h)Wide charactersThis header file defines several functions to work with C wide strings. FunctionsInput/Output: (mostly wide versions of functions) fgetwcGet wide character from stream (function )fgetwsGet wide string from stream (function )fputwcWrite wide character to stream (function )fputwsWrite wide string to stream (function )fwideStream orienta..

  29. 2017.11.08 [header][C library] cuchar (uchar.h) (C++11)

    *[header][C library] cuchar (uchar.h) (C++11) (uchar.h)Unicode charactersThis header provides support for 16-bit and 32-bit characters, suitable to be encoded using UTF-16 and UTF-32. TypesIn C, this header defines two macros: char16_t and char32_t, which map to unsigned integral types of the appropriate size (the same as uint_least16_t and uint_least32_t, respectively). In C++, char16_t and cha..

  30. 2017.11.08 [header][C library] ctime (time.h)

    *[header][C library] ctime (time.h) (time.h)C Time LibraryThis header file contains definitions of functions to get and manipulate date and time information. FunctionsTime manipulationclockClock program (function )difftimeReturn difference between two times (function )mktimeConvert tm structure to time_t (function )timeGet current time (function ) ConversionasctimeConvert tm structure to string ..

728x90


📖 Contents 📖