【问题标题】:Ordering using stl sort in Visual Studio and GCC在 Visual Studio 和 GCC 中使用 stl sort 进行排序
【发布时间】:2011-10-25 23:13:23
【问题描述】:

编写应该在 Linux 和 Windows 环境中可移植的程序我发现在使用 Visual Studio 和 gcc 编译时,STL 排序功能存在问题。 为了对复杂数据结构的向量进行排序,我为这种形式的结构编写了一个 int 转换运算符:

struct result
{ 
public :
  int Gene_a;
  int Gene_b;
  std::vector<int> score;
  float total_score;
  operator int() {return total_score;}
}

在这种情况下,我在 Visual Studio 中使用标准整数排序算法没有问题:

sort(results.rbegin(),results.rend());

但是当尝试使用 GCC(实际上是 g++)编译时,会导致有趣的错误。 为了避免这种情况,我似乎必须编写一个排序函数:

 inline bool better (result a, result b)
 {
   return a.total_score > b.total_score;
 }

并以如下形式调用排序:

sort(results.begin(),results.end(),better);

我是在使用标准 C++ 之外的东西还是缺少 g++ STL 实现? 是不是可以让g++明白struct的vector等价于int的vector?

这里有一个简短的主要说明错误:

#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) 
{
  vector<result> r;           // define a vector of struct
  for (int i=0;i<10;i++)      // fill up with data
  {
    result a;
    a.Gene_a=i;
    a.Gene_b=2*i;
    for(int j=0;j<i;j++)
      a.score.push_back(i); // fill the int vector in the struct
    a.total_score=i;
    r.push_back(a);
  }
  // sort(r.rbegin(),r.rend()); // this line will fail in g++
  sort(r.rbegin(),r.rend(),better);
  for (int i=0;i<10;i++)      // demonstrate that the int operator works
    cout << (int)r[i] << endl;
}// End main

【问题讨论】:

  • 什么版本的g++?有哪些有趣的错误?您能想出一个演示错误的最小示例吗? g++ 4.5.1 毫无怨言地接受以下内容:struct X { operator int() const { return 42; } }; int main() { std::vector&lt;X&gt; v; std::sort(v.begin(), v.end()); }
  • g++ 版本是 4.6.1 结构是:struct result { public : int Gene_a; int Gene_b; std::vector&lt;int&gt; score; float total_score; operator int() {return total_score;}} 在编译时这给了我很多错误。如果您确实需要,我可以尝试为您制作屏幕转储。
  • 为什么要进行屏幕转储?编辑您的问题并将代码和错误消息复制并粘贴到问题的文本中。
  • 错误在哪里长(字符串屏幕),但我会将代码放在问题中。
  • 请复制并粘贴您遇到的编译错误。如果可能,请给我们一个完整但最少的源代码清单,以重现该问题。

标签: c++ visual-c++ stl g++


【解决方案1】:

我看到的两种比较方法之间唯一有意义的区别是,当元素为const 时,第二种方法将起作用。第一个应该是:

//             vvvvv
operator int() const

即使您正在修改容器,您的比较仍然要求它适用于 const 对象。在您的情况下,实现使用了该假设并且出现了错误。

但这不重要,因为对容器及其元素进行排序需要可修改...

【讨论】:

  • 但是当比较元素时,它们不应该被修改,所以实现可能是正确的。 (错误发生在‘const _Tp&amp; std::__median(const _Tp&amp;, const _Tp&amp;, const _Tp&amp;) [with _Tp = result]’
  • @visitor:是的,我就是这么想的。我只是不确定是否允许实现在变异算法中假设元素可以被视为 const。无论哪种方式,const 都是罪魁祸首。我会相信 GCC 在这个问题上。谢谢。
  • @GBBL:什么错误?您需要复制并粘贴错误消息,它们会准确地告诉您问题所在。
  • 好的,我现在已经完成了最后的检查!实际上使用 const 错误消失了!尝试在 Linux、MacOsX 和... Windows 上使用 MiniGW。感谢 GMan 和所有其他人!
猜你喜欢
  • 1970-01-01
  • 2020-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-26
相关资源
最近更新 更多