c++泛型算法


#include "algs_preamble.h"
#include <fstream>
using std::ifstream;
#include <cstddef>
using std::size_t;

// comparison function to be used to sort by word length
bool isShorter(const string &s1, const string &s2)
{
 return s1.size() < s2.size();
}

// determine whether a given word is greater than length 6
// will reimplement later as a more general version using function objects
bool GT6(const string &s)
{
 return s.size() >= 6;
}

inline double
percent(double numerator, double denominator)
{
 return 100 * numerator/denominator;
}

// report number of words greater than 6
// later chapter will reimplement to be more general
void report_complexity(vector<string>::iterator beg,
                       vector<string>::iterator end,
                       ostream &output = cout)
{

 vector<string>::difference_type cnt = count_if(beg, end, GT6);//count_if 根据GT6 标准统计vector中元素个数
 output << "Number of unique words in the input "
        << end - beg << endl;
 output << cnt << " "
        <<  make_plural(cnt, "word", "s")
        << " 6 characters or longer" << endl;
 output << "Percentage of words 6 characters or more "
        << percent(cnt, end - beg) << endl;
}

ifstream &open_file(ifstream&, const string&);

ifstream &prompt_user(ifstream &stream)
{
    // loops until we get a valid stream or the user asks to quit
    while (true) {
        // ask for name of the file to open
        string filename;
        cout << "Please enter file name."
             << "Hit Enter to quit: \n";
        getline(cin, filename);  // read the filename
        // terminate the loop on either empty line or eof
        if (!cin || filename == "") {
            // set condition state to indicate failure & eof
            stream.setstate(
                 ifstream::eofbit | ifstream::failbit);
            return stream;
        }

        // use getline in case user enters a filename with spaces
        if (open_file(stream, filename)) return stream;

        // otherwise, stream wasn't valid, prompt user to try again
        cerr << "oops! unable to open file"
             << filename
             << " please try again!" << endl;
    }
}

// calls open_file to ask the user for the next book to process
// builds a vector<book> that contains the contents of each book
vector<string> get_books()
{
 ifstream infile;    // stream bound to the next book file
 vector<string> ret; // data structure we'll return to our caller

 // prompt_user asks user for next book and binds infile to it
 while (prompt_user(infile)) {

  // iterator to read the text of the book
  istream_iterator<string> in_iter(infile), eos;//这里意思是创建 从输入流infile中读取string 的istream_iterator对象
  //用于读取流
      while(in_iter!=eos){
       ret.push_back(*in_iter++);
       }
  // read contents of the book into this book's vector
  ret.insert(ret.end(), in_iter, eos);

  infile.close();  // close the file when we're done with it
 }
 return ret;
}


int main()
{
 // read the contents of the books to analyze
 vector<string> words = get_books();

 // sort the input so that we can eliminate duplicates
 sort(words.begin(), words.end());//排序算法

 // unique reorders elements and returns iterator to end of unique range
 // erase uses that iterator to erase non-unique elements
 words.erase(unique(words.begin(), words.end()), //erase 和unique一起 删除指定vector中的重复元素
             words.end());

 // sort the words by size, but maintain alphabetic order for words of the same size
 stable_sort(words.begin(), words.end(), isShorter);//stable_sort按照某个标准排序

 // analyze complexity: report frequency of words of each size
 // and total number/% of words greaten than length 6
 report_complexity(words.begin(), words.end());

 return 0;
}


    // write one string per line to the standard output
    ostream_iterator<string> out_iter(cout, "\n");

    // read strings from standard input and the end iterator
    istream_iterator<string> in_iter(cin), eof;

    // read until eof and write what was read to the standard output
    while (in_iter != eof)
     // write value of in_iter to standard output
     // and then increment the iterator to get the next value from cin
     *out_iter++ = *in_iter++;  //这个得意思是先读取cin ,再输入到cout

vector<int> vec;

    istream_iterator<int> in_iter(cin);  // read ints from cin
    istream_iterator<int> eof;           // istream ``end'' iterator

    // read until end of file, storing what was read in vec
    while (in_iter != eof)
            // increment advances the stream to the next value
            // dereference reads next value from the istream
            vec.push_back(*in_iter++);

    // print what we got
    for (vector<int>::const_iterator it = vec.begin();
                                     it != vec.end(); ++it)
     cout << *it << " ";
    cout << endl;
   
      // find last element in a comma-separated list
    string::reverse_iterator rcomma = //反向迭代器
                           find(line.rbegin(), line.rend(), ',');

    // wrong: will generate the word in reverse order
    cout << string(line.rbegin(), rcomma) << endl;

    // ok: get a forward iterator and read to end of line
    cout << string(rcomma.base(), line.end()) << endl;

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值