c++ map 示例_C ++ Map用示例解释

c++ map 示例

map is a container that stores elements in key-value pairs. It's similar to collections in Java, associative arrays in PHP, or objects in JavaScript.

map是一个以键值对形式存储元素的容器。 它类似于Java中的集合,PHP中的关联数组或JavaScript中的对象。

Here are the main benefits of using map:

这是使用map的主要好处:

  • map only stores unique keys, and the keys themselves are in sorted order

    map仅存储唯一键,并且键本身按排序顺序

  • Because the keys are already in order, searching for an element is very fast

    因为键已经按顺序排列,所以搜索元素非常快
  • There is only one value for every key

    每个键只有一个值

Here is an example:

这是一个例子:

#include <iostream>
#include <map>

using namespace std;

int main (){
  map<char,int> first;
  
  //initializing
  first['a']=10;
  first['b']=20;
  first['c']=30;
  first['d']=40;
  
   map<char, int>::iterator it;
   for(it=first.begin(); it!=first.end(); ++it){
      cout << it->first << " => " << it->second << '\n';
   }
   
  return 0;
}

Output:

输出:

a => 10
b => 20
c => 30
d => 40

创建map对象 (Creating a map object)

map<string, int> myMap;

map<string, int> myMap;

插入 (Insertion)

Inserting data with insert member function.

使用插入成员函数插入数据。

myMap.insert(make_pair("earth", 1));
myMap.insert(make_pair("moon", 2));

We can also insert data in std::map using operator [] i.e.

我们还可以使用运算符[]将数据插入std :: map中,即

myMap["sun"] = 3;

myMap["sun"] = 3;

访问map元素 (Accessing map elements)

To access map elements, you have to create iterator for it. Here is an example as stated before.

要访问地图元素,您必须为其创建迭代器。 这是前面所述的示例。

map<char, int>::iterator it;
for(it=first.begin(); it!=first.end(); ++it){
  cout << it->first << " => " << it->second << '\n';
}

翻译自: https://www.freecodecamp.org/news/c-plus-plus-map-explained-with-examples/

c++ map 示例

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值