【问题标题】:In c++, how can I retrieve the values from a vector in the same order they would be retrieved from a map?在 C++ 中,如何以与从地图中检索的顺序相同的顺序从向量中检索值?
【发布时间】:2015-07-03 12:46:30
【问题描述】:

我正在编写将对象存储到map<string, vector<T> > 中的代码。这张地图是用数据迭代填充的,这些数据被分析,然后在一个大循环中写入文件。在该循环之前,我打开文件以写出每一列的内容,例如# time var1 var2 var3。问题是,我需要在标题中可靠地写入var1var2var3 等...,其顺序与从地图中检索它们的顺序相同。我现在正在使用一个丑陋的解决方法,带有一个向量:

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,它们是大循环开始时的值。

【问题讨论】:

  • 不能只对向量进行排序,然后从头到尾依次输出吗?
  • var1等从何而来?键在地图中吗?

标签: c++ sorting dictionary vector


【解决方案1】:

为什么不遍历地图本身呢?这将保证您以与地图本身相同的顺序检索它,因为它是地图本身的顺序:

std::map<std::string, std::vector<T> > m = ...;

for (const auto& item : m)
{
    outputfile << item.first << " ";
}

Ideone example.

【讨论】:

  • 这是个好主意。然后我可以清除大循环开头的map
【解决方案2】:

std::map 使用 std::less(如果您将比较器指定为模板参数,则使用自定义比较器)按键对其条目进行排序。如果您想将 std::vector 中的条目与它们在地图中的顺序相同,只需在其上使用 std::sort

【讨论】:

    【解决方案3】:

    我不确定你想做什么,但这是我的建议:

    首先,最好编写自己的小类(或结构,如果需要)作为变量的容器,如下所示:

    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;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-09
      • 2013-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多