"C++ 맵 find()"의 두 판 사이의 차이

 
(같은 사용자의 중간 판 하나는 보이지 않습니다)
22번째 줄: 22번째 줄:


int main() {
int main() {
     map<string, int> m;
     map<string, int> m = {{"apple",40},{"lemon",-74}};
    m["apple"] = 40;
    m["lemon"] = -74;
 
     cout << m.find("apple")->second << endl; // 40
     cout << m.find("apple")->second << endl; // 40
     cout << m.find("lemon")->second << endl; // -74
     cout << m.find("lemon")->second << endl; // -74
     cout << m.find("onion")->second << endl; // 1864668064 (not exists)
     cout << m.find("onion")->second << endl; // 1864668064 (not exists)
}
</syntaxhighlight>
<syntaxhighlight lang='cpp' run>
#include <iostream>
#include <map>
using namespace std;
int main() {
    map<string,int> m = {{"apple",40},{"lemon",-74}};
    map<string,int>::iterator it;
    it = m.find("apple");
    if(it == m.end()) {
        cout << "not found" << endl;
    } else {
        cout << it->second << endl; // 40
    }
    it = m.find("onion");
    if(it == m.end()) {
        cout << "not found" << endl; // not found
    } else {
        cout << it->second << endl;
    }
}
}
</syntaxhighlight>
</syntaxhighlight>

2023년 11월 23일 (목) 01:13 기준 최신판

1 개요[ | ]

C++ 맵 find()
#include <iostream>
#include <map>
using namespace std;

int main() {
    map<string, int> m;
    m["a"] = 40;
    m["b"] = -74;
    
    cout << (m.find("a") != m.end()) << endl; // 1 (exists)
    cout << (m.find("x") != m.end()) << endl; // 0 (not exists)
}
#include <iostream>
#include <map>
using namespace std;

int main() {
    map<string, int> m = {{"apple",40},{"lemon",-74}};
    cout << m.find("apple")->second << endl; // 40
    cout << m.find("lemon")->second << endl; // -74
    cout << m.find("onion")->second << endl; // 1864668064 (not exists)
}
#include <iostream>
#include <map>
using namespace std;

int main() {
    map<string,int> m = {{"apple",40},{"lemon",-74}};
    map<string,int>::iterator it;
    it = m.find("apple");
    if(it == m.end()) {
        cout << "not found" << endl;
    } else {
        cout << it->second << endl; // 40
    }
    it = m.find("onion");
    if(it == m.end()) {
        cout << "not found" << endl; // not found
    } else {
        cout << it->second << endl;
    }
}

2 같이 보기[ | ]

3 참고[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}