Open In App

Map of Vector Struct and Struct Giving Error in C++ STL

Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisites:

A structure is a user-defined data type that groups together related data items of different data types. Structures are similar to classes, but they have some key differences. A vector is a container object that can store a sequence of values. It is similar to an array, but it can grow and shrink dynamically, allowing elements to be added or removed from the vector as needed. In C++, the data used can be of different types 

Vector of Struct

A vector of structs is a type of vector that can store a sequence of struct objects. Struct itself is very useful and if we can store multiple instances of structure binded together as one can be quite useful. vector of a struct can be quite useful for the reasons mentioned below:

  1. Multiple structures are bound together
  2. We can store as many structures as we want 
  3. Accessing and traversing all the structure is easy
  4. Manual insertion and deletion of elements 

Example:

Structure of Person:

So , if we want to store data about multiple person so rather than storing it as person1,person2 ,….personN , we can store all of them inside a vector ,where we can store N persons just by inserting data vector<struct> and accessing will be easy like person[i] rather than manually.

Below is the implementation of the above example:

C++




// C++ Program to implement
// vector of struct
#include <iostream>
#include <vector>
 
// Struct Declared
struct Person {
    std::string name;
    int age;
};
 
int main()
{
    // Create a vector of Person structs
    std::vector<Person> people;
 
    // Add some people to the vector
    people.push_back({ "John Doe", 30 });
    people.push_back({ "Jane Smith", 25 });
    people.push_back({ "Bob Johnson", 40 });
 
    // Print the name and age of each person
    for (const auto& person : people) {
        std::cout << person.name << " is " << person.age
                  << " years old." << std::endl;
    }
 
    return 0;
}


Output

John Doe is 30 years old.
Jane Smith is 25 years old.
Bob Johnson is 40 years old.

Map of  Vector Struct 

 A map of a vector of structs is a data structure that combines two container objects: a map and a vector. Using a map with a vector of structs can be useful when you need to manage a collection of related data that is organized into groups. The map allows you to easily create and manage these groups, and the vector of structs allows you to store the data for each group. This data structure provides a convenient way to access and manipulate the data, making it easy to add, remove, or update individual items in the collection.

Image Showing how Map of vector struct works

Image Showing how Map of vector struct works

Example:

We have coordinates collected together where x,y are defining collective data about the elements . So, we want to collect data showing similar result.

Let’s assume [{1,2}] show a particular result , [{3,4},{5,6}] show same result and [{7,8}] show a different result then to collect them and call them we can use map.

Below is the implementation of the above example:

C++




#include <iostream>
#include <map>
#include <vector>
 
using namespace std;
 
struct Data {
    int x;
    int y;
};
 
int main()
{
    // Define a map with integer keys and vector of Data
    // values.
    map<int, vector<Data> > mapOfVectors;
 
    // Add some elements to the map.
    mapOfVectors[0].push_back({ 1, 2 });
    mapOfVectors[1].push_back({ 3, 4 });
    mapOfVectors[1].push_back({ 5, 6 });
    mapOfVectors[2].push_back({ 7, 8 });
 
    for (auto it : mapOfVectors) {
        cout << "index:" << it.first << endl;
        for (auto a : it.second) {
            cout << a.x << " " << a.y << endl;
        }
    }
 
    return 0;
}


Output

index:0
1 2
index:1
3 4
5 6
index:2
7 8

This code creates a map object called map vectors that has integer keys and values that are vectors of Data structs. It then adds some elements to the map, iterates over the map and prints the elements, and finally returns 0 to indicate that the program executed successfully.

Reason for error: If you are trying to create a map of vector structs and getting an error in C++ STL, it is likely that you have not defined the < operator for the struct. The < operator is used by the map to compare and order the structs, and if it is not defined, you will get an error.

The solution to the problem: To fix this, you need to define the <, operator, declare struct in this way,

struct MyStruct {
    int a;
    int b;
    bool operator<(const MyStruct& other) const
    {
        // Define how the struct should be compared and
        // ordered here For example, you could use the
        // values of the 'a' and 'b' fields
        if (a != other.a)
            return a < other.a;
        return b < other.b;
    }
};

In this code, the < operator is defined for the MyStruct struct. The operator compares the a and b fields of the struct to determine the order and returns true if the struct should be considered less than the other struct, and false otherwise.

Once you have defined the < operator for the struct, you should be able to create a map of vector structs without any errors. 

Example:

C++




#include <iostream>
#include <map>
#include <vector>
 
using namespace std;
 
// Define the struct and the '<' operator
struct MyStruct {
    int a;
    int b;
    bool operator<(const MyStruct& other) const
    {
        if (a != other.a)
            return a < other.a;
        return b < other.b;
    }
};
 
int main()
{
    // Create a map of vector structs
    map<MyStruct, vector<MyStruct> > myMap;
     
    MyStruct temp={1,2};
 
    myMap[temp].push_back({ 1, 2 });
     
    temp={3,4};
    myMap[temp].push_back({ 3, 4 });
    myMap[temp].push_back({ 5, 6 });
     
    temp={7,8};
    myMap[temp].push_back({ 7, 8 });
 
    for (auto it : myMap) {
        cout << "index:" << it.first.a<<" "<<it.first.b << endl;
        for (auto arr : it.second) {
            cout << arr.a << " " << arr.b << endl;
        }
    }
 
    return 0;
}


Output

index:1 2
1 2
index:3 4
3 4
5 6
index:7 8
7 8


Last Updated : 05 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads