c++ - 是否可以使用vector <T>作为值来定义unordered_map?

标签 c++ templates vector stl unordered-map

我有一个 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/

相关文章:

c++ - 线程同步101

Django {% with %} 标签在 {% if %} {% else %} 标签内?

c++ - vector.size() 始终返回 0

C++:使用迭代器调用 Vector::erase

c++ - 如何使用 erase() 函数通过索引删除 vector ?

c++ - 调用模板类的构造函数

c++ - 模板将运算符转换为指向成员函数语法的指针如何工作

c++ - 需要类型名错误(模板相关错误)

c++ - 如何存储/检索成员函数指针以用作模板参数?

c++ - 尽管存在专用函数,但是否可以调用非专用模板函数?