有沒有一種標準的方式來改變容器內的類型,如std :: vector? 這方面的一個例子是具有:真正的動態矢量打字
std::vector<std::string> v;
v.insert("hi");
然後改變類型某種程度上和添加:
v.insert(1);
非常相似,如何解釋語言能夠有多種類型在列表/陣列
我知道載體本身並不這樣做,但是我失去了如何避免使用第三方庫如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](http://www.boost.org/doc/libs/1_58_0/doc/html/any.html)。最好的方式去。 –
隨着模板的工作方式,這不是微不足道的。查看JSON庫的做法。 –
使用'boost :: any'或者阻止你自己的一個類似的函數。但是,請記住,如果您想要抵消它,除非您的任何類在編譯時具有了解該類型的魔術功能,否則您將必須進行類型轉換... – Joe