Map of Vectors in C++ STL with Examples

Map in STL Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values.

Vector in STL Vector is same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators.

Map of Vectors in STL: Map of Vectors can be very efficient in designing complex data structures.

Syntax:

map<key, vector<datatype>> map_of_vector;
OR
map<vector<datatype>, key> map_of_vector;

For example: Consider a simple problem where we have to check if a vector is visited or not.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to demonstrate
// use of map for vectors
  
#include <bits/stdc++.h>
using namespace std;
  
map<vector<int>, int> vis;
  
// Print True if vector is visited
// or False if not visited
void CheckVisited(vector<int> data)
{
    if (vis.find(data) != vis.end()) {
        cout << "True" << endl;
    }
    else {
        cout << "False" << endl;
    }
}
  
// Driver code
int main()
{
    // Initializing some vectors
    vector<int> data_1{ 10, 20, 30, 40 };
    vector<int> data_2{ 5, 10, 15 };
    vector<int> data_3{ 1, 3, 5, 7, 9, 11, 13 };
  
    // Making some vectors as visited
    vis[data_1] = 1;
    vis[data_2] = 1;
    vis[data_3] = 1;
  
    // checking if these vectors are
    // visited or not
    vector<int> check_1 = { 5, 10, 15 };
    vector<int> check_2 = { 2, 4, 6, 8, 10, 12 };
  
    CheckVisited(check_1);
    CheckVisited(check_2);
  
    return 0;
}

chevron_right


Output:

True
False

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


4


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.