gpt4 book ai didi

c++ - 真正的动态 vector 类型

转载 作者:行者123 更新时间:2023-11-28 06:10:32 26 4
gpt4 key购买 nike

有没有标准的方法来改变容器内部的类型,比如 std::vector?这方面的一个例子是:

std::vector<std::string> v;

v.insert("hi");

然后以某种方式更改类型并添加:

v.insert(1);

非常类似于解释器语言如何能够在列表/数组中拥有多种类型

我知道 vector 本身并不会这样做,但是我不知道如何在不使用像 boost 这样的第三方库的情况下绕过它,即使这样我也没有方向。

我创建了一个示例代码来展示一种键值数据方法。它确实有效,但是中间的(非工作)评论部分是我试图实现的想法。

#include <iostream>
#include <iterator>
#include <vector>
#include <map>
#include <string>
#include <typeinfo>

using namespace std;

int main()
{
typedef std::map<std::string, std::string> map_type;
typedef std::vector<map_type> vector_type;
typedef std::map<std::string, map_type> map_keyobj_type;
vector_type stack;
vector_type::iterator it = stack.begin();

//First map
map_type stringmap;
stringmap.insert(map_type::value_type("I'm a string", "Also a String"));
it = stack.insert(it, stringmap);

//Second wanted map, example code of what is wanted
/*
map_keyobj_type secondlayer;
map_type secondlayervalue;
secondlayervalue.insert(map_type::value_type("String from inside map", "That too string"));
secondlayer.insert(map_keyobj_type::value_type("List", secondlayervalue));
stack.insert(it, secondlayer);
*/

map_type stringmap2;
stringmap2.insert(map_type::value_type("String after map map", "Also string"));
it = stack.insert(it, stringmap2);


//prints stack, only supports map_type
//Iterates backwards to get top-down input correct.
for (int i = stack.size()-1; i > -1; --i)
{
//Print map_type
if (typeid(stack[i]).name() == typeid(map_type).name())
{
for (map_type::const_iterator ite = stack[i].begin(); ite != stack[i].end(); ++ite)
{
cout << ite->first << " : " << ite->second << "\n";
}
}
}

//return 0;
}

最佳答案

您可以使用 boost::any,诀窍是您需要知道您保存的是什么类型才能将其取出。这也是非常低效的,如果你关心的话,因为它节省了几个指针你的整数而不是一个整数。

您可以使用有区别的 union 。这是一个包含枚举和 union 的结构。枚举告诉您的代码 union 中保存的是什么类型。

您提到了解释性语言。他们中的大多数使用discriminated union方法。查看 Python 中的 PyObject 或 Perl 的 SV。

关于c++ - 真正的动态 vector 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31362201/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com