Читаем Thinking In C++. Volume 2: Practical Programming полностью

  cout << title << ':' << endl;

  if(c.empty()) {

    cout << "(empty)" << endl;

    return;

  }

  typename Container::iterator it;

  for(it = c.begin(); it != c.end(); it++)

    cout << *it << " ";

  cout << endl;

  cout << "size() " << c.size()

    << " max_size() "<< c.max_size()

    << " front() " << c.front()

    << " back() " << c.back() << endl;

}

template

void basicOps(char* s) {

  cout << "------- " << s << " -------" << endl;

  typedef ContainerOfInt Ci;

  Ci c;

  print(c, "c after default constructor");

  Ci c2(10, 1); // 10 elements, values all 1

  print(c2, "c2 after constructor(10,1)");

  int ia[] = { 1, 3, 5, 7, 9 };

  const int iasz = sizeof(ia)/sizeof(*ia);

  // Initialize with begin & end iterators:

  Ci c3(ia, ia + iasz);

  print(c3, "c3 after constructor(iter,iter)");

  Ci c4(c2); // Copy-constructor

  print(c4, "c4 after copy-constructor(c2)");

  c = c2; // Assignment operator

  print(c, "c after operator=c2");

  c.assign(10, 2); // 10 elements, values all 2

  print(c, "c after assign(10, 2)");

  // Assign with begin & end iterators:

  c.assign(ia, ia + iasz);

  print(c, "c after assign(iter, iter)");

  cout << "c using reverse iterators:" << endl;

  typename Ci::reverse_iterator rit = c.rbegin();

  while(rit != c.rend())

    cout << *rit++ << " ";

  cout << endl;

  c.resize(4);

  print(c, "c after resize(4)");

  c.push_back(47);

  print(c, "c after push_back(47)");

  c.pop_back();

  print(c, "c after pop_back()");

  typename Ci::iterator it = c.begin();

  it++; it++;

  c.insert(it, 74);

  print(c, "c after insert(it, 74)");

  it = c.begin();

  it++;

  c.insert(it, 3, 96);

  print(c, "c after insert(it, 3, 96)");

  it = c.begin();

  it++;

  c.insert(it, c3.begin(), c3.end());

  print(c, "c after insert("

    "it, c3.begin(), c3.end())");

  it = c.begin();

  it++;

  c.erase(it);

  print(c, "c after erase(it)");

  typename Ci::iterator it2 = it = c.begin();

  it++;

  it2++; it2++; it2++; it2++; it2++;

  c.erase(it, it2);

  print(c, "c after erase(it, it2)");

  c.swap(c2);

  print(c, "c after swap(c2)");

  c.clear();

  print(c, "c after clear()");

}

int main() {

  basicOps >("vector");

  basicOps >("deque");

  basicOps >("list");

} ///:~

The first function template, print( ), demonstrates the basic information you can get from any sequence container: whether it’s empty, its current size, the size of the largest possible container, the element at the beginning, and the element at the end. You can also see that every container has begin( ) and end( ) member functions that return iterators.

The basicOps( ) function tests everything else (and in turn calls print( )), including a variety of constructors: default, copy-constructor, quantity and initial value, and beginning and ending iterators. There are an assignment operator= and two kinds of assign( ) member functions. One takes a quantity and an initial value, and the other takes a beginning and ending iterator.

All the basic sequence containers are reversible containers, as shown by the use of the rbegin( ) and rend( ) member functions. A sequence container can be resized, and the entire contents of the container can be removed with clear( ). When you call resize( ) to expand a sequence, the new elements use the default constructor of the type of element in the sequence, or if they are built-in types, they are zero-initialized.

Using an iterator to indicate where you want to start inserting into any sequence container, you can insert( ) a single element, a number of elements that all have the same value, and a group of elements from another container using the beginning and ending iterators of that group.

To erase( ) a single element from the middle, use an iterator; to erase( ) a range of elements, use a pair of iterators. Notice that since a list supports only bidirectional iterators, all the iterator motion must be performed with increments and decrements. (If the containers were limited to vector and deque, which produce random-access iterators, operator+ and operator- could have been used to move the iterators in big jumps.)

Although both list and deque support push_front( ) and pop_front( ), vector does not, so the only member functions that work with all three are push_back( ) and pop_back( ).

Перейти на страницу:

Похожие книги

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных