用这种类型的值填充的最佳方法是什么?
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
。
如果是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);
有很多很多大括号:
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}}}
};
如果您的意思是向量已经存在,并且您在构造时没有使用文字值初始化映射,那么您通常会使用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<整数、字符串>"。
或者像这样使用:
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_……方法是有帮助的(或者至少"对我来说似乎是"),因为它通过从形参中获取类型而省略了显式的模板类型声明。
也许这对其他人也有帮助(或者至少是鼓舞人心的:-))…