18870

csct3456·2022년 4월 21일
0

map 사용법

#include <iostream>
#include <vector>
#include <algorithm>
#include <map>

using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    
    int tmp, n;
    vector<int> v;
    map<int, int> m;
    map<int, int>::iterator iter;
    
    cin >> n;
    int num[n];
    
    for(int i=0; i<n; i++) {
        cin >> tmp;
        num[i] = tmp;
        v.push_back(tmp);
    }
    
    sort(v.begin(), v.end());
    v.erase(unique(v.begin(), v.end()), v.end());
    
    for(int i=0; i < v.size(); i++){
        m.insert(make_pair(v[i], i));
    }
    
    for(int i=0; i<n; i++) {
        auto item = m.find(num[i]);
        cout << item->second << ' ';
    }
    
    return 0;
}
  • 선언 : map<key_type, value_type> m;
  • 초기화 : m.insert(make_pair(key, value));
  • 검색 : auto iter = m.find(key);

참고용

http://www.cplusplus.com/reference/algorithm/find_if/
https://stackoverflow.com/questions/22676301/find-pair-by-key-within-a-vector-of-pairs

auto it = std::find_if( sortList.begin(), sortList.end(),
    [&User](const std::pair<std::string, int>& element){ return element.first == Username;} );
bool isEqual(const std::pair<std::string, int>& element)
{
    return element.first ==  Username;
}
it = std::find_if( sortList.begin(), sortList.end(), isEqual );

0개의 댓글