C ++中的关联数组

在c ++编程语言中,关联数组是一种特殊的数组,其中的索引值可以是任何数据类型,即可以是char,float,string等。这些关联数组也称为映射或字典。同样,索引被赋予一个不同的名称,它是键,而存储在键位置的数据是值。

因此,我们可以将关联数组定义为键值对。

让我们定义一个自行车及其最高速度的关联数组。

Bike top speed
Ninja 290
S1000rr 310
Bullet 127
Duke 135
R1 286

示例

#include <bits/stdc++.h>
using namespace std;
int main(){
   map<string, int> speed{ { "ninja", 290 },
   { "s1000rr", 310 }, { "bullet", 127 },
   { "Duke", 135 }, { "R1", 286 } };
   map<string, int>::iterator i;
   cout << "The topspeed of bikes are" << endl;
   for (i = speed.begin(); i != speed.end(); i++)
   cout<<i->first<<" "<<i->second <<endl;
   cout << endl;
   cout << "The top speed of bullet is "<< speed["bullet"] << endl;
}

输出结果

The topspeed of bikes are
Duke    135
R1      286
Bullet  127
ninja   290
s1000rr 310
The top speed of bullet is 127