[英]How to populate map of string and pair of vectors of double
用这种类型的值填充的最佳方法是什么?
typedef std::map<std::string, std::pair<std::vector<double>, std::vector<double>>> buf;
所以,我需要这样的东西:
(“Label”, {1,2,3}, {100,200,300})
先感谢您!
上:所以,我来了。 但我认为它看起来不太好:
double a[] = {0.1, 0.2};
double b[] = {0.0, 0.0};
foo.insert( make_pair("box", make_pair(vector<double>(a, a + sizeof(a) / sizeof(a[0])), vector<double>(b, b + sizeof(b) / sizeof(b[0]))) ) );
您可以使用insert
typedef std::map<std::string, std::pair<std::vector<double>, std::vector<double>>> buf;
int main()
{
buf foo;
foo.insert({"Label", {{1,2,3}, {100,200,300}}});
}
请注意,您需要使用一个{}
来表示您的std::pair
。
有很多括号:
buf my_map { // <== whole map
{ // <== next individual map item
"Label", // <== key
{ // <== value
{1.0, 2.0, 3.0}, // <== value.first
{100.0, 200.0, 300.0} // <== value.second
}
}
};
将整个项目放在一行上时,该内容显示为:
buf my_map {
{"Label", {{1.0, 2.0, 3.0}, {100.0, 200.0, 300.0}}}
};
如果是C ++ 11或更高版本
buf x = {{"Label", {{1,2,3}, {100, 200, 300}}};
编辑
如果没有C ++ 11,如果您真的想用文字填充(如您的示例中所示),请创建辅助函数:
template <int N, int M>
std::pair<std::vector<double>, std::vector<double>> build_pair(double(&x)[N], double(&y)[M])
{
return std::make_pair(std::vector<double>(x, x + N), std::vector<double>(y, y + M));
}
您可以使用它:
double x[] = { 1, 2, 3 };
double y[] = { 100, 200, 300 };
b["Label"] = build_pair(x, y);
万一您认为向量已经存在并且在构造时不使用文字值初始化地图,那么通常会使用std::make_pair
创建向量对,以及键/值对进入地图。
#include <utility>
buf my_map;
my_map.insert(std::make_pair(label, std::make_pair(vector1, vector2)));
typedef std::map<std::string, std::pair<std::vector<double>, std::vector<double>>> buf;
buf mybuf {
{
"Label",
{
{1,2,3}, {100,200,300}
}
},
{
"Label2",
{
{4,5,6}, {400,500,600}
}
}
};
为了简化(使用编译时常量)填充映射的创建,我创建了以下模板:
#include <map>
#include <type_traits>
template<typename... Ts>
constexpr auto make_map(Ts&&... ts)
-> std::map<typename std::common_type_t<Ts...>::first_type,typename std::common_type_t<Ts...>::second_type>
{
return { std::forward<Ts>(ts)... };
}//---------------------------------------------------------
可以这样使用:
using namespace std;
auto myDict = make_map(make_pair(666,string("the number of the beast"))
,make_pair(667,string("the neighbor of the beast"))
);
将myDict创建为“ map <int,string>”。
或者在您的情况下使用它,如下所示:
using namespace std;
auto myDict = make_map(make_pair(string("label")
, make_pair(make_vector(1.,2.,3.)
,make_vector(100.,200.,300.)
)
)
);
(“ make_vector”的定义与“ make_map”非常相似)
make _...方法很有用(或至少“对我来说似乎是”),因为它通过从参数中获取类型来省略了显式的模板类型声明。
也许这在某种程度上也对其他人有所帮助(或至少鼓舞了:-))...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.