1

I am trying to achieve the creation of such a map. The following code attempts to do this

#include <list>
#include <map>
#include <string>

class IntWithString {
private:
  int a;
  std::string s;

public:
  IntWithString(int a, std::string s) : a(a), s(s) {}
  std::string getString() { return s; }
  int getInt() { return a; }
};

namespace {
std::map<std::string, std::list<IntWithString *> > m;
}

void appendMap(IntWithString *a) {
  auto it = m.find(a->getString());
  if (it != m.end()) {
    m[a->getString()].push_back(a);
  } else {
    std::list<IntWithString *> l;
    l.push_back(a);
    m[a->getString()] = l;
  }
}

int main() {
  IntWithString a(10, "ten");
  IntWithString b(11, "ten");
  appendMap(&a);
  appendMap(&b);
  return 0;
}

However when looking at the map m with the debugger I am getting a map that maps "ten" to a list of size 0. What I would like is a list of size 2.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • Do you really want a `std::list`? Generally you do not want to store pointers in a standard container, and if you do, generally you should use a smart pointer so that the container can manage it's lifetime. – NathanOliver Jun 07 '19 at 13:51
  • 1
    I cannot reproduce the problem with MS VS 2017. `m` consists of a single element with list of two pointers as a value. – vahancho Jun 07 '19 at 13:54
  • I'm not really sure what you're trying to achieve here, but the code behaves correctly. – Jabberwocky Jun 07 '19 at 13:58
  • Of topic but... doesn't your `appendMap` implementation basically reduce to `m[a->getString()].push_back(a);` since `m[a->getString()]` will default construct an `std::list` if an entry doesn't already exist for the key in question? – G.M. Jun 07 '19 at 14:04
  • 1
    Have you considered using `std::multimap` here? – Paul Sanders Jun 07 '19 at 14:32

1 Answers1

0

I am not sure what you mean. If I do:

std::cout << m.size() << ", " << m["ten"].size() << std::endl;

I get this output:

1, 2

which is a map with one key ("ten"), and two values for that key (10 and 11), as expected.

Live demo

PS: Storing pointers in a container like this is a bit uncommon in C++. If you really want to do this though, consider to use Smart Pointers.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • Ok, this is strange. I get the same output as you. BUT lldb tells me that it is a map with one key and a the sizeof the list is zero. –  Jun 07 '19 at 14:08
  • @HMPARTICLE strange indeed, however I do not know why, and I am about to board my flight. Sorry. – gsamaras Jun 07 '19 at 15:27