C++中的map特性

Jackey C/C++ 1,842 次浏览 , 没有评论
int main() {

    map<int, int> myMap;
    // 查找
    if (myMap.find(42) == myMap.end())
        cout<<"Can not find element 42"<<endl;
    else
        cout<<"Element 42 is in the map"<<endl;

    // map的默认值为0
    cout<<myMap[42]<<endl;

    // 访问之后,自动插入元素
    if (myMap.find(42) == myMap.end())
        cout<<"Can not find element 42"<<endl;
    else
        cout<<"Element 42 is in the map"<<endl;

    cout<<myMap[42]<<endl;

    // 进行++操作之后,值变成1
    myMap[42]++;
    cout<<myMap[42]<<endl;

    // 进行--操作周后,值变为0
    myMap[42]--;
    cout<<myMap[42]<<endl;

    // 此时不影响查找
    if (myMap.find(42) == myMap.end())
        cout<<"Can not find element 42"<<endl;
    else
        cout<<"Element 42 is in the map"<<endl;

    // 真正的删除元素
    myMap.erase(42);
    if (myMap.find(42) == myMap.end())
        cout<<"Can not find element 42"<<endl;
    else
        cout<<"Element 42 is in the map"<<endl;

    return 0;
}

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Go