Associative arrays in C++


In c++ programming language, an associative array is a special type of array in which the index value can be of any data type i.e. it can be char, float, string, etc. These associative arrays are also known as maps or dictionaries. Also, the indexes are given a different name which is key and the data that is stored at the position of the key is value.

So, we can define the associative array as a key-value pair.

Let's define an associative array of bikes and their top speed.

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

Example

 Live Demo

#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;
}

Output

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

Updated on: 24-Oct-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements