C++map容器插入数据的4种方法

  • Post author:
  • Post category:其他


转自:https://blog.csdn.net/cbnotes/article/details/76594435

在构造map容器后,我们就可以往里面插入数据了。这里讲四种插入数据的方法:

第一种:用insert函数插入pair数据:在VC下请加入这条语句,屏蔽4786警告 #pragma warning (disable:4786) )

  1. map<

    int, string> mapStudent;
  2. mapStudent.insert(pair<

    int, string>(1,

    “student_one”));

  3. mapStudent.insert(pair<

    int, string>(2,

    “student_two”));

  4. mapStudent.insert(pair<

    int, string>(3,

    “student_three”));


第二种:用insert函数插入value_type数据,下面举例说明


  1. map<

    int, string> mapStudent;
  2. mapStudent.insert(map<

    int, string>::value_type (1,

    “student_one”));

  3. mapStudent.insert(map<

    int, string>::value_type (2,

    “student_two”));

  4. mapStudent.insert(map<

    int, string>::value_type (3,

    “student_three”));


第三种:在insert函数中使用make_pair()函数,下面举例说明


  1. map<

    int, string> mapStudent;
  2. mapStudent.insert(make_pair

    (1,

    “student_one”));

  3. mapStudent.insert(make_pair

    (2,

    “student_two”));

  4. mapStudent.insert(make_pair

    (3,

    “student_three”));


第四种:用数组方式插入数据,下面举例说明

  1. map<

    int, string> mapStudent;
  2. mapStudent[1] =

    “student_one”;
  3. mapStudent[2] =

    “student_two”;
  4. mapStudent[3] =

    “student_three”;