Автор | Сообщение |
|
Отправлено: 07.06.14 14:18. Заголовок: vector adjacent equal elements
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
[только новые]
|
|
|
Отправлено: 07.06.14 19:05. Заголовок: If I have understood..
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 #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; } The output is 2 5 6 7 5 4 2 1 3 3 6 10 9 6 2 1 Otherwise it would be better to use standard algorithm std::adjucent_find or std::is_sorted_until as I demonstrated early.
|
|
|
|
Отправлено: 09.06.14 16:43. Заголовок: yes thanks problem s..
yes thanks problem solved
|
|
|
|