BillyJean
BillyJean

Reputation: 1587

Storing objects in an std::map

I'd like to store objects of a class in an std::map. Here is a working example showing how I am doing it currenty

#include <iostream>
#include <map>

class A
{
private:
  int a;
  std::string b;

public:
  A(int init_a, std::string init_b) : a(init_a), b(init_b){};  
  void output_a() {std::cout << a << "\n";}
};

int main()
{
  std::map<size_t, A> result_map;
  for (size_t iter = 0; iter < 10; ++iter)
  {
    A a(iter, "bb");
    result_map.insert(std::make_pair(iter, a));
  }

  return 0;
}

I have two question to this example:

  1. Is this the professional C++-way to store objects in an std::map in the above case? Or should I create a pointer to an object of A and store that instead? I like the first (current) option as I don't have to worry about memory management myself by using new and delete - but most importantly I'd like to do things properly.

  2. How would I go about calling a member function of, say, result_map[0]? I naively tried result_map[0].output_a(), but that gave me the error: error: no matching function for call to ‘A::A()’

Upvotes: 1

Views: 7431

Answers (2)

user5880324
user5880324

Reputation:

1- It depends: If your class can be copied and you're not worried about performance issues with copying objects into the map, then that's a good way to do it. However, if say your class held any immutable data (std::mutex for example) you'd have to use a pointer, as the copy constructor c++ automatically generates would be ill formed, so it merely wouldn't be able to copy the class

2- result_map.at(0).output_a() or result_map.at(0)->output_a() if you're using a map of pointers

Upvotes: 0

Slava
Slava

Reputation: 44278

Is this the professional C++-way to store objects in an std::map in the above case?

It is fine, simpler code could be:

result_map.emplace(iter, A(iter, "bb") );

you should use whatever you find more readable. By the way calling integer counter iter is not a way to write a readable code.

How would I go about calling a member function of, say, result_map[0]?

You better use std::map::find:

auto f = result_map.find( 0 );
if( f != result_map.end() ) f->output_a();

problem with operator[] in your case - it has to create and instance if object does not exist with that index but you do not have default ctor for A.

Upvotes: 5

Related Questions