Отправлено: 25.06.13 01:33. Заголовок: Предложение по включению в стандарт C++ новых обобщенных функций std::reverse и std::sort
В подавляющем большинстве случаев стандартные алгоритмы std::reverse и std::sort (и аналогичные им функции члены классов std::forward_list и std::list) вызываются для всего контейнера. Поэтому было бы целесообразно включить в стандарт C++ соответствующие обобщенные функции std::reverse и std::sort, которые в качестве параметра имели бы ссылку на контейнер. Это упростило бы работу программиста по рутинному написанию вызовов соответствующих функций с указанием итераторов начала списка элементов контейнера и его конца.
Ниже приведен демонстрационный пример, иллюстрирующий идею предложения.
int main() { int a[3] = { 1, 2, 3 }; std::forward_list<int> f( std::begin( a ), std::end( a ) ); std::list<int> l( std::begin( a ), std::end( a ) ); std::vector<int> v( std::begin( a ), std::end( a ) );
std::cout << "a:\t"; for ( int x : a ) std::cout << x << ' '; std::cout << std::endl; std::cout << "f:\t"; for ( int x : f ) std::cout << x << ' '; std::cout << std::endl; std::cout << "l:\t"; for ( int x : l ) std::cout << x << ' '; std::cout << std::endl; std::cout << "v:\t"; for ( int x : v ) std::cout << x << ' '; std::cout << std::endl; std::cout << std::endl;
N1::reverse( a ); N1::reverse( f ); N1::reverse( l ); N1::reverse( v );
std::cout << "a:\t"; for ( int x : a ) std::cout << x << ' '; std::cout << std::endl; std::cout << "f:\t"; for ( int x : f ) std::cout << x << ' '; std::cout << std::endl; std::cout << "l:\t"; for ( int x : l ) std::cout << x << ' '; std::cout << std::endl; std::cout << "v:\t"; for ( int x : v ) std::cout << x << ' '; std::cout << std::endl; std::cout << std::endl;
N1::sort( a ); N1::sort( f ); N1::sort( l ); N1::sort( v );
std::cout << "a:\t"; for ( int x : a ) std::cout << x << ' '; std::cout << std::endl; std::cout << "f:\t"; for ( int x : f ) std::cout << x << ' '; std::cout << std::endl; std::cout << "l:\t"; for ( int x : l ) std::cout << x << ' '; std::cout << std::endl; std::cout << "v:\t"; for ( int x : v ) std::cout << x << ' '; std::cout << std::endl; std::cout << std::endl;
std::cout << "a:\t"; for ( int x : a ) std::cout << x << ' '; std::cout << std::endl; std::cout << "f:\t"; for ( int x : f ) std::cout << x << ' '; std::cout << std::endl; std::cout << "l:\t"; for ( int x : l ) std::cout << x << ' '; std::cout << std::endl; std::cout << "v:\t"; for ( int x : v ) std::cout << x << ' '; std::cout << std::endl; std::cout << std::endl; }
Отправлено: 05.10.18 18:00. Заголовок: Похоже с включением ..
Похоже с включением в стандарт C++ выражений требований (requires expressions) будет не сложно написать обобщенные функции std::sort и std::reverse. Я еще не достаточно изучил это нововведение, но тем не менее представленный ниже код выполняет поставленную задачу. Естественно выражения требований у функций могут быть еще уточнены.
template <typename Container, typename Key> auto lower_bound( const Container &container, const Key &key ) requires requires() { &Container::lower_bound; } { std::cout << "lower_bound for a const object with requires is called.\n"; return container.lower_bound( key ); }
template <typename Container, typename Key> auto lower_bound( Container &container, const Key &key ) requires requires() { &Container::lower_bound; } { std::cout << "lower_bound for a non-const object with requires is called.\n"; return container.lower_bound( key ); }
template <typename Container, typename Key> auto lower_bound( const Container &container, const Key &key ) { std::cout << "lower_bound for a const object without requires is called.\n"; return std::lower_bound( std::begin( container ), std::end( container ), key ); }
template <typename Container, typename Key > auto lower_bound( Container &container, const Key &key ) { std::cout << "lower_bound for a non-const object without requires is called.\n"; return std::lower_bound( std::begin( container ), std::end( container ), key ); }
template <typename Container, typename Key, typename Compare> auto lower_bound( const Container &container, const Key &key, Compare comp ) { std::cout << "lower_bound for a const object without requires is called.\n"; return std::lower_bound( std::begin( container ), std::end( container ), key, comp ); }
template <typename Container, typename Key, typename Compare> auto lower_bound( Container &container, const Key &key, Compare comp ) { std::cout << "lower_bound for a non-const object without requires is called.\n"; return std::lower_bound( std::begin( container ), std::end( container ), key, comp ); }
int main() { std::set<int> set1 = { 1, 2, 3, 4, 5 }; int value = 4;
auto it1 = lower_bound( set1, value );
std::cout << "The position for " << value << " is " << std::distance( std::begin( set1 ), it1 ) << '\n';
const std::set<int> set2 = { 1, 2, 3, 4, 5 };
auto it2 = lower_bound( set2, value );
std::cout << "The position for " << value << " is " << std::distance( std::begin( set2 ), it2 ) << '\n';
std::cout << '\n';
std::vector<int> v1 = { 1, 2, 3, 4, 5 };
auto it3 = lower_bound( v1, value );
std::cout << "The position for " << value << " is " << std::distance( std::begin( v1 ), it3 ) << '\n';
const std::vector<int> v2 = { 1, 2, 3, 4, 5 };
auto it4 = lower_bound( v2, value );
std::cout << "The position for " << value << " is " << std::distance( std::begin( v2 ), it4 ) << '\n';
std::cout << '\n';
std::vector<int> v3 = { 1, 2, 3, 4, 5 };
auto it5 = lower_bound( v3, value, std::less<>() );
std::cout << "The position for " << value << " is " << std::distance( std::begin( v3 ), it5 ) << '\n';
const std::vector<int> v4 = { 1, 2, 3, 4, 5 };
auto it6 = lower_bound( v4, value, std::less<>() );
std::cout << "The position for " << value << " is " << std::distance( std::begin( v4 ), it6 ) << '\n';
std::cout << '\n'; }
Вывод программы на консоль
lower_bound for a non-const object with requires is called. The position for 4 is 3 lower_bound for a const object with requires is called. The position for 4 is 3
lower_bound for a non-const object without requires is called. The position for 4 is 3 lower_bound for a const object without requires is called. The position for 4 is 3
lower_bound for a non-const object without requires is called. The position for 4 is 3 lower_bound for a const object without requires is called. The position for 4 is 3
В указанном вопросе требуется проверить, являются ли две строки анаграммами друг друга.
Один из подходов решения поставленной задачи - это сортировать строки и сравнить их друг с другом.
Написать соответствующую функцию будет очень просто, если обобщенная функция std::sort (это также касается и обобщенной функции std::reverse) будет возвращать ссылку на исходный контейнер.
Все даты в формате GMT
3 час. Хитов сегодня: 1006
Права: смайлы да, картинки да, шрифты да, голосования нет
аватары да, автозамена ссылок вкл, премодерация откл, правка нет