C++ 使用boost::variant库制作地图。如何以正确的类型存储和显示物品?
我试图使用boost::variant库创建一个映射,但似乎无法正确打印映射中的任何数据 代码: 我知道第一个变量被存储为int,因此它的类型是0,但是为什么它显示的值是0呢 第二个输出也是一样,只是我不明白为什么它被存储为bool,值是1(真)吗 感谢所有的帮助C++ 使用boost::variant库制作地图。如何以正确的类型存储和显示物品?,c++,boost,C++,Boost,我试图使用boost::variant库创建一个映射,但似乎无法正确打印映射中的任何数据 代码: 我知道第一个变量被存储为int,因此它的类型是0,但是为什么它显示的值是0呢 第二个输出也是一样,只是我不明白为什么它被存储为bool,值是1(真)吗 感谢所有的帮助 谢谢 第二个被存储为bool,因为它是比到std::string更基本的转换(编译器更喜欢const char*->bool而不是const char*->std::string)。由于指针为非null,因此它将布尔值赋值为true。
谢谢 第二个被存储为
bool
,因为它是比到std::string
更基本的转换(编译器更喜欢const char*
->bool
而不是const char*
->std::string
)。由于指针为非null,因此它将布尔值赋值为true。您可以在此处专门构造一个std::string
,以绕过默认转换
至于为什么数据输出不起作用,我唯一能怀疑的是,可能设置了
BOOST\u NO\u IOSTREAM
,导致它没有合适的运算符库,我尝试使用const char*而不是字符串,它工作得很好。整数输出问题实际上是一个类型。我试图输出一个不存在的对(myMap[“PAGE)SIZE1”]而不是myMap[“PAGE_SIZE”])。wrt示例代码:我认为在#include中指定boost版本目录不是一个好主意。将boost_1_55_0放入您的搜索路径,并将其从源中删除。依我拙见
#include <string>
#include <iostream>
#include "boost_1_55_0/boost/any.hpp"
#include "boost_1_55_0/boost/variant.hpp"
#include <map>
#include <list>
#include <complex>
#include <vector>
using namespace std;
int main()
{
std::map <string, boost::variant <int, double, bool, string> > myMap;
myMap.insert(pair<string, int>("PAGE_SIZE",2048));
myMap.insert(pair<string, boost::variant <int, double,bool, string> > ("PAGE_SIZE2", "hello, this is a string" )); //setup an enum to specify the second value maybe?
cout << "data page 1: " << myMap["PAGE)SIZE1"] << "\ntype page 1: " << myMap["PAGE_SIZE"].which() << endl;
cout << "data: " << myMap["PAGE_SIZE2"] << "\ntype: "<< myMap["PAGE_SIZE2"].which()<< endl;
return 0;
}
data page 1: 0
type page 1: 0
data page 2: 1
type page 2: 2