English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
C ++ map begin()함수는 맵 컨테이너의 첫 번째 요소에 대한 이터레이터를 반환합니다.
iterator begin(); //until C++ 11 const_iterator begin() const; //until C++ 11 iterator begin() noexcept; //since C++ 11 const_iterator begin() const noexcept; //since C++ 11
없음
맵의 첫 번째 요소를 가리키는 이터레이터를 반환합니다.
begin() 함수의 간단한 예제를 보겠습니다.
#include <iostream> #include <map> using namespace std; int main () { map<char, string> mymap; mymap['b'] = "Java"; mymap['a'] = "C++"; mymap['c'] = "SQL"; // 내용 표시 for (map<char, string>::iterator it = mymap.begin(); it != mymap.end(); ++it) cout << it->first << " => " << it->second << '\n'; return 0; }
출력:
a => C++ b => Java c => SQL
위의 코드에서 begin() 함수는 mymap 매핑의 첫 번째 요소를 가리키는 이터너리를 반환합니다.
for를 사용한 간단한 예제를 보겠습니다-each 루프로 맵을 순회합니다.
#include <iostream> #include <map> #include <string> #include <iterator> #include <algorithm> using namespace std; int main() { map<string, int> m; m["Room1"] = 100; m["Room2"] = 200; m["Room3"] = 300; // 맵의 시작을 지시하는 맵 이터레이터를 생성합니다 map<string, int>::iterator it = m.begin(); // std::for_each와 람다 함수를 사용하여 맵을 순회합니다 for_each(m.begin(), m.end(), [](pair<string, int> element){ // KEY를 접근 string word = element.first; // VALUE를 접근 int count = element.second; cout<<word<<" = "<<count<<endl; }); return 0; }
출력:
Room1 = 100 Room2 = 200 Room3 = 300
위의 예제에서 STL 알고리즘 std :: for-each 맵을 순회합니다. 이는 맵의 각 요소를 순회하며 제공된 콜백을 호출합니다.
while 루프를 사용하여 맵을 이터너이션하는 간단한 예제를 보겠습니다。
#include <iostream> #include <map> #include <string> int main() { using namespace std; map<int,string> mymap = { { 100, "Nikita"}, { 200, "Deep" }, { 300, "Priya" }, { 400, "Suman" }, { 500, "Aman" }}; cout<<"요소는:" <<endl; map<int, string>::const_iterator it; // 이터너리를 선언 it = mymap.begin(); // 그를 벡터의 시작점에 할당 while (it != mymap.end()) { cout << it->first << " = " << it->second << "\n"; // 그가 가리키는 요소의 값을 출력 ++it; // 다음 요소로 이동 } cout << endl; }
출력:
요소는: 100: Nikita 200: Deep 300: Priya 400: Suman 500: Aman
위의 코드에서 begin() 함수는 mymap 매핑의 첫 번째 요소를 가리키는 이터너리를 반환합니다.
간단한 예제를 보겠습니다:
#include <iostream> #include <string> #include <map> using namespace std; int main () { map<int,int> mymap = { { 10, 10}, { 20, 20 }, { 30, 30 } }; cout<<"요소는:" <<endl; for (auto it = mymap.begin(); it != mymap.end(); ++it) cout << it-first << " + " << it-second << " = " <<it-first + it-second << '\n'; auto ite = mymap.begin(); cout << "The first element is: "; cout << "{" << ite->first << "", " << ite->second << "}\n"; return 0; }
출력:
요소는: 10 + 10 = 20 20 + 20 = 40 30 + 30 = 60 The first element is: {10, 10}
위의 예제에서 begin() 함수는 mymap 컨테이너의 첫 번째 요소에 대한 이터레이터를 반환합니다.