我有一个 vector 模式,其 setter/getter 如下所示:
vector<A>& getA() const { return a; }
vector<B>& getB() const { return b; }
vector<C>& getC() const { return c; }
...
我对具有某种类似于
vector<T>& getByName(string s) const
的功能很感兴趣,这样我就可以通过这种方式调用该功能:getByName("A")
,getByName("B")
等。我尝试使用无序 map ,但没有找到任何合适的方法来制作像这样的线:
unordered_map< string, vector<T> >
。A,B,C ...是完全不同的结构,因此多态解决方案不是我想要的。
由于
vector<T>
是一个具有固定大小的容器(如果我没记错的话,则为24个字节),所以我不明白为什么无论 vector 的类型如何,映射都无法将这些字节存储在内存中。
最佳答案
As vector is a container with a fixed size (24 bytes if I'm not wrong), I don't see why the map is not able to store those bytes somewhere in memory no matter the vector's type.
因为C++是一种强类型语言,并且
vector<A>
,vector<B>
和vector<C>
类型的大小相同,这一事实并不重要,因为它们是不同的类型。pair<int16_t, int16_t>
与int32_t
的大小相同(在大多数实现中),但这并不能使它们互换。您可能(我想)有一个
map<string, variant<...>
或map<string, any>
,但这将需要您自己管理所有类型。[后来]
I'm interesed in having some kind of function like
vector<T>& getByName(string s)
这种函数的问题在于,您必须(在编译时)指定函数将返回的类型。您希望让返回类型由在运行时传递给函数的参数的值确定。
关于c++ - 是否可以使用vector <T>作为值来定义unordered_map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59726904/