【问题标题】:list<pair<float,float>> iterating through a list that holds pairs?list<pair<float,float>> 遍历包含对的列表?
【发布时间】:2020-02-02 13:12:01
【问题描述】:

作为运行时分析的一部分,我有一个小游戏,它在计算每个帧后都会在此列表中添加一个新元素:

typedef std::list<std::pair<float, float>> PairList;

PairList Frames; //in pair: index 0 = elapsed time, index 1 = frames 

txt 文件稍后用于绘制图形。 我决定使用列表,因为在玩游戏时我不需要处理列表中保存的数据,而且我认为列表是仅添加或删除项目时最快的容器。作为下一步,我想将帧写入外部 txt 文件。

void WriteStats(PairList &pairList)
{
    // open a file in write mode.
    std::ofstream outfile;
    outfile.open("afile.dat");

    PairList::iterator itBegin = pairList.begin();
    PairList::iterator itEnd = pairList.end();

    for (auto it = itBegin; it != itEnd; ++it)
    {
        outfile << *it.first << "\t" << *it.second;
    }
    outfile.close();

}

对于普通列表,指向“it”的指针应该返回项目对吗? 除了visual studio说pair&lt;float, float&gt;*没有一个叫first的成员 当通过我的迭代器访问不起作用时,我想怎么做?是不是因为我传入了对列表的引用?

【问题讨论】:

  • (1,2) (3,4) (5,6) 的输出将是 1\t23\t45\t6 ... 可能难以解析为输入。

标签: c++ list iterator


【解决方案1】:

*it.first 被解析为*(it.first)

你需要(*it).first,或者,更好的是it-&gt;first

或者,更好的是使用范围:

for (auto& elem : pairList)
{
    float a = elem.first;
}

我决定使用列表,因为 [...] 我认为列表是最快的容器,仅用于添加或删除项目。

第一个首选容器应该是std::vector。在实践中,即使在纸面上由于缓存局部性而在 std::list 上应该更快的算法上,它也会优于 std::list。所以如果性能是一个问题,我会用一个很好的基准测试你的理论。

【讨论】:

  • 每个选项都能完美运行,谢谢。事实上,我用列表和向量做了一些测试。使用 iota() 函数将 100 万个元素添加到向量时,所需时间比添加到列表的时间长 86 倍。不过,这是一个很小的差异,当您要计算每个元素时,+1 向量的速度要快 6000 倍以上。
  • @onefriendlyprogrammer 这些结果看起来非常非常可疑。您应该仔细检查您的测试方法。
【解决方案2】:

问题是operator precedence 之一。具体来说,成员访问运算符'.'比间接 '*' 具有更高的优先级,因此 *it.first 被有效地解析为...

*(it.first)

因此发出警告。而是使用...

it->first

【讨论】:

    【解决方案3】:

    使用 range-based for loop 而不是使用迭代器:

    void WriteStats(const PairList &pairList)
    {
        // open a file in write mode.
        std::ofstream outfile("afile.dat");
    
        for (const auto &elem : pairList) {
          outfile << elem.first << "\t" << elem.second << '\n';
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-30
      • 1970-01-01
      • 2015-07-17
      • 1970-01-01
      • 2020-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多