首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

关于C++泛型算法的一个编译有关问题,求指点!

2013-08-04 
关于C++泛型算法的一个编译问题,求指点!!!#include iostream#include list#include fstream#include

关于C++泛型算法的一个编译问题,求指点!!!

#include <iostream>
#include <list>
#include <fstream>
#include <algorithm>
#include <string>
using namespace std;

bool isShorter (const string &s1, const string &s2)
{
return s1.size() < s2.size();
}

int main (int argc, char **argv)
{
if (argc < 2)
{
cout << "No input file!" << endl;
return EXIT_FAILURE;
}

ifstream inFile;
inFile.open (argv[1]);
if (!inFile)
{
cerr << "Can not open input file!" << endl;
return EXIT_FAILURE;
}
list<string> words;
string word;

while (inFile >> word)
   words.push_back (word);
   
words.sort();
words.unique();
stable_sort (words.begin(),words.end(), isShorter);   //我觉得是这里的调用出问题了,但是不知道出在哪里??

cout << "unique words: " << endl;
for (list<string>::iterator iter = words.begin(); iter != words.end(); ++iter)
   cout << *iter << " ";
cout << endl;

return 0;
}


编译时,弹出一个<stl_algo.h>的头文件里报错,报的错误如下,我摘的一段,但我不咋看得懂,求解释下,谢谢了!!
 /// This is a helper function for the stable sorting routines.
  template<typename _RandomAccessIterator, typename _Compare>
    void
    __inplace_stable_sort(_RandomAccessIterator __first,
  _RandomAccessIterator __last, _Compare __comp)
    {
      if (__last - __first < 15)   //显示的这里出错!!!
{
  std::__insertion_sort(__first, __last, __comp);
  return;
}

这个帖子我散的分,但是好像散错地方了,http://bbs.csdn.net/topics/390519511?page=1#post-395053704 泛型 算法 C++


[解决办法]
sort和stable_sort都要求随机访问迭代器,list::iterator是顺序访问迭代器,不能用它们排序。
改为:

words.sort(isShorter);

也是稳定的归并排序,而且是保证空间复杂度O(1)时间复杂度O(N*Log(N))的。
[解决办法]
sort需要RandomAccessIterator。list的iterator不是random access的。

热点排行