C++ primer 修正 6.13.1的方法和疑问

9 views
Skip to first unread message

candid Qiu

unread,
Mar 7, 2006, 2:03:04 AM3/7/06
to ACE...@googlegroups.com
这里举例说明如何用set。
原例子:
typedef set< string >::difference_type diff_type;
set< string > exclusion_set;
ifstream infile( "exclusion_set" );
if ( ! infile )
{
    static string default_excluded_words[25] = {
    "the","and","but","that","then","are","been",
    "can","can't","cannot","could","did","for",
    "had","have","him","his","her","its","into",
    "were","which","when","with","would"
    };
    cerr << "warning! unable to open word exclusion file! -- "
    << "using default set\n";
    copy( default_excluded_words, default_excluded_words+25,
    inserter( exclusion_set, exclusion_set.begin() ));
}
else
 {
    istream_iterator\string,diff_type> input_set(infile),eos;
    copy( input_set, eos, inserter( exclusion_set,
    exclusion_set.begin() ));
}
 
我用stlport后发现有问题,见红色字样。
我查看了英文发现,原文也是这样?
 
我修正为:

 typedef set< string >::difference_type diff_type;
 set< string > exclusion_set;
 ifstream infile( "exclusion_set" );
 
 if ( ! infile )
 {
  static string default_excluded_words[25] = {
  "the","and","but","that","then","are","been",
  "can","can't","cannot","could","did","for",
  "had","have","him","his","her","its","into",
  "were","which","when","with","would"
  };

  cout << "warning! unable to open word exclusion file! -- "
  << "using default set\n";
  copy( default_excluded_words, default_excluded_words+25,
  inserter( exclusion_set, exclusion_set.begin() ));
 }
 else
 {
  istream_iterator<string> input_set(infile),eos;
  copy( input_set, eos, inserter( exclusion_set,
  exclusion_set.begin() ));
 }

 for(set< string >::iterator it=exclusion_set.begin(); it!=exclusion_set.end(); ++it)
 {
  cout<<"Set item is "<<*it<<"\n";
 }

疑问:
为什么要用到 typedef set< string >::difference_type diff_type???
 
注意:
还要用到的头文件为:
#include <stlport/algorithm>
#include <stlport/fstream>
#include <stlport/iterator>
#include <stlport/set>

邱戈川

unread,
Mar 7, 2006, 2:11:30 AM3/7/06
to 基于ACE和SpiderMonkey的SMS虚拟运营系统
没有变颜色,查找:
istream_iterator\string,diff_type> input_set(infile),eos;
这一行!

邱戈川

unread,
Mar 14, 2006, 1:34:26 AM3/14/06
to 基于ACE和SpiderMonkey的SMS虚拟运营系统
对于使用difference_type的原因:
如果你的编译器还不支持模板参数的缺省值那么需要给istream_iterator
构造函数提供一个显式的第二个
实参用于存放元素的容器的difference_type difference_type
是能够保存一个容器的两个iterator 减法结
果的类型例如在12.2
节中在不支持模板参数缺省值的编译器下的程序的表示中我们这样写
typedef vector<string,allocator>::difference_type diff_type;
istream_iterator< string, diff_type > input_set1( infile1 ), eos;
istream_iterator< string, diff_type > input_set2( infile2 );
在一个完全兼容标准C++的编译器下面我们可以简化为下面的代码
istream_iterator< string>, input_set1( infile1 ), eos;
istream_iterator< string>, input_set2( infile2 );
Reply all
Reply to author
Forward
0 new messages