C++ STL Map 에서 Find 메서드 사용하기

C++Beginner
지금 연습하기

소개

이 랩에서는 C++ 의 Map 에서 find() 메서드를 사용하는 방법을 배우게 됩니다. find() 메서드는 주어진 키를 가진 Map 에서 요소를 검색하는 데 사용됩니다. 이 랩은 C++ 와 Map 컨테이너에 대한 기본적인 지식을 가지고 있다고 가정합니다.

새 C++ 파일 생성

먼저, ~/project 디렉토리에 main.cpp라는 이름의 새로운 C++ 파일을 생성해야 합니다. 이 파일을 생성하고 편집하기 위해 모든 텍스트 편집기 또는 IDE 를 사용할 수 있습니다.

cd ~/project
touch main.cpp

필요한 라이브러리 및 네임스페이스 포함

main.cpp 파일의 상단에 필요한 라이브러리와 using 지시문을 포함합니다.

#include <iostream>
#include <map>   //include map library

using namespace std;

main 함수 정의

코드를 작성하기 시작하려면 main() 함수를 정의하십시오.

int main() {
  //Your code
  return 0;   //Exit program
}

Map 컨테이너 생성

정수 키와 값을 갖는 Map 컨테이너를 생성합니다. Map 컨테이너는 키의 오름차순으로 정렬된 키 - 값 쌍을 저장합니다.

map<int, int> myMap;   //Create a Map container with integer keys and values

Map 에 요소 삽입

insert() 메서드를 사용하여 Map 컨테이너에 키 - 값 쌍을 삽입합니다. 이 단계는 Map 에 다섯 개의 요소를 삽입합니다.

myMap.insert(make_pair(3, 9));
myMap.insert(make_pair(2, 4));
myMap.insert(make_pair(5, 25));
myMap.insert(make_pair(9, 81));
myMap.insert(make_pair(1, 1));

find() 메서드를 사용하여 요소 검색

find(x) 메서드를 사용하여 Map 에서 키 x 를 가진 요소를 검색합니다. 요소가 발견되면, 메서드는 해당 요소에 대한 이터레이터 (iterator) 를 반환합니다. 찾을 수 없으면, 메서드는 Map 컨테이너의 end()에 대한 이터레이터를 반환합니다. 여기서는 키 5 와 6 을 가진 요소를 검색합니다.

map<int, int>::iterator it;   //Create an iterator for the Map container
it = myMap.find(5);   //Find the element with key 5 in the Map
if (it != myMap.end()) {
  cout << "Element with key 5 is found and the value is " << it->second << endl;
} else {
  cout << "Element with key 5 is not found\n";
}
it = myMap.find(6);   //Find the element with key 6 in the Map
if (it != myMap.end()) {
  cout << "Element with key 6 is found and the value is " << it->second << endl;
} else {
  cout << "Element with key 6 is not found\n";
}

프로그램 컴파일 및 실행

터미널에서 다음 명령을 사용하여 main.cpp 파일을 컴파일합니다.

g++ main.cpp -o main

다음 명령을 사용하여 프로그램을 실행합니다.

./main

프로그램 테스트

프로그램을 실행한 후, 터미널에서 다음과 같은 출력을 볼 수 있습니다.

Element with key 5 is found and the value is 25
Element with key 6 is not found

이 출력은 키 5 를 가진 요소가 Map 에서 발견되었고, 해당 값은 25 임을 보여줍니다. 키 6 을 가진 요소는 Map 에서 발견되지 않았습니다.

코드 완성

다음 전체 코드를 복사하여 main.cpp 파일에 붙여넣으세요.

#include <iostream>
#include <map>

using namespace std;

int main() {
  map<int, int> myMap;   //Create a Map container with integer keys and values
  myMap.insert(make_pair(3, 9));
  myMap.insert(make_pair(2, 4));
  myMap.insert(make_pair(5, 25));
  myMap.insert(make_pair(9, 81));
  myMap.insert(make_pair(1, 1));
  map<int, int>::iterator it;   //Create an iterator for the Map container
  it = myMap.find(5);   //Find the element with key 5 in the Map
  if (it != myMap.end()) {
    cout << "Element with key 5 is found and the value is " << it->second << endl;
  } else {
    cout << "Element with key 5 is not found\n";
  }
  it = myMap.find(6);   //Find the element with key 6 in the Map
  if (it != myMap.end()) {
    cout << "Element with key 6 is found and the value is " << it->second << endl;
  } else {
    cout << "Element with key 6 is not found\n";
  }
  return 0;   //Exit program
}

요약

축하합니다! C++ 에서 Map 컨테이너의 find() 메서드를 사용하는 방법을 성공적으로 배우셨습니다. find() 메서드는 Map 컨테이너에서 특정 키를 가진 요소를 검색하는 데 유용합니다. find() 메서드는 요소가 발견되면 해당 요소에 대한 이터레이터 (iterator) 를 반환하고, 요소가 발견되지 않으면 Map 컨테이너의 end()에 대한 이터레이터를 반환한다는 것을 기억하세요.