Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Thinking In C++, 2nd Edition, Volume 2 Standard Libraries& Advanced Topics - Eckel B..pdf
Скачиваний:
313
Добавлен:
24.05.2014
Размер:
2.09 Mб
Скачать

The second vector<string> v2 is not given an initial size so back_inserter must be used to force new elements in instead of trying to assign to existing locations. Just as an example, the other print( ) is used which requires a range.

The generate( ) and generate_n( ) functions have the same form as the “fill” functions except that they use a generator instead of a constant value; here, both generators are demonstrated.

Counting

All containers have a method size( ) that will tell you how many elements they hold. The following two algorithms count objects only if they satisfy certain criteria.

IntegralValue count(InputIterator first, InputIterator last, const EqualityComparable& value);

Produces the number of elements in [first, last) that are equivalent to value (when tested using operator==).

IntegralValue count_if(InputIterator first, InputIterator last, Predicate pred);

Produces the number of elements in [first, last) which each cause pred to return true.

Example

Here, a vector<char> v is filled with random characters (including some duplicates). A set<char> is initialized from v, so it holds only one of each letter represented in v. This set is used to count all the instances of all the different characters, which are then displayed:

//: C05:Counting.cpp

// The counting algorithms #include "PrintSequence.h" #include "Generators.h"

#include <vector> #include <algorithm> using namespace std;

int main() { vector<char> v;

generate_n(back_inserter(v), 50, CharGen()); print(v, "v", "");

// Create a set of the characters in v: set<char> cs(v.begin(), v.end()); set<char>::iterator it = cs.begin(); while(it != cs.end()) {

int n = count(v.begin(), v.end(), *it); cout << *it << ": " << n << ", ";

it++;

Chapter 15: Multiple Inheritance

293

Соседние файлы в предмете Программирование