Форум » C/C++ для начинающих (C/C++ for beginners) » vector adjacent equal elements » Ответить

vector adjacent equal elements

ramees: u showed me how splitting an array when there are adjacent equal elements. i like to know how to do same calculation on a vector container #include <iostream> #include <vector> const int * find_greater( const int a[], size_t n ) { if ( n != 0 ) { for ( const int *prev = a, *next = a; ++next != a + n; ++prev ) { if ( *next < *prev ) return prev; } } return ( a + n ); } const int * find_less( const int a[], size_t n ) { if ( n != 0 ) { for ( const int *prev = a, *next = a; ++next != a + n; ++prev ) { if ( *prev < *next ) return prev; } } return ( a + n ); } int main() { int a[] = { 2, 5, 6, 7, 5, 4, 2, 1, 3, 3, 6, 10, 9, 6, 2, 1 }; size_t n = sizeof( a ) / sizeof( *a ); const int *first = a; std::vector<std::vector<int>> v; while ( first != a + n ) { const int * last = find_greater( first, n - ( first - a ) ); last = find_less( last, n - ( last - a ) ); if ( last != a + n ) ++last; v.push_back( std::vector<int>( first, last ) ); first = last; } for ( const std::vector<int> &v1 : v ) { for ( int x : v1 ) std::cout << x << ' '; std::cout << std::endl; } return 0; }

Ответов - 2

Сыроежка: If I have understood correctly you want that I would show how to rewrite functions find_greater and find_less when there is used a vector instead of an array. In fact you need not to rewrite the functions. You can use them with a vector by means of using member function data(). For example [pre2] #include <iostream> #include <vector> const int * find_greater( const int a[], size_t n ) { if ( n != 0 ) { for ( const int *prev = a, *next = a; ++next != a + n; ++prev ) { if ( *next < *prev ) return prev; } } return ( a + n ); } const int * find_less( const int a[], size_t n ) { if ( n != 0 ) { for ( const int *prev = a, *next = a; ++next != a + n; ++prev ) { if ( *prev < *next ) return prev; } } return ( a + n ); } int main() { std::vector<int> a = { 2, 5, 6, 7, 5, 4, 2, 1, 3, 3, 6, 10, 9, 6, 2, 1 }; std::vector<int>::size_type n = a.size(); const int *first = a.data(); std::vector<std::vector<int>> v; while ( first != a.data() + n ) { const int * last = find_greater( first, n - ( first - a.data() ) ); last = find_less( last, n - ( last - a.data() ) ); if ( last != a.data() + n ) ++last; v.push_back( std::vector<int>( first, last ) ); first = last; } for ( const std::vector<int> &v1 : v ) { for ( int x : v1 ) std::cout << x << ' '; std::cout << std::endl; } return 0; } [/pre2] The output is [pre2] 2 5 6 7 5 4 2 1 3 3 6 10 9 6 2 1 [/pre2] Otherwise it would be better to use standard algorithm std::adjucent_find or std::is_sorted_until as I demonstrated early.

ramees: yes thanks problem solved



полная версия страницы