рефераты конспекты курсовые дипломные лекции шпоры

Реферат Курсовая Конспект

Using the STL Sorting Functions

Using the STL Sorting Functions - раздел Образование, Unit 4. Sorting, Searching, and Complexity · 4.1 Sorting and Searching · 4.2 Complexity Assessments · Multiple-Choice Quiz The Standard Template Library Includes Functions That Programmers Can Use To ...

The Standard Template Library includes functions that programmers can use to sort a variety of containers. One of these functions is the sort function. The sort function performs a fast sort (typically a quicksort) on a container.

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: #include <iostream>#include <cstdlib>#include <ctime>#include <vector>#include <algorithm>#include <iterator> using namespace std; int random_less_than_50(void) { return (rand() % 50);} int main(int argc, char* argv[]) { // seed the random number generator srand( time(0) ); // create a vector with ten random elements (all less than 50) vector<int> v; back_insert_iterator< vector<int> > back_itr(v); generate_n(back_itr, 10, random_less_than_50); // display its contents ostream_iterator<int> out(cout, " "); copy(v.begin(), v.end(), out); // sort the vector sort(v.begin(), v.end()); // display its contents, sorted cout << endl; copy(v.begin(), v.end(), out); return EXIT_SUCCESS;}
Listing 2 Using the sort algorithm

Listing 2 uses a few other functions that warrant explanation. First, the STL function generate_n is used in Listing 2 to populate a vector with ten random numbers. This function takes as parameters an output iterator, a number of items to generate, and a function to use to generate each item. The generated items are placed in the output iterator specified in the first parameter. In this case, the output iterator is a back_insert_iterator for the vector v. Thus, all items generated by the function in the third parameter are placed at the end of vector v. The function specified in the third parameter is a wrapper for the C-library function rand. The function rand returns a random number from the runtime's random number generator. This random number can be quite large, so a wrapper function is used to reduce the number returned to a smaller range of values.

The sort function can operate only on containers that provide random access iterators. Containers such as vector, deque, and string all provide random access iterators. Since the STL list container does not provide random access iterators the general-purpose sort function on a list object results in a compile-time error. Since linked lists often need to be sorted, the list container has a special sort member function. Listing 3 demonstrates its use.

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: #include <iostream>#include <cstdlib>#include <ctime>#include <list>#include <algorithm>#include <iterator> using namespace std; int random_less_than_50(void) { return (rand() % 50);} int main(int argc, char* argv[]) { // seed the random number generator srand( time(0) ); // create a list with ten random elements // (all less than 50) list<int> ls; back_insert_iterator< list<int> > back_itr(ls); generate_n(back_itr, 10, random_less_than_50); // display its contents ostream_iterator<int> out(cout, " "); copy(ls.begin(), ls.end(), out); // sort the list // The following can NOT be used since lists // do not provide random access iterators // sort(ls.begin(), ls.end()); ls.sort(); // display its contents again cout << endl; copy(ls.begin(), ls.end(), out); return EXIT_SUCCESS;}
Listing 3 Sorting a list

In addition to sorting, the STL provides the ability to shuffle the contents of a container. Shuffling, the opposite of sorting, is the random arrangement of data in a set. The following listing demonstrates the STL function random_shuffle.

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: // create a deque with 10 elementsdeque<int> d;for (int i = 1; i <= 10; i++) { d.push_back(i);} ostream_iterator<int> out(cout, " "); for (int j = 1; j <= 5; j++) { // display its contents copy(d.begin(), d.end(), out); cout << endl; random_shuffle(d.begin(), d.end()); copy(d.begin(), d.end(), out); cout << endl << endl; sort(d.begin(), d.end());}
Listing 4 Shuffling a container

 

– Конец работы –

Эта тема принадлежит разделу:

Unit 4. Sorting, Searching, and Complexity · 4.1 Sorting and Searching · 4.2 Complexity Assessments · Multiple-Choice Quiz

На сайте allrefs.net читайте: "Unit 4. Sorting, Searching, and Complexity · 4.1 Sorting and Searching · 4.2 Complexity Assessments · Multiple-Choice Quiz"

Если Вам нужно дополнительный материал на эту тему, или Вы не нашли то, что искали, рекомендуем воспользоваться поиском по нашей базе работ: Using the STL Sorting Functions

Что будем делать с полученным материалом:

Если этот материал оказался полезным ля Вас, Вы можете сохранить его на свою страничку в социальных сетях:

Все темы данного раздела:

Binary Search
A binary search is a fast search algorithm suitable for data sets of any reasonable size encountered. Unlike a linear search, it is suitable even for very large data sets because it eliminates larg

Sorting Overview
Many different basic sorting algorithms exist. Each of these algorithms has unique characteristics, behaviors, and requirements. For example, for the same set of data, one algorithm may perform far

Selection Sort
Selection sort is a basic sorting algorithm that works by making iterations, or passes, through the data being sorted. Each pass results in the placement of one element into its correct location. A

Binary поиск
Binary поиск считается быстрым алгоритмом поиска, подходит для наборов данных любого разумного размера. В отличие от линейного поиска, может использоваться даже для очень больших наборов данных, по

Краткий обзор
Существуют много различных алгоритмов сортировки. У каждого из этих алгоритмов есть уникальные характеристики, поведения, и требования. Например, для одной и той же задачи, один алгоритм может выпо

Selection Sort (Вид выбора)
Алгоритм selection sort является основным алгоритмом сортировки, который работает посредством итерации, или передачи сортируемых данных. Каждая передача приводит к перемещению одного элемента в его

Алгоритм
Quicksort является быстрым алгоритмом сортировки, который решает задачу используя проблему divide-and-conquer (разделяй и властвуй). Quicksort это рекурсия приводит массив элементов к элементарному

Реализация
Код quicksort реализации приведен в листинге 1. Эта quicksort реализация использует основную стратегию выбора центра как выбор среднего элемента. Это простой подход к реализации, и иногда он может

Использование функции сортировки STL
Стандартная библиотека шаблонов включает функции, которые программисты могут использовать, чтобы сортировать массивы контейнеров. Одна из этих функций sort функция. Функция sort выполняет быстрый s

Краткий обзор Хэш-таблиц
Хэш-таблица это структура данных ассоциативного массива, которая поддерживает очень быструю вставку элементов, удаление, и извлечение. Т.е. она позволяет хранить пары (ключ, значение) и выпо

Хеш-функции
Операции использующие хэш-таблицы эффективны, потому что позиция хранимой суммы может быть вычислена, используя ключ. Хэш-таблицы обычно реализуются как массив значений, а хеш-функция исполь

Реализация Хэш-таблицы
Следующий файл заголовочного файла и реализации объявляет и определяет шаблонный класс сопоставления хеша. Класс берет четыре шаблонных параметра. Первым является ключевой тип, и вторым является ти

The Algorithm
Quicksort is a fast sorting algorithm that uses a divide-and-conquer problem solving approach. Unlike the basic sorting algorithms we have already examined, quicksort uses recursion. Given an array

An Implementation
A quicksort implementation appears in Listing 1. This quicksort implementation uses a basic pivot selection strategy of selecting the middle element. This is a simple approach to implement, but one

Overview of Hash Tables
A hash table is a data structure that supports very fast element insertion, removal, and retrieval. A hash table that is properly configured for the elements it contains can support these op

Hash Functions
Operations using hash tables are efficient because the position of a stored value can be calculated using the key. Hash tables are implemented typically as an array of values. A hash function

A Hash Table Implementation
The following header file and implementation file declares and defines a template hash map class. The class takes four template parameters. The first is the key type and the second is the value typ

Хотите получать на электронную почту самые свежие новости?
Education Insider Sample
Подпишитесь на Нашу рассылку
Наша политика приватности обеспечивает 100% безопасность и анонимность Ваших E-Mail
Реклама
Соответствующий теме материал
  • Похожее
  • Популярное
  • Облако тегов
  • Здесь
  • Временно
  • Пусто
Теги