C ++ Struct, which contains a map of itself

A simple question: how do I get this to work?

struct A {
    double whatever; 
    std::unordered_map<std::string, A> mapToMoreA; 
}

g ++ error: std :: pair <_T1, _T2> :: second is of an incomplete type

As far as I understand, when creating an instance of a map, the compiler must know the size of A, but it does not know this, because the map is declared in the declaration of A, so this is the only way around this using pointers to A (I don’t want to do this)?

+5
source share
7 answers

(, , , ). -, std::unordered_map , . GCC std::map .

, . , std::vector -

template <typename T> class my_vector {
  T *begin;
  T *end;
  ...
};

T, T . my_vector T

class X;
my_vector<X> v; // OK

"" , (, , ) my_vector.

, - T , chahge

template <typename T>
class my_vector {
  T *begin;
  T *end;
  T dummy_element;
  ...
};

T , my_vector

class X;
my_vector<X> v; // ERROR, incomplete type

- . unordered_map, , - A. (, ).

unordered_map A . A. , unordered_map Boost.

+2

STL-, , . -, :

struct A {
    struct B { double whatever; }; 
    std::unordered_map<std::string, B> mapToB; 
};

: , .

struct A {
    double whatever;
    std::unordered_map<std::string, std::unique_ptr<A>> mapToMoreA; 
};

boost::unordered_map, , Visual Studio, Microsoft std::unordered_map - . gcc .

+2

Boost.Variant , – boost::recusive_wrapper<>. :

struct A {
    double whatever; 
    std::unordered_map<std::string, boost::recursive_wrapper<A>> mapToMoreA; 
};

, Boost.Variant ++ 11. : Boost 1.56.

+1

. void * ( ). , std:: unordered_map, .

0

++ :

, , , : * -> delete - .

struct A
{
    double bla;
    std::map<std::string, A*> mapToMoreA;
};

- A struct , A :

struct A
{
    double bla;
    std::map<std::string, A*> mapToMoreA;
    void doStuff(const std::string& str);
};

void A::doStuff(const std::string& str)
{
    mapToMoreA[str] = new A();
}
0

, , :

struct A {
  struct hidden;
  std::unique_ptr<hidden> pimpl;
};

struct A::hidden {
  double whatever;
  std::unordered_map<std::string, A> mapToMoreA;
};
0

, struct A; , .

: , , , , , :

#include <boost/unordered_map.hpp>                                                                                      
#include <string>
#include <iostream>

struct A;

struct A {
    double whatever;
    boost::unordered_map<std::string, A> mapToMoreA;
};

int main(void)
{
    A b;
    b.whatever = 2.5;
    b.mapToMoreA["abc"] = b;
    std::cerr << b.mapToMoreA["abc"].whatever << std::endl;
    return 0;
}

g++ 4.2.1 mac "2.5" ( ).

, unordered_map boost. ? (.. std::unordered_map - , boost ?) , . , , , . !

-2

All Articles