C++primer 학습: 연관 컨테이너(1)

7009 단어

map: 모든 대상은pair 대상이고 키워드와 값 집합입니다.


set: 키워드의 집합일 뿐입니다. 존재하는지 확인하는 데 사용됩니다.


연습: 텍스트를 읽고 자주 사용하는 키워드 이외의 단어의 출현 횟수를 통계합니다.

map<string, size_t> word_counts;
    set<string> exclude = { "a", "an", "the", "is", "he" };
    string word;
    while (cin>>word)
    {
        if (exclude.find(word) == exclude.end())
            ++word_counts[word];
    }
    for (const auto & it:word_counts)
        cout << it.first << " : " << it.second << " times
"
; return 0;

연습: 이전 문제 덮어쓰기, 대소문자 및 문장부호 무시


//여기에 표준 라이브러리 알고리즘remove 활용if. remove(val)/remove_만약 (pred) 삭제 ==val 또는 pred를 실제 요소로
map<string, size_t> word_counts;
    set<string> exclude = { "a", "an", "the", "is", "he" };
    string word;
    while (cin>>word)
    {
        if (exclude.find(word) == exclude.end())
        {
            word[0] = toupper(word[0]);// 
            remove_if(word.begin(), word.end(), ispunct);
            ++word_counts[word];
        }

    }
    for (const auto & it:word_counts)
        cout << it.first << " : " << it.second << " times
"
; return 0;

연습: 맵을 정의합니다. 키워드는 가정의 성이고 값은 가정의 아이의 이름입니다.새로운 가정을 추가하고 가정에 아이를 추가하는 것을 실현한다.

using Children = vector<string>;
int main()
{
    map<string, Children> family;
    set<string> exclude;
    string name_f,name_child;
    while (cin>>name_f)
    {
        cout << "children :" << endl;
        while (cin>>name_child)
        {
            family[name_f].push_back(name_child);
        }
        cin.clear();
    }
    for (const auto it : family)
    {
        cout << endl<<it.first << ":" ;
        for(const auto child : it.second)
        {
            cout << child << " ";
        }
    }
    return 0;
}

연습: 반복되지 않는 단어를 vector로 저장합니다.


: set을 사용하는 장점은 네가 어떻게 입력하든지 순서대로 저장하는 것이다

vector<string> S;
    string word;
    while (cin>>word)
    {
        if (find(S.cbegin(), S.cend(), word) == S.cend())
        S.push_back(word);
    }
    for (auto it : S)
        cout << it<<" ";
    return 0;
}

만약 키워드가 <기호를 정의하지 않았다면, 우리는 스스로 정의한 함수를 비교 규칙으로 제공해야 한다.원소 유형을 제외하고 함수 바늘도 하나 더 추가해야 한다.

bool compareIsbn(const Sales_data& lhs, const Sales_data& rhs)
{
    return lhs.isbn() < rhs.isbn();
}

int main()
{
    using compareType = bool (*)(const Sales_data& lhs, const Sales_data& rhs);
    // typedef bool(*compareType)(const Sales_data &lhs, const Sales_data &rhs);
    std::multiset<Sales_data, decltype<compareIsbn>*> bookstore(compareIsbn);
}

좋은 웹페이지 즐겨찾기