English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
C ++ map cbegin()该函数用于返回指向map容器第一个元素的常量迭代器。
const_iterator cbegin() const noexcept; //C++ 11 之后
没有
그것은 맵의 첫 번째 요소를 가리키는 상수 이터너리를 반환합니다.
让我们来看一个简单的cbegin() 함수 예제.
#include <iostream> #include <map> using namespace std; int main () { map<char, string> mymap; mymap['b'] = "Java"; mymap['a'] = "C++"; mymap['c'] = "SQL"; // 显示内容: for (auto it = mymap.cbegin(); it != mymap.cend(); ++it) cout << (*it).first << " => " << (*it).second << '\n'; return 0; }
출력:
a => C++ b => Java c => SQL
在上面的代码中,cbegin() 함수는 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; //std::for_each와 람다 함수를 사용하여 맵을 순회합니다. for_each(m.cbegin(), m.cend(), [](pair<string, int> element){ // ACCESSING KEY FROM ELEMENT. string word = element.first; // ACCESSING VALUE FROM ELEMENT. 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" }}; map<int, string>::const_iterator it; // 이터너터를 선언 it = mymap.cbegin(); // 그를 벡터의 시작점에 할당 while (it != mymap.cend()) { cout << it->first << " = " << it->second << "\n"; // 그가 가리키는 요소의 값을 출력 ++it; // 다음 요소로 이동 } cout << endl; }
출력:
100: Nikita 200: Deep 300: Priya 400: Suman 500: Aman
위의 예제에서 cbegin() 함수는 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.cbegin(); it != mymap.cend(); ++it) cout << it->first << " + " << it->second << " = " <<it->first + it->second << '\n'; auto ite = mymap.cbegin(); cout << "첫 번째 요소는: "; cout << "{" << ite->first << ", " << ite->second << "}\n"; return 0; }
출력:
요소는: 10 + 10 = 20 20 + 20 = 40 30 + 30 = 60 첫 번째 요소는: {10, 10}
위의 예제에서 cbegin() 함수는 mymap 컨테이너의 첫 번째 요소에 대한 이터레이터를 반환합니다.