C++入门:STL——map

关联式容器:每个元素位置取决于特定的排序准则以及元素值,和插入次序无关。

一、map

map提供一对一(其中第一个称为关键字key,每个关键字只能在map中出现一次,第二个称为该关键字的值value)的数据处理能力,由于这个特性,它完成有可能在我们处理一对一数据的时候,在编程上提供快速通道。map内部自建一颗红黑树(一 种非严格意义上的平衡二叉树),这颗树具有对数据自动排序的功能,所以在map内部所有的数据都是有序的。

二、map的初始化

map <string,int> m;
map <string,int>::iterator it;

三、map的大小和容量

  • m.size():返回map中元素的个数
  • m.max_size():返回最大可允许的map元素数量值

四、map的插入:insert()

  • m.insert(pair<T,T>(key, value)) :插入pair数据
  • m.insert(map<T,T>::value_type (key, value)):插入value_type数据
  • m[key]=value:用数组方式插入数据
#include <map>
#include <string>
#include <iostream>
using namespace std;

int main()
{
    map<int, string> mapStudent;

    //第一种:用insert函数插入pair数据
    mapStudent.insert(pair<int, string>(1, "student_one"));

    //第二种:用insert函数插入make_pair数据
    mapStudent.insert(make_pair(2, "student_two"));

    //第三种:用insert函数插入value_type数据
    mapStudent.insert(map<int, string>::value_type (3, "student_three"));

    //第四种:用数组方式插入数据
    mapStudent[4] = "student_four";

    map<int, string>::iterator iter;
    for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
       cout<<iter->first<<' '<<iter->second<<endl;
}

用insert函数插入数据,当map中有这个关键字时,insert操作是插入数据不了的,但是用数组方式就不同了,它可以覆盖以前该关键字对应的值。我们通过pair的第二个变量来知道是否插入成功,它的第一个变量first返回的是一个map的迭代器,如果插入成功的话第二个变量second应该是true的,否则为false。

五、map的删除:erase()

  • m.erase(iterator it):删除map中迭代器指向元素
  • m.erase(iterator first,iterator last):删除map中[first,last)中元素
  • m.clear():清空map中所有元素
#include <map>
#include <string>
#include <iostream>
using namespace std;

int main()
{
    map<int, string> mapStudent;
    mapStudent.insert(pair<int, string>(1, "student_one"));
    mapStudent.insert(pair<int, string>(2, "student_two"));
    mapStudent.insert(pair<int, string>(3, "student_three"));

    //如果要删除1,用迭代器删除
    map<int, string>::iterator iter;
    iter = mapStudent.find(1);
    mapStudent.erase(iter);

    //如果要删除1,用关键字删除
    int n = mapStudent.erase(1);//如果删除了会返回1,否则返回0

    //用迭代器,成片的删除
    //一下代码把整个map清空
    mapStudent.erase( mapStudent.begin(), mapStudent.end() );

    //成片删除要注意的是,也是STL的特性,删除区间是一个前闭后开的集合
    //自个加上遍历代码,打印输出吧
}

六、map的遍历:借助迭代器或者下标法[]

  • m.begin():返回map头指针,指向第一个元素
  • m.end():返回map尾指针,指向map最后一个元素的下一个位置
  • m.rbegin():反向迭代器,指向最后一个元素
  • m.rend():反向迭代器,指向第一个元素之前的位置
#include <map>
#include <string>
#include <iostream>
using namespace std;
  
int main()
{
    map<int, string> mapStudent;

    mapStudent.insert(pair<int, string>(1, "student_one"));
    mapStudent.insert(pair<int, string>(2, "student_two"));
    mapStudent.insert(pair<int, string>(3, "student_three"));
    
    //第一种,利用迭代器
    map<int, string>::iterator iter;
    for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
       cout<<iter->first<<' '<<iter->second<<endl;

    //第二种,利用反向迭代器
    for(iter = mapStudent.rbegin(); iter != mapStudent.rend(); iter++)
        cout<<iter->first<<"  "<<iter->second<<endl;
    
    //第三种:用数组方式
    //此处应注意,应该是 for(int nindex = 1; nindex <= nSize; nindex++)
    //而不是 for(int nindex = 0; nindex < nSize; nindex++)
    for(int nindex = 1; nindex <= nSize; nindex++)
        cout<<mapStudent[nindex]<<endl;
}

七、map的查找函数(键)

  • m.count():判定关键字是否出现,其缺点是无法定位数据出现位置,返回值只有两个,要么是0,要么是1(出现)
  • m.find():定位数据出现位置,它返回的一个迭代器,当数据出现时,它返回数据所在位置的迭代器,如果map中没有要查找的数据,它返回的迭代器等于end函数返回的迭代器。
#include<string>
#include<cstring>
#include<iostream>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
int main(){
    map<string,int> test;
    test.insert(make_pair("test1",1));//test["test1"]=1
    test.insert(make_pair("test2",2));//test["test2"]=2
    map<string,int>::iterator it;
    it=test.find("test0");
    cout<<"test0 find:";
    if(it==test.end()){
        cout<<"test0 not found"<<endl;
    }
    else{
        cout<<it->second<<endl;
    }
    cout<<"test0 count:";
    cout<<test.count("test0")<<endl;
    cout<<"-------------------"<<endl;
    cout<<"test2 find:";
    it=test.find("test2");
    if(it==test.end()){
        cout<<"test2 not found"<<endl;
    }
    else{
        cout<<it->second<<endl;
    }
    cout<<"test2 count:";
    cout<<test.count("test2")<<endl;
    cout<<"-------------------"<<endl;
    cout<<"inserting test1:insert"<<endl;
    test.insert(make_pair("test1",2));
    cout<<"test1 find:";
    it=test.find("test1");
    if(it==test.end()){
        cout<<"test1 not found"<<endl;
    }
    else{
        cout<<it->second<<endl;
    }
    cout<<"test1 count:";
    cout<<test.count("test1")<<endl;
    cout<<"-------------------"<<endl;
    cout<<"inserting test1:[]"<<endl;
    test["test1"]=2;
    cout<<"test1 find:";
    it=test.find("test1");
    if(it==test.end()){
        cout<<"test1 not found"<<endl;
    }
    else{
        cout<<it->second<<endl;
    }
    cout<<"test1 count:";
    cout<<test.count("test1")<<endl;
    return 0;
}

八、map的排序函数

  • 对有序map中的key排序:如果在有序的map中,key是int或string,它们本身的就是有序的,不用额外的操作。
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include <vector>
#include<string>
#include<map>
#include <functional> // std::greater
using namespace std;

struct CmpByKeyLength {
    bool operator()(const string& k1, const string& k2)const {
        return k1.length() < k2.length();
    }
};

int main()
{
    //1、map这里指定less作为其默认比较函数(对象),就是默认按键值升序排列
    // map<string, int> name_score_map;
    /*Albert
      Bing
      BoB
      LiMin
      ZiLinMi*/

    // 2、可以自定义,按照键值升序排列,注意加载
    // #include <functional> // std::greater
    // map<string, int, greater<string>> name_score_map;

    //3、按照自定义内容进行排序,比如字符串的长度
    map<string, int, CmpByKeyLength> name_score_map;

    name_score_map["LiMin"] = 90;
    name_score_map["ZiLinMi"] = 79;
    name_score_map["BoB"] = 92;
    name_score_map.insert(make_pair("Bing", 99));
    name_score_map.insert(make_pair("Albert", 86));

    map<string, int>::iterator iter;
    for ( iter = name_score_map.begin();iter != name_score_map.end();++iter) {
        cout << (*iter).first << endl;
    }

    system("pause");
    return 0;
}

  • 对有序map中的value排序:把map中的元素放到序列容器(如vector)中,再用sort进行排序。
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include <vector>
#include<string>
#include<map>
#include <functional> // std::greater
using namespace std;

bool cmp(const pair<string, int>& a, const pair<string, int>& b) {
        return a.second < b.second;
}

int main()
{
    //1、map这里指定less作为其默认比较函数(对象),就是默认按键值升序排列
    map<string, int> name_score_map;
    name_score_map["LiMin"] = 90;
    name_score_map["ZiLinMi"] = 79;
    name_score_map["BoB"] = 92;
    name_score_map.insert(make_pair("Bing", 99));
    name_score_map.insert(make_pair("Albert", 86));

    //输出添加的内容
    map<string, int>::iterator iter;
    for (iter = name_score_map.begin(); iter != name_score_map.end(); ++iter) {
        cout << (*iter).first << endl;
    }
    cout << endl;

    // 将map中的内容转存到vector中
    vector<pair<string, int>> vec(name_score_map.begin(), name_score_map.end());
    //对线性的vector进行排序
    sort(vec.begin(), vec.end(), cmp);
    for (int i = 0; i < vec.size(); ++i)
        cout << vec[i].first << endl;

    system("pause");
    return 0;
}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: C++STL(Standard Template Library,标准模板库)是一个强大的库,其中包含了许多容器、算法和迭代器等组件。其中的容器是实现数据管理和存储的基本组件,包括向量、列表、队列和映射等。而在STL中使用的容器,大多采用了 C++ 的泛型编程的方式,即采用了泛型。 泛型是一种基于类型参数化的编程方式,它的主要特点是可以忽略类型细节而将通用算法应用于不同的类型数据上。在STL中,泛型的应用可以明显提高代码的复用性和灵活性,使得STL的容器可以应用于不同类型的数据。 在STL中,容器、算法和迭代器等组件都是以泛型的形式出现。泛型程序可以使用模板来定义不同类型的函数和类。例如,使用 vector 模板可以创建一个自动分配和管理内存的可变数组。使用迭代器就可以对容器中的元素进行遍历。而STL中的算法则可以对容器中的元素进行各种处理,如排序和查找等。 STL中的泛型应用使得程序员们不必为不同的数据类型写出不同的版本的代码,同时也使得算法重用更加容易。因此,STL成为了C++编程中不可或缺的一部分,它将数据结构和算法分离,使得程序变得更加简单、漂亮和容易理解。 ### 回答2: STL(标准模板库)是C++编程中的一种重要的程序库,它提供了一系列的模板类和模板函数,可以帮助开发者更加高效地进行编程。其中,泛型是STL中的重要概念,它可以实现代码的重用,提高程序的可读性和可维护性。 泛型是指在STL程序设计中,可以将容器的类型、算法的参数、迭代器的类型等抽象成具有灵活性的、可重用的模板。这种设计思想可以让程序员编写具有通用性的代码,无需为每种数据类型单独编写代码。同时,泛型还可以维护代码的一致性和可靠性,减少编程错误。 STL的泛型分为容器和算法两个方面。容器是指能够存储某种数据类型的数据结构,例如vector、list、deque、set、map等。它们的共同点是都提供了访问元素的迭代器接口,可以通过迭代器的方式对元素进行访问、添加、删除等操作。使用容器能够简化对元素的操作,提高代码的可读性。 算法是指对容器中的元素执行某些操作的函数,例如find、sort、copy等。在STL中,算法通常使用迭代器作为参数,允许程序员通过自定义函数对象来实现更灵活的算法。 STL采用有限的基本概念和范式,尝试构建一种抽象的“程序设计语言”,把现实世界中需要处理的数据组织成容器,用算法来操作容器中的数据,以及迭代器来遍历容器中的元素。这种设计使得编写代码变得简单、可读性强、可维护性好,具有很高的实用价值。 总之,STL泛型技术是C++中一个非常重要的概念,它能够提高程序的可读性和可维护性,使得程序员能够高效地开发各种应用程序。掌握STL泛型技术,不仅可以帮助程序员更好地理解C++编程,而且也可以让代码更加清晰、简洁和高效。 ### 回答3: STL(标准模板库)是C++中的一个重要组成部分,它包含很多的类模板和函数模板,而其中的泛型(generic programming)则是STL的核心理念。泛型是指在编写程序时抽象出类型,使得同一份代码适用于多种不同的数据类型,同时保持程序代码的高效和可维护性。STL采用了泛型编程的方法,利用了模板特性,实现了很多可以适用于广泛场景的标准算法和容器。以下是STL中常见的泛型及其应用。 1. 容器(Containers): STL提供了多种类型的容器,如vector、list、deque、map等等。它们都是通过模板类实现的,可以存储不同类型的数据并提供多种数据管理功能。容器可以存储基本类型或用户定义的对象,可用于解决很多实际问题。例如,vector是一种高效的数据结构,可以存储不同类型的数据,比如数组和连续的空间。list和deque是序列容器,可以方便地插入、删除和遍历数据。map是一种关联式容器,它提供了键值对的存储和查找功能,可以极大地简化一些算法。 2. 迭代器(Iterators): 迭代器是指指向容器中某个元素的指针或类似于指针的对象。迭代器可以按照顺序访问容器中的元素,并可以实现很多算法。STL中的迭代器被设计成可以与容器类型无关,使得同一份算法可以适用于不同类型的容器。例如,迭代器可以用于实现排序、搜索和复制等操作。 3. 算法(Algorithms): STL提供了很多通用算法,例如sort、find、copy等等。这些算法都是通过模板函数实现的,可以适用于不同类型的容器和迭代器。算法的实现通常采用泛型编程技术,使得代码复用率高,并且可以保证算法的高效性。 在实际应用中,STL的泛型编程理念优化了大部分的数据结构和算法的实现,并且使得代码更加清晰。STL容器除了能够存储不同类型的数据,还具有一定的自我维护机制,如动态增长、内存管理等。同时,STL也弥补了一些C++语言中的不足,如指针操作容易出错、STL提供了异常处理机制等。在实际使用中,STL容器和算法的复杂度较低,执行效率较高,因此在开发中应尽可能采用STL

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值