Home > OS >  How to iterate through map when pass a class to map
How to iterate through map when pass a class to map

Time:02-04

I am writing a simple code that. I've created two objects from class Employee that have two method. getData() and displayData(), and I've made a map of Employee type. It is taking input but to iterate through map by calling the displayData() that is in class.

Here is the code. Ive got the error that error: 'struct std::pair<const int, Employee>' has no member named 'displayData'

Any suggestions or am i doing it wrong.

#include <iostream>
#include <map>

using namespace std;
class Employee {
    private:
       int id; 
       string name;
    public :
       void getData(){
          cin >> id >> name;
       }
    
       void displayData(){
          cout << id <<" "<<name<<endl;
       }
  };

int main() {

    map<int, Employee> m1;
    map<int, Employee> :: iterator it;
    Employee e1,e2;

    //for (i)
    e1.getData();
    m1[1] = e1;
    e2.getData();
    m1[2] = e2;

    for (it = m1.begin(); it!=m1.end();   it){
       cout << (*it).first.displayData() << (*it).second.displayData() <<endl;
    }

    return 0;

 }

Thanks for the help in advance

CodePudding user response:

Here is the code. Ive got the error that error: 'struct std::pair<const int, Employee>' has no member named 'displayData'

The compiler tells you exactly what is wrong, you may have a Misconception about std::maps, std::maps holds a key-value pair(More details About Maps) which is a std::pair which can be accessed via an iterator or the value accessed directly via map[key]. iterator::first holds the key which in your code is an int, while iterator::second holds the value which in your case right now is an object called Employee, hence (*it).first.displayData() error.

This line is also incorrect, and would produce compiler errors.

cout << (*it).first.displayData() << (*it).second.displayData() <<endl;

(*it).second.displayData() will return the return type of the function since this is a function call, in this case a type of void. You can simply call the function like this to achieve your desired result in every iteration.

std::cout << it->first << " ";
it->second.displayData();

Always trust compiler errors.

CodePudding user response:

In C 17, you can use structured bindings for more readbility:

for (auto [eid, employee] : m1)
{
    std::cout << eid << ": ";
    employee.displayData();
}
  •  Tags:  
  • c
  • Related