ShovelingLife
A Game Programmer
ShovelingLife
전체 방문자
오늘
어제
  • 분류 전체보기 (1072)
    • 그래픽스 (57)
      • 공통 (19)
      • 수학 물리 (22)
      • OpenGL & Vulkan (1)
      • DirectX (14)
    • 게임엔진 (183)
      • Unreal (69)
      • Unity (103)
      • Cocos2D-X (3)
      • 개인 플젝 (8)
    • 코딩테스트 (221)
      • 공통 (7)
      • 프로그래머스 (22)
      • 백준 (162)
      • LeetCode (19)
      • HackerRank (2)
      • 코딩테스트 알고리즘 (8)
    • CS (235)
      • 공통 (21)
      • 네트워크 (44)
      • OS & 하드웨어 (55)
      • 자료구조 & 알고리즘 (98)
      • 디자인패턴 (6)
      • UML (4)
      • 데이터베이스 (7)
    • 프로그래밍 언어 (348)
      • C++ (167)
      • C# (90)
      • Java (9)
      • Python (33)
      • SQL (30)
      • JavaScript (8)
      • React (7)
    • 그 외 (9)
      • Math (5)
      • 일상 (5)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

  • Source Code 좌측 상단에 복사 버튼 추가 완료
  • 언리얼 엔진 C++ 빌드시간 단축 꿀팁
  • 게임 업계 코딩테스트 관련
  • 1인칭 시점으로 써내려가는 글들

인기 글

태그

  • 티스토리챌린지
  • 언리얼
  • 포인터
  • C++
  • string
  • C
  • 백준
  • 오블완
  • 그래픽스
  • 알고리즘
  • 유니티
  • Unity
  • 파이썬
  • 문자열
  • 배열
  • 프로그래머스
  • c#
  • SQL
  • 클래스
  • 함수

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
ShovelingLife

A Game Programmer

CS/자료구조 & 알고리즘

C++ vector empty()와 size()간 차이

2022. 8. 4. 13:20

vector::empty()

벡터가 비어있는지 확인하는 함수이다.

Input  : myvector = 1, 2, 3, 4, 5
         myvector.empty();
Output : False

Input  : myvector = {}
         myvector.empty();
Output : True

시간 복잡도 : O(1)

#include <iostream>
#include <vector>
using namespace std;
 
int main()
{
    vector<int> myvector{};
    if (myvector.empty())
    {
        cout << "True";
    }
    else {
        cout << "False";
    }
    return 0;
}
True

다음은 전체 배열의 합계를 구하는 프로그램이다.

Input  : 1, 5, 6, 3, 9, 2
Output : 26
Explanation -  1+5+6+3+9+2 = 26
// CPP program to illustrate
// Application of empty() function
#include <iostream>
#include <vector>
using namespace std;
 
int main()
{
    int sum = 0;
    vector<int> myvector{ 1, 5, 6, 3, 9, 2 };
    while (!myvector.empty())
    {
        sum = sum + myvector.back();
        myvector.pop_back();
    }
    cout << sum;
    return 0;
}

vector::size()

배열의 크기를 반환하는 함수이다.

Input  : myvector = 1, 2, 3, 4, 5
         myvector.size();
Output : 5

Input  : myvector = {}
         myvector.size();
Output : 0
#include <iostream>
#include <vector>
using namespace std;
 
int main()
{
    vector<int> myvector{ 1, 2, 3, 4, 5 };
    cout << myvector.size();
    return 0;
}

왜 size()보단 empty()가 선호 될까?

  1. 조건 연산자를 안쓰기 때문에 직관적이다.
  2. O(1)의 복잡도를 유지한다, list 같은 경우에는 O(n)
Input  : 1, 5, 6, 3, 9, 2
Output : 26
Explanation -  1+5+6+3+9+2 = 26
#include <iostream>
#include <vector>
using namespace std;
 
int main()
{
    int sum = 0;
    vector<int> myvector{ 1, 5, 6, 3, 9, 2 };
    while (myvector.size() > 0) {
        sum = sum + myvector.back();
        myvector.pop_back();
    }
    cout << sum;
    return 0;
}

clear() 함수를 호출 후 size() 함수를 호출할 시 쓰레기 값이 나온다. 아래는 정상 출력

#include <bits/stdc++.h>
using namespace std;
 
int main()
{
 
    // Initializing a vector of string type
    vector<string> vec = { "Geeks", "For", "Geeks" };
 
    for (int i = 0 ; i <= vec.size() - 1 ; i++)
        cout << vec[i] << ' ';
    return 0;
}
Geeks For Geeks 

 

#include <bits/stdc++.h>
using namespace std;
 
int main()
{
 
    // Initializing a vector of string type
    vector<string> vec = { "Geeks", "For", "Geeks" };
 
    vec.clear();
    for (int i = 0; i <= vec.size() - 1; i++)
        cout << vec[i] << ' ';
 
    cout << "Geeks For Geeks";
    return 0;
}
Segmentation Fault SIGEGV

따라서 clear후 for문에서 조건으로는 int형으로 캐스팅 해줘야한다.

#include <bits/stdc++.h>
using namespace std;
 
int main()
{
 
    // Initializing a vector of string type
    vector<string> vec = { "Geeks", "For", "Geeks" };
     
      // Clearing the vector
      // Now size is equal to 0
    vec.clear();
       
      // Typecasting vec.size() to int
    for (int i = 0; i < (int)vec.size() - 1; i++)
        cout << vec[i] << ' ';
 
    cout << "Geeks For Geeks";
    return 0;
}

출처 : https://www.geeksforgeeks.org/vectorempty-vectorsize-c-stl/

저작자표시 (새창열림)

'CS > 자료구조 & 알고리즘' 카테고리의 다른 글

최소 스패닝 트리 (MST) / 크루스칼 알고리즘 (Kruskal Algorithm)  (0) 2022.08.14
가중치 그래프와 임계 경로(Critical Path)  (0) 2022.08.14
C++ vector사용법 및 설명 (장&단점)  (0) 2022.08.03
C 정렬 코드  (0) 2022.07.20
컨테이너 어댑터 (스택, 큐, 우선순위 큐)  (0) 2022.07.04
    'CS/자료구조 & 알고리즘' 카테고리의 다른 글
    • 최소 스패닝 트리 (MST) / 크루스칼 알고리즘 (Kruskal Algorithm)
    • 가중치 그래프와 임계 경로(Critical Path)
    • C++ vector사용법 및 설명 (장&단점)
    • C 정렬 코드
    ShovelingLife
    ShovelingLife
    Main skill stack => Unity C# / Unreal C++ Studying Front / BackEnd, Java Python

    티스토리툴바