Exceptional C++

【Exceptional C++(1)】Iterators

2018-01-26  本文已影响22人  downdemo

问题

int main()
{
    vector<Date> e;
    copy(istream_iterator<Date>(cin), istream_iterator<Date>(), back_inserter(e) );
    vector<Date>::iterator first = find(e.begin(), e.end(), "01/01/95");
    vector<Date>::iterator last = find(e.begin(), e.end(), "12/31/95");
    *last = "12/30/95";
    copy(first, last, ostream_iterator<Date>(cout, "\n") );
    e.insert(--e.end(), TodaysDate() );
    copy(first, last, ostream_iterator(cout, "\n") );
}

说明

template<class InputIterator, class OutputIterator>
  OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result)
{
  while (first!=last) {
    *result = *first;
    ++result; ++first;
  }
  return result;
}
// istream_iterator example
#include <iostream>     // std::cin, std::cout
#include <iterator>     // std::istream_iterator

int main () {
  double value1, value2;
  std::cout << "Please, insert two values: ";

  std::istream_iterator<double> eos;              // 不指定对象即为end-of-stream iterator
  std::istream_iterator<double> iit (std::cin);   // stdin iterator

  if (iit!=eos) value1=*iit;

  ++iit;
  if (iit!=eos) value2=*iit;

  std::cout << value1 << "*" << value2 << "=" << (value1*value2) << '\n';

  return 0;
}

// output
Please, insert two values: 2 32
2*32=64
// back_inserter example
#include <iostream>     // std::cout
#include <iterator>     // std::back_inserter
#include <vector>       // std::vector
#include <algorithm>    // std::copy

int main () {
  std::vector<int> foo,bar;
  for (int i=1; i<=5; i++)
  { foo.push_back(i); bar.push_back(i*10); }

  std::copy (bar.begin(),bar.end(),back_inserter(foo));

  std::cout << "foo contains:";
  for ( std::vector<int>::iterator it = foo.begin(); it!= foo.end(); ++it )
      std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

//output
foo contains: 1 2 3 4 5 10 20 30 40 50
// ostream_iterator example
#include <iostream>     // std::cout
#include <iterator>     // std::ostream_iterator
#include <vector>       // std::vector
#include <algorithm>    // std::copy

int main () {
  std::vector<int> myvector;
  for (int i=1; i<10; ++i) myvector.push_back(i*10);

  std::ostream_iterator<int> out_it (std::cout,", ");
  std::copy ( myvector.begin(), myvector.end(), out_it ); // 打印元素后接分隔符
  return 0;
}

// output
10, 20, 30, 40, 50, 60, 70, 80, 90,

解答

int main()
{
    vector<Date> e;
    copy(istream_iterator<Date>(cin), istream_iterator<Date>(), back_inserter(e) );
    vector<Date>::iterator first = find(e.begin(), e.end(), "01/01/95");
    vector<Date>::iterator last = find(e.begin(), e.end(), "12/31/95");
    *last = "12/30/95"; // 1
    copy(first, last, ostream_iterator<Date>(cout, "\n") ); // 2
    e.insert(--e.end(), TodaysDate() ); // 3
    copy(first, last, ostream_iterator(cout, "\n") );
}
Date* f();
p = --f(); // 错误,但写成f()-1就可以

总结

上一篇下一篇

猜你喜欢

热点阅读