Item 1 Iterators

class Date { public: Date(const char* date = "jxd"); Date(const Date& date); Date operator()(const char* date); Date& operator=(const Date& date); ~Date(); friend bool operator==(const Date& date1, const Date& date2); friend istream& operator>>(istream& in, Date& date); friend ostream& operator<<(ostream& out, const Date& date); private: string m_date; }; Date::Date(const char *date) : m_date(date) { cout << "[debug] Date ctor: " << date << endl; } Date::Date(const Date& date) { m_date.assign(date.m_date); cout << "[debug] Date copy ctor: " << m_date.c_str() << endl; } Date::~Date() { cout << "[debug] Date dtor: " << m_date.c_str() << endl; } Date Date::operator()(const char* date) { cout << "[debug] Date conversion/n"; return Date(date); } Date TodaysDate() { return Date("today"); } /** * Input a date string * Finish inputing by Ctrl+Z in Win32, or Ctrl+D in Linux */ istream& operator>>(istream& in, Date& date) { char buffer[32]; in >> buffer; date.m_date.assign(buffer); return in; } ostream& operator<<(ostream& out, const Date& date) { out << date.m_date.c_str(); return out; } Date& Date::operator=(const Date& date) { m_date.assign(date.m_date); return *this; } bool operator==(const Date& date1, const Date& date2) { return date1.m_date.compare(date2.m_date) == 0; } int main() { vector<Date> e; int size = e.max_size(); 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, // 2 last, ostream_iterator<Date>(cout, "/n")); e.insert(--e.end(), TodaysDate()); // 3 copy(first, // 4 last, ostream_iterator<Date>(cout, "/n")); }

 

1> 只有(last != e.end())时才合法
2> 只有(distance(first, last) > 0)时才合法
3> e.end()返回的临时变量,不允许修改;另外,e.end()-1有可能是非法位置
4> 因为vector会自动重新分配内存,所以first、last经过了insert可能已经失效了

你可能感兴趣的:(Date,String,vector,iterator,buffer,distance)