我正在编写一个将对象存储到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的答案,在这里初始化映射,然后清除大循环开头的值vectors。
发布于 2015-04-24 19:21:12
为什么不迭代一下地图本身呢?这将确保您以与地图本身相同的顺序检索它,因为它是映射本身的顺序:
std::map<std::string, std::vector<T> > m = ...;
for (const auto& item : m)
{
outputfile << item.first << " ";
}发布于 2015-04-24 19:25:05
std::map使用std::less (如果您指定一个自定义比较器作为模板参数)按键对其条目进行排序。如果要将std::vector中的条目按映射中的相同顺序放置,只需在其上使用std::sort即可。
发布于 2015-04-24 19:37:12
我不知道你想做什么,但以下是我的建议:
首先,最好将自己的小类(如果需要的话是struct )编写为变量的容器,如下所示:
class Variable final
{
public:
int variable1;
int variable2;
int variable3;
};然后,您应该使用所需的助手函数编写一个容器。
class Variables final
{
public:
void add( const Variable& variable )
{
data.push_back( variable );
}
void write( const std::string& filename )
{
std::ofstream outputfile( filename );
// Write the header texts. This is always the same.
writeHeader( outputfile );
// Write the data in a loop.
writeData( outputfile );
}
private:
void writeHeader( std::ofstream& file ) { ... }
void writeData( std::ofstream& file ) { ... }
private:
std::list< Variable > data;
};https://stackoverflow.com/questions/29855526
复制相似问题