我正在编写一个将对象存储到map<string, vector<T> >
的代码。该映射迭代地填充数据,分析数据,然后以大循环写入文件。在该循环之前,我打开文件以写出每列的内容,例如# time var1 var2 var3
。问题是,我需要在标题中可靠地写入var1
,var2
和var3
等...,它们将从地图中检索它们的顺序。我现在使用一个丑陋的解决方法,使用矢量:
std::vector<std::string> header_names;
header_names.push_back("var1");
header_names.push_back("var2");
header_names.push_back("var3");
std::map<std::string, std::string> headers;
for(int i = 0; i < header_names.size(); i++) {
headers[header_names[i]] = header_names[i];
}
std::ofstream outputfile("out.txt");
outputfile << "# time ";
for(auto it = headers.begin(); it != headers.end(); ++it) {
outputfile << it->first << " ";
}
有没有更好的方法来实现相同的结果?
编辑:
使用@Claudiu的答案,我初始化地图,然后清除vector
s,它们是大循环开头的值。
答案 0 :(得分:4)
为什么不迭代地图本身?这将保证您以与地图本身相同的顺序检索它,因为它是地图本身的顺序:
std::map<std::string, std::vector<T> > m = ...;
for (const auto& item : m)
{
outputfile << item.first << " ";
}
答案 1 :(得分:0)
std::map
使用std::less
按键对其条目进行排序(如果指定一个作为模板参数,则使用自定义比较器)。如果您想将std::vector
中的条目与他们在地图中的顺序相同,只需在其上使用std::sort
即可。
答案 2 :(得分:0)
我不确定你想做什么,但这是我的建议:
首先,最好将自己的小类(或结构,如果你想)编写为变量的容器,如下所示:
class MyController {
static responseFormats = ['json']
def get() {
MyCommand command = bindData(new MyCommand(), params)
command.validate()
if (command.hasErrors()) {
...
}
else {
//...do stuff with command object
}
}
@Validateable
class MyCommand {
Long resourceId
Date startDate
Date endDate
static constraints = {
resourceId nullable: false
startDate nullable: false
endDate nullable: false
}
}
}
然后你应该编写一个包含所需辅助函数的容器。
class Variable final
{
public:
int variable1;
int variable2;
int variable3;
};