Программирование >>  Инициализация объектов класса, структура 

1 ... 180 181 182 [ 183 ] 184 185 186 ... 395


a a a a alice alive almost

alternately ancient and and and and and and

and as asks at at beautiful becomes bird

bird blows blue bounded but by calling coat

daddy daddy daddy dark darkened darkening distant each

either emma eternity falls fear fiery fiery flight

flowing for grow hair hair has he heaven,

held her her her her him him home

houses i immeasurable immensity in in in in

inexpressibly is is is it it it its

journeying lands leave leave life like long looks

magical mean more night, no not not not

now now of of on one one one

passion puts quite red rises row same says

she she shush shyly sight sky so so

star star still stone such tell tells tells

that that the the the the the the

the there there thing through time to to

to to trees unravel untamed wanting watch what

when wind with with you you you you

your your

После применения unique() и последующего вызова erase() вектор texts выглядит следующим образом:

a alice alive almost alternately ancient

and as asks at beautiful becomes bird blows

blue bounded but by calling coat daddy dark

darkened darkening distant each either emma eternity falls

fear fiery flight flowing for grow hair has

he heaven, held her him home houses i

immeasurable immensity in inexpressibly is it its journeying

lands leave life like long looks magical mean

more night, no not now of on one

passion puts quite red rises row same says

she shush shyly sight sky so star still

stone such tell tells that the there thing

through time to trees unravel untamed wanting watch

what when wind with you your

Следующая наша задача - отсортировать строки по длине. Для этого мы воспользуемся не алгоритмом sort() , а алгоритмом stable sort() , который сохраняет относительные положения равных элементов. В результате для элементов равной длины сохраняется алфавитный порядок. Для сортировки по длине мы применим собственную операцию

bool less than( const string & s1, const string & s2 ) {

return s1.size() < s1.size();

void process vocab( vector<textwords, allocator> *pvec ) {

отсортировать элементы вектора texts по длине, сохранив также прежний порядок

stable sort( texts.begin(), texts.end(), less than );

...

сравнения меньше . Один из возможных способов таков:



объект-функция - операция реазована с помощью перегрузки оператора operator() class LessThan { public:

bool operator()( const string & s1, const string & s2 ) { return s1.size() < s2.size(); }

объекта-функции: };

Объект-функция - это класс, в котором перегружен оператор вызова operator() . В теле этого оператора и реализуется логика функции, в данном случае сравнение меньше . Определение оператора вызова выглядит странно из-за двух нар скобок. Запись

operator()

говорит компилятору, что мы перегружаем оператор вызова. Вторая пара скобок

( const string & s1, const string & s2 )

задает передаваемые ему формальные параметры. Если сравнить это определение с предыдущим определением функции less than() , мы увидим, что, за исключением замены less than на operator(), они совпадают.

Объект-функция определяется так же, как обычный объект класса (правда, в данном случае нам не понадобился конструктор: нет членов, подлежащих инициализации):

LessThan lt;

Для вызова экземпляра перегруженного оператора мы применяем оператор вызова к

string st1( shakespeare );

string st2( marlowe );

вызывается lt.operator()( st1, st2 );

нашему объекту класса, передавая необходимые аргументы. Например:

bool is shakespeare less = lt( st1, st2 );

Ниже показана исправленная функция process vocab() , в которой алгоритму stable sort() передается безымянный объект-функция LessThan() :

Нужный результат при этом достигается, но эффективность существенно ниже, чем хотелось бы. less than() реализована в виде одной инструкции. Обычно она вызывается как встроенная (inline) функция. Но, передавая указатель на нее, м1 не даем компилятору сделать ее встроенной. Способ, позволяющий добиться этого, -применение



void process vocab( vector<textwords, allocator> *pvec ) {

stable sort( texts.begin(), texts.end(), LessThan() );

...

Внутри stable sort() перегруженный оператор вызова подставляется в текст программы как встроенная функция. (В качестве третьего аргумента stable sort() может принимать как указатель на функцию less than() , так и объект класса LessThan, поскольку аргументом является параметр-тип шаблона. Подробнее об объектах-функциях мы расскажем в разделе 12.3.)

Вот результат применения stable sort() к вектору texts:

as at by he in is it no

of on so to and but for has

her him its not now one red row

she sky the you asks bird blue coat

dark each emma fear grow hair held home

life like long mean more puts same says

star such tell that time what when wind

with your alice alive blows daddy falls fiery

lands leave looks quite rises shush shyly sight

still stone tells there thing trees watch almost

either flight houses night, ancient becomes bounded calling

distant flowing heaven, magical passion through unravel untamed

wanting darkened eternity beautiful darkening immensity journeying alternately

immeasurable inexpressibly

Подсчитать число слов, длина которых больше шести символов, можно с помощью обобщенного алгоритма count if() и еще одного объекта-функции - GreaterThan. Этот объект чуть сложнее, так как позволяет пользователю задать размер, с которым производится сравнение. Мы сохраняем размер в члене класса и инициализируем его с

#include <iostream> class GreaterThan {

public:

GreaterThan( int size = 6 ) : size( size ){} int size() { return size; }

bool operator()( const string & s1 ) { return s1.size() > 6; }

private:

int size;

помощью конструктора (по умолчанию - значением 6): Использовать его можно так:



1 ... 180 181 182 [ 183 ] 184 185 186 ... 395

© 2006 - 2025 pmbk.ru. Генерация страницы: 0
При копировании материалов приветствуются ссылки.
Яндекс.Метрика