Класс unordered_multisetunordered_multiset Class
Шаблон класса описывает объект, управляющий последовательностью элементов типа с различной длиной const Key
.The class template describes an object that controls a varying-length sequence of elements of type const Key
. Последовательность слабо упорядочена хэш-функцией, которая разделяет последовательность в упорядоченный набор подпоследовательностей, называемых блоками.The sequence is weakly ordered by a hash function, which partitions the sequence into an ordered set of subsequences called buckets. В каждом блоке функция сравнения определяет, упорядочена ли каждая пара элементов соответствующим образом.Within each bucket a comparison function determines whether any pair of elements has equivalent ordering. Каждый элемент используется в качестве ключа сортировки и в качестве значения.Each element serves as both a sort key and a value. Последовательность представляется в виде, позволяющем выполнять поиск, вставку и удаление произвольного элемента несколькими операциями, которые могут не зависеть от числа элементов в последовательности (постоянное время), по крайней мере, когда все блоки имеют примерно одинаковую длину.The sequence is represented in a way that permits lookup, insertion, and removal of an arbitrary element with a number of operations that can be independent of the number of elements in the sequence (constant time), at least when all buckets are of roughly equal length. В худшем случае, когда все элементы находятся в одном блоке, количество операций пропорционально количеству элементов в последовательности (линейное время).In the worst case, when all of the elements are in one bucket, the number of operations is proportional to the number of elements in the sequence (linear time). Кроме того, вставка элементов не делает итераторы недействительными, а при удалении элементов недействительными становятся только итераторы, указывающие на удаленный элемент.Moreover, inserting an element invalidates no iterators, and removing an element invalidates only those iterators which point at the removed element.
СинтаксисSyntax
template <class Key,
class Hash = std::hash<Key>,
class Pred = std::equal_to<Key>,
class Alloc = std::allocator<Key>>
class unordered_multiset;
ПараметрыParameters
РазделKey
Тип ключа.The key type.
ФункцииHash
Тип объекта хэш-функции.The hash function object type.
ВозможенPred
Тип объекта функции сравнения на предмет равенства.The equality comparison function object type.
ИдентификаторAlloc
Класс распределителя.The allocator class.
ЭлементыMembers
Определение типаType Definition | ОписаниеDescription |
---|---|
allocator_typeallocator_type | Тип распределителя для управления хранилищем.The type of an allocator for managing storage. |
const_iteratorconst_iterator | Тип постоянного итератора для управляемой последовательности.The type of a constant iterator for the controlled sequence. |
const_local_iteratorconst_local_iterator | Тип постоянного итератора блока для управляемой последовательности.The type of a constant bucket iterator for the controlled sequence. |
const_pointerconst_pointer | Тип постоянного указателя на элемент.The type of a constant pointer to an element. |
const_referenceconst_reference | Тип постоянной ссылки на элемент.The type of a constant reference to an element. |
difference_typedifference_type | Тип расстояния со знаком между двумя элементами.The type of a signed distance between two elements. |
Hasherhasher | Тип хэш-функции.The type of the hash function. |
итерациiterator | Тип итератора для управляемой последовательности.The type of an iterator for the controlled sequence. |
key_equalkey_equal | Тип функции сравнения.The type of the comparison function. |
key_typekey_type | Тип ключа упорядочения.The type of an ordering key. |
local_iteratorlocal_iterator | Тип итератора блока для управляемой последовательности.The type of a bucket iterator for the controlled sequence. |
видpointer | Тип указателя на элемент.The type of a pointer to an element. |
referencereference | Тип ссылки на элемент.The type of a reference to an element. |
size_typesize_type | Тип беззнакового расстояния между двумя элементами.The type of an unsigned distance between two elements. |
value_typevalue_type | Тип элемента.The type of an element. |
Функция-членMember Function | ОписаниеDescription |
---|---|
началеbegin | Задает начало управляемой последовательности.Designates the beginning of the controlled sequence. |
периодbucket | Получает номер блока для значения ключа.Gets the bucket number for a key value. |
bucket_countbucket_count | Получает количество блоков.Gets the number of buckets. |
bucket_sizebucket_size | Получает размер блока.Gets the size of a bucket. |
cbegincbegin | Задает начало управляемой последовательности.Designates the beginning of the controlled sequence. |
cendcend | Задает конец управляемой последовательности.Designates the end of the controlled sequence. |
пустоclear | Удаляет все элементы.Removes all elements. |
содержитc++ 20containsC++20 | Проверяет, существует ли элемент с указанным ключом.Checks if there's an element with the specified key. |
countcount | Определяет количество элементов, соответствующих заданному ключу.Finds the number of elements matching a specified key. |
emplaceemplace | Добавляет элемент, созданный на месте.Adds an element constructed in place. |
emplace_hintemplace_hint | Добавляет элемент, созданный на месте, с подсказкой.Adds an element constructed in place, with hint. |
emptyempty | Проверяет отсутствие элементов.Tests whether no elements are present. |
endend | Задает конец управляемой последовательности.Designates the end of the controlled sequence. |
equal_rangeequal_range | Находит диапазон, соответствующий указанному ключу.Finds range that matches a specified key. |
eraseerase | Удаляет элементы в указанных позициях.Removes elements at specified positions. |
findfind | Определяет элемент, соответствующий указанному ключу.Finds an element that matches a specified key. |
get_allocatorget_allocator | Возвращает сохраненный объект распределителя.Gets the stored allocator object. |
hash_functionhash_function | Получает сохраненный объект хэш-функции.Gets the stored hash function object. |
insertinsert | Добавляет элементы.Adds elements. |
key_eqkey_eq | Получает сохраненный объект функции сравнения.Gets the stored comparison function object. |
load_factorload_factor | Подсчитывает среднее число элементов в блоке.Counts the average elements per bucket. |
max_bucket_countmax_bucket_count | Получает максимальное количество блоков.Gets the maximum number of buckets. |
max_load_factormax_load_factor | Возвращает или задает максимальное количество элементов в блоке.Gets or sets the maximum elements per bucket. |
max_sizemax_size | Возвращает максимальный размер управляемой последовательности.Gets the maximum size of the controlled sequence. |
rehashrehash | Повторно создает хэш-таблицу.Rebuilds the hash table. |
sizesize | Подсчитывает количество элементов.Counts the number of elements. |
позицииswap | Меняет местами содержимое двух контейнеров.Swaps the contents of two containers. |
unordered_multisetunordered_multiset | Создает объект контейнера.Constructs a container object. |
ОператорOperator | ОписаниеDescription |
---|---|
unordered_multiset:: operator =unordered_multiset::operator= | Копирует хэш-таблицу.Copies a hash table. |
КомментарииRemarks
Объект упорядочивает управляемую им последовательность путем вызова двух сохраненных объектов — объекта функции сравнения типа unordered_multiset::key_equal и объекта хэш-функции типа unordered_multiset::hasher.The object orders the sequence it controls by calling two stored objects, a comparison function object of type unordered_multiset::key_equal and a hash function object of type unordered_multiset::hasher. Доступ к первому сохраненному объекту осуществляется путем вызова функции члена unordered_multiset:: key_eq ()
; доступ к второму сохраненному объекту осуществляется путем вызова функции члена unordered_multiset:: hash_function ()
.You access the first stored object by calling the member function unordered_multiset::key_eq()
; and you access the second stored object by calling the member function unordered_multiset::hash_function()
. В частности, для всех значений X
и Y
типа Key
вызов key_eq()(X, Y)
возвращает значение true, только если два значения аргументов имеют соответствующий порядок; вызов hash_function()(keyval)
создает распределение значений типа size_t
.Specifically, for all values X
and Y
of type Key
, the call key_eq()(X, Y)
returns true only if the two argument values have equivalent ordering; the call hash_function()(keyval)
yields a distribution of values of type size_t
. В отличие от класса Unordered_set Class, объект типа не unordered_multiset
гарантирует, что key_eq()(X, Y)
всегда имеет значение false для любого из двух элементов управляемой последовательности.Unlike class template unordered_set Class, an object of type unordered_multiset
does not ensure that key_eq()(X, Y)
is always false for any two elements of the controlled sequence. (Ключи не обязательно должны быть уникальными.)(Keys need not be unique.)
Объект также хранит максимальный коэффициент нагрузки, который определяет максимальное желаемое среднее количество элементов в блоке.The object also stores a maximum load factor, which specifies the maximum desired average number of elements per bucket. Если вставка элемента приводит к превышению максимального коэффициента загрузки unordered_multiset:: load_factor ()
, контейнер увеличивает количество сегментов и перестраивает хэш-таблицу по мере необходимости.If inserting an element causes unordered_multiset::load_factor()
to exceed the maximum load factor, the container increases the number of buckets and rebuilds the hash table as needed.
Фактический порядок элементов в управляемой последовательности зависит от хэш-функции, функции сравнения, порядка вставки, максимального коэффициента нагрузки и текущего числа блоков.The actual order of elements in the controlled sequence depends on the hash function, the comparison function, the order of insertion, the maximum load factor, and the current number of buckets. Обычно невозможно предсказать порядок элементов в управляемой последовательности.You cannot in general predict the order of elements in the controlled sequence. Однако всегда можно сохранять уверенность, что любое подмножество элементов, имеющих соответствующий порядок, будет расположено по соседству в управляемой последовательности.You can always be assured, however, that any subset of elements that have equivalent ordering are adjacent in the controlled sequence.
Объект выделяет и освобождает хранилище для управляемой им последовательности с помощью сохраненного объекта распределителя типа unordered_multiset::allocator_type.The object allocates and frees storage for the sequence it controls through a stored allocator object of type unordered_multiset::allocator_type. Такой объект распределителя должен иметь тот же внешний интерфейс, что и объект типа allocator
.Such an allocator object must have the same external interface as an object of type allocator
. Обратите внимание, что сохраненный объект распределителя не копируется, когда назначается объект контейнера.Note that the stored allocator object is not copied when the container object is assigned.
ТребованияRequirements
Заголовок:<unordered_set>Header: <unordered_set>
Пространство имен: stdNamespace: std
unordered_multiset:: allocator_typeunordered_multiset::allocator_type
Тип распределителя для управления хранилищем.The type of an allocator for managing storage.
typedef Alloc allocator_type;
КомментарииRemarks
Этот тип является синонимом для параметра шаблона Alloc
.The type is a synonym for the template parameter Alloc
.
ПримерExample
// std__unordered_set__unordered_multiset_allocator_type.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
typedef std::allocator<std::pair<const char, int> > Myalloc;
int main()
{
Myset c1;
Myset::allocator_type al = c1.get_allocator();
std::cout << "al == std::allocator() is "
<< std::boolalpha << (al == Myalloc()) << std::endl;
return (0);
}
al == std::allocator() is true
unordered_multiset:: Beginunordered_multiset::begin
Задает начало управляемой последовательности или сегмента.Designates the beginning of the controlled sequence or a bucket.
iterator begin();
const_iterator begin() const;
local_iterator begin(size_type nbucket);
const_local_iterator begin(size_type nbucket) const;
ПараметрыParameters
нбуккетnbucket
Номер сегмента.The bucket number.
КомментарииRemarks
Первые две функции-члены возвращают прямой итератор, указывающий на первый элемент последовательности (или на место сразу за концом пустой последовательности).The first two member functions return a forward iterator that points at the first element of the sequence (or just beyond the end of an empty sequence). Последние две функции-члена возвращают прямой итератор, указывающий на первый элемент контейнера нбуккет (или сразу за концом пустого контейнера).The last two member functions return a forward iterator that points at the first element of bucket nbucket (or just beyond the end of an empty bucket).
ПримерExample
// std__unordered_set__unordered_multiset_begin.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a]"
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
// inspect first two items "[c] [b]"
Myset::iterator it2 = c1.begin();
std::cout << "[" << *it2 << "] ";
++it2;
std::cout << "[" << *it2 << "] ";
std::cout << std::endl;
// inspect bucket containing 'a'
Myset::const_local_iterator lit = c1.begin(c1.bucket('a'));
std::cout << "[" << *lit << "] ";
return (0);
}
[c] [b] [a]
[c] [b]
[a]
unordered_multiset:: контейнерunordered_multiset::bucket
Получает номер блока для значения ключа.Gets the bucket number for a key value.
size_type bucket(const Key& keyval) const;
ПараметрыParameters
кэйвалkeyval
Значение ключа для сопоставления.The key value to map.
КомментарииRemarks
Функция-член возвращает номер контейнера, который в настоящий момент соответствует значению ключа keyval
.The member function returns the bucket number currently corresponding to the key value keyval
.
ПримерExample
// std__unordered_set__unordered_multiset_bucket.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a] "
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
// display buckets for keys
Myset::size_type bs = c1.bucket('a');
std::cout << "bucket('a') == " << bs << std::endl;
std::cout << "bucket_size(" << bs << ") == " << c1.bucket_size(bs)
<< std::endl;
return (0);
}
[c] [b] [a]
bucket('a') == 7
bucket_size(7) == 1
unordered_multiset:: bucket_countunordered_multiset::bucket_count
Получает количество блоков.Gets the number of buckets.
size_type bucket_count() const;
КомментарииRemarks
Функция-член возвращает текущее число блоков.The member function returns the current number of buckets.
ПримерExample
// std__unordered_set__unordered_multiset_bucket_count.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a] "
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
// inspect current parameters
std::cout << "bucket_count() == " << c1.bucket_count() << std::endl;
std::cout << "load_factor() == " << c1.load_factor() << std::endl;
std::cout << "max_bucket_count() == "
<< c1.max_bucket_count() << std::endl;
std::cout << "max_load_factor() == "
<< c1.max_load_factor() << std::endl;
std::cout << std::endl;
// change max_load_factor and redisplay
c1.max_load_factor(0.10f);
std::cout << "bucket_count() == " << c1.bucket_count() << std::endl;
std::cout << "load_factor() == " << c1.load_factor() << std::endl;
std::cout << "max_bucket_count() == "
<< c1.max_bucket_count() << std::endl;
std::cout << "max_load_factor() == "
<< c1.max_load_factor() << std::endl;
std::cout << std::endl;
// rehash and redisplay
c1.rehash(100);
std::cout << "bucket_count() == " << c1.bucket_count() << std::endl;
std::cout << "load_factor() == " << c1.load_factor() << std::endl;
std::cout << "max_bucket_count() == "
<< c1.max_bucket_count() << std::endl;
std::cout << "max_load_factor() == "
<< c1.max_load_factor() << std::endl;
return (0);
}
[c] [b] [a]
bucket_count() == 8
load_factor() == 0.375
max_bucket_count() == 8
max_load_factor() == 4
bucket_count() == 8
load_factor() == 0.375
max_bucket_count() == 8
max_load_factor() == 0.1
bucket_count() == 128
load_factor() == 0.0234375
max_bucket_count() == 128
max_load_factor() == 0.1
unordered_multiset:: bucket_sizeunordered_multiset::bucket_size
Получает размер сегмента.Gets the size of a bucket
size_type bucket_size(size_type nbucket) const;
ПараметрыParameters
нбуккетnbucket
Номер сегмента.The bucket number.
КомментарииRemarks
Функции элементов возвращают размер сегмента нбуккет.The member functions returns the size of bucket number nbucket.
ПримерExample
// std__unordered_set__unordered_multiset_bucket_size.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a] "
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
// display buckets for keys
Myset::size_type bs = c1.bucket('a');
std::cout << "bucket('a') == " << bs << std::endl;
std::cout << "bucket_size(" << bs << ") == " << c1.bucket_size(bs)
<< std::endl;
return (0);
}
[c] [b] [a]
bucket('a') == 7
bucket_size(7) == 1
unordered_multiset:: cbeginunordered_multiset::cbegin
Возвращает const
итератор, который обращается к первому элементу в диапазоне.Returns a const
iterator that addresses the first element in the range.
const_iterator cbegin() const;
Возвращаемое значениеReturn Value
const
Итератор прямого доступа, указывающий на первый элемент диапазона, или расположение непосредственно за концом пустого диапазона (для пустого диапазона cbegin() == cend()
).A const
forward-access iterator that points at the first element of the range, or the location just beyond the end of an empty range (for an empty range, cbegin() == cend()
).
КомментарииRemarks
Элементы в диапазоне нельзя изменить с помощью возвращаемого значения cbegin
.With the return value of cbegin
, the elements in the range cannot be modified.
Эту функцию-член можно использовать вместо функции-члена begin()
, чтобы гарантировать, что возвращаемое значение будет const_iterator
.You can use this member function in place of the begin()
member function to guarantee that the return value is const_iterator
. Обычно используется вместе с ключевым словом вывода типа auto, как показано в следующем примере.Typically, it's used in conjunction with the auto type deduction keyword, as shown in the following example. В этом примере рекомендуется использовать Container
изменяемый (не- const
) контейнер любого типа, который поддерживает begin()
и cbegin()
.In the example, consider Container
to be a modifiable (non- const
) container of any kind that supports begin()
and cbegin()
.
auto i1 = Container.begin();
// i1 is Container<T>::iterator
auto i2 = Container.cbegin();
// i2 is Container<T>::const_iterator
unordered_multiset:: cendunordered_multiset::cend
Возвращает const
итератор, который обращается к расположению сразу за последним элементом в диапазоне.Returns a const
iterator that addresses the location just beyond the last element in a range.
const_iterator cend() const;
Возвращаемое значениеReturn Value
const
Итератор прямого доступа, указывающий на место сразу за концом диапазона.A const
forward-access iterator that points just beyond the end of the range.
КомментарииRemarks
cend
используется для проверки того, прошел ли итератор конец диапазона.cend
is used to test whether an iterator has passed the end of its range.
Эту функцию-член можно использовать вместо функции-члена end()
, чтобы гарантировать, что возвращаемое значение будет const_iterator
.You can use this member function in place of the end()
member function to guarantee that the return value is const_iterator
. Обычно используется вместе с ключевым словом вывода типа auto, как показано в следующем примере.Typically, it's used in conjunction with the auto type deduction keyword, as shown in the following example. В этом примере рекомендуется использовать Container
изменяемый (не- const
) контейнер любого типа, который поддерживает end()
и cend()
.In the example, consider Container
to be a modifiable (non- const
) container of any kind that supports end()
and cend()
.
auto i1 = Container.end();
// i1 is Container<T>::iterator
auto i2 = Container.cend();
// i2 is Container<T>::const_iterator
Значение, возвращаемое cend
, не должно быть подвергнуто удалению ссылки.The value returned by cend
should not be dereferenced.
unordered_multiset:: Clearunordered_multiset::clear
Удаляет все элементы.Removes all elements.
void clear();
КомментарииRemarks
Функция-член вызывает unordered_multiset::erase(
unordered_multiset::begin(),
unordered_multiset::end())
.The member function calls unordered_multiset::erase(
unordered_multiset::begin(),
unordered_multiset::end())
.
ПримерExample
// std__unordered_set__unordered_multiset_clear.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a] "
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
// clear the container and reinspect
c1.clear();
std::cout << "size == " << c1.size() << std::endl;
std::cout << "empty() == " << std::boolalpha << c1.empty() << std::endl;
std::cout << std::endl;
c1.insert('d');
c1.insert('e');
// display contents "[e] [d] "
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
std::cout << "size == " << c1.size() << std::endl;
std::cout << "empty() == " << std::boolalpha << c1.empty() << std::endl;
return (0);
}
[c] [b] [a]
size == 0
empty() == true
[e] [d]
size == 2
empty() == false
unordered_multiset:: const_iteratorunordered_multiset::const_iterator
Тип постоянного итератора для управляемой последовательности.The type of a constant iterator for the controlled sequence.
typedef T1 const_iterator;
КомментарииRemarks
Тип описывает объект, который можно использовать в качестве постоянного прямого итератора для управляемой последовательности.The type describes an object that can serve as a constant forward iterator for the controlled sequence. Он описан здесь как синоним для типа T1
, определяемого реализацией.It is described here as a synonym for the implementation-defined type T1
.
ПримерExample
// std__unordered_set__unordered_multiset_const_iterator.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a]"
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
return (0);
}
[c] [b] [a]
unordered_multiset:: const_local_iteratorunordered_multiset::const_local_iterator
Тип постоянного итератора блока для управляемой последовательности.The type of a constant bucket iterator for the controlled sequence.
typedef T5 const_local_iterator;
КомментарииRemarks
Этот тип описывает объект, который можно использовать в качестве постоянного прямого итератора для блока.The type describes an object that can serve as a constant forward iterator for a bucket. Он описан здесь как синоним для типа T5
, определяемого реализацией.It is described here as a synonym for the implementation-defined type T5
.
ПримерExample
// std__unordered_set__unordered_multiset_const_local_iterator.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a]"
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
// inspect bucket containing 'a'
Myset::const_local_iterator lit = c1.begin(c1.bucket('a'));
std::cout << "[" << *lit << "] ";
return (0);
}
[c] [b] [a]
[a]
unordered_multiset:: const_pointerunordered_multiset::const_pointer
Тип постоянного указателя на элемент.The type of a constant pointer to an element.
typedef Alloc::const_pointer const_pointer;
КомментарииRemarks
Этот тип описывает объект, который можно использовать в качестве постоянного указателя на элемент управляемой последовательности.The type describes an object that can serve as a constant pointer to an element of the controlled sequence.
ПримерExample
// std__unordered_set__unordered_multiset_const_pointer.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a]"
for (Myset::iterator it = c1.begin();
it != c1.end(); ++it)
{
Myset::const_pointer p = &*it;
std::cout << "[" << *p << "] ";
}
std::cout << std::endl;
return (0);
}
[c] [b] [a]
unordered_multiset:: const_referenceunordered_multiset::const_reference
Тип постоянной ссылки на элемент.The type of a constant reference to an element.
typedef Alloc::const_reference const_reference;
КомментарииRemarks
Тип описывает объект, который можно использовать в качестве постоянной ссылки на элемент управляемой последовательности.The type describes an object that can serve as a constant reference to an element of the controlled sequence.
ПримерExample
// std__unordered_set__unordered_multiset_const_reference.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a]"
for (Myset::iterator it = c1.begin();
it != c1.end(); ++it)
{
Myset::const_reference ref = *it;
std::cout << "[" << ref << "] ";
}
std::cout << std::endl;
return (0);
}
[c] [b] [a]
unordered_multiset:: Containsunordered_multiset::contains
Проверяет, существует ли элемент с указанным ключом в unordered_multiset
.Checks if there's an element with the specified key in the unordered_multiset
.
bool contains(const Key& key) const;
template<class K> bool contains(const K& key) const;
ПараметрыParameters
ЗанятK
Тип ключа.The type of the key.
разделkey
Искомое значение ключа элемента.The element's key value to look for.
Возвращаемое значениеReturn Value
true
значение, если элемент найден в контейнере; false
в противном случае — значение.true
if the element is found in the container; false
otherwise.
КомментарииRemarks
contains()
Новое в C++ 20.contains()
is new in C++20. Чтобы использовать его, укажите параметр компилятора /std: c + + Latest .To use it, specify the /std:c++latest compiler option.
template<class K> bool contains(const K& key) const
принимает участие в разрешении перегрузки только в key_compare
том случае, если является прозрачным.template<class K> bool contains(const K& key) const
only participates in overload resolution if key_compare
is transparent.
ПримерExample
// Requires /std:c++latest
#include <unordered_set>
#include <iostream>
int main()
{
std::unordered_multiset<int> theUnorderedMultiset = { 1, 2, 3 };
std::cout << std::boolalpha; // so booleans show as 'true' or 'false'
std::cout << theUnorderedMultiset.contains(1) << '\n';
std::cout << theUnorderedMultiset.contains(4) << '\n';
return 0;
}
true
false
unordered_multiset:: countunordered_multiset::count
Определяет количество элементов, соответствующих заданному ключу.Finds the number of elements matching a specified key.
size_type count(const Key& keyval) const;
ПараметрыParameters
кэйвалkeyval
Искомое значение ключа.Key value to search for.
КомментарииRemarks
Функция – член возвращает количество элементов в диапазоне, ограниченном unordered_multiset:: equal_range (keyval)
.The member function returns the number of elements in the range delimited by unordered_multiset::equal_range(keyval)
.
ПримерExample
// std__unordered_set__unordered_multiset_count.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a]"
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
std::cout << "count('A') == " << c1.count('A') << std::endl;
std::cout << "count('b') == " << c1.count('b') << std::endl;
std::cout << "count('C') == " << c1.count('C') << std::endl;
return (0);
}
[c] [b] [a]
count('A') == 0
count('b') == 1
count('C') == 0
unordered_multiset::d ifference_typeunordered_multiset::difference_type
Тип расстояния со знаком между двумя элементами.The type of a signed distance between two elements.
typedef T3 difference_type;
КомментарииRemarks
Тип целого числа со знаком описывает объект, который может представлять разницу между адресами любых двух элементов в управляемой последовательности.The signed integer type describes an object that can represent the difference between the addresses of any two elements in the controlled sequence. Он описан здесь как синоним для типа T3
, определяемого реализацией.It is described here as a synonym for the implementation-defined type T3
.
ПримерExample
// std__unordered_set__unordered_multiset_difference_type.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a]"
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
// compute positive difference
Myset::difference_type diff = 0;
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
++diff;
std::cout << "end()-begin() == " << diff << std::endl;
// compute negative difference
diff = 0;
for (Myset::const_iterator it = c1.end();
it != c1.begin(); --it)
--diff;
std::cout << "begin()-end() == " << diff << std::endl;
return (0);
}
[c] [b] [a]
end()-begin() == 3
begin()-end() == -3
unordered_multiset:: emplaceunordered_multiset::emplace
Вставляет элемент, созданный на месте (операции копирования или перемещения не выполняются).Inserts an element constructed in place (no copy or move operations are performed).
template <class... Args>
iterator emplace(Args&&... args);
ПараметрыParameters
argsargs
Аргументы, передаваемые для создания элемента, который будет вставлен в объект unordered_multiset.The arguments forwarded to construct an element to be inserted into the unordered_multiset.
Возвращаемое значениеReturn Value
Итератор, указывающий на вновь вставленный элемент.An iterator to the newly inserted element.
КомментарииRemarks
Эта функция не делает недействительными никакие ссылки на элементы контейнера, но она может сделать недействительными все итераторы к контейнеру.No references to container elements are invalidated by this function, but it may invalidate all iterators to the container.
Если во время вставки возникает исключение, но оно произошло не в хэш-функции контейнера, контейнер не изменяется.During the insertion, if an exception is thrown but does not occur in the container's hash function, the container is not modified. Если исключение вызывается в хэш-функции, результат не определен.If the exception is thrown in the hash function, the result is undefined.
Пример кода см. в разделе multiset::emplace.For a code example, see multiset::emplace.
unordered_multiset:: emplace_hintunordered_multiset::emplace_hint
Вставляет созданный элемент на место (операции копирования или перемещения не выполняются) с указанием о размещении.Inserts an element constructed in place (no copy or move operations are performed), with a placement hint.
template <class... Args>
iterator emplace_hint(
const_iterator where,
Args&&... args);
ПараметрыParameters
argsargs
Аргументы, передаваемые для создания элемента, который будет вставлен в объект unordered_multiset.The arguments forwarded to construct an element to be inserted into the unordered_multiset.
которомуwhere
Подсказка о месте начала поиска правильной точки вставки.A hint regarding the place to start searching for the correct point of insertion.
Возвращаемое значениеReturn Value
Итератор, указывающий на вновь вставленный элемент.An iterator to the newly inserted element.
КомментарииRemarks
Эта функция не делает недействительными никакие ссылки на элементы контейнера, но она может сделать недействительными все итераторы к контейнеру.No references to container elements are invalidated by this function, but it may invalidate all iterators to the container.
Если во время вставки возникает исключение, но оно произошло не в хэш-функции контейнера, контейнер не изменяется.During the insertion, if an exception is thrown but does not occur in the container's hash function, the container is not modified. Если исключение вызывается в хэш-функции, результат не определен.If the exception is thrown in the hash function, the result is undefined.
Пример кода см. в разделе set::emplace_hint.For a code example, see set::emplace_hint.
unordered_multiset:: Emptyunordered_multiset::empty
Проверяет отсутствие элементов.Tests whether no elements are present.
bool empty() const;
КомментарииRemarks
Эта функция-член возвращает значение true для пустой управляемой последовательности.The member function returns true for an empty controlled sequence.
ПримерExample
// std__unordered_set__unordered_multiset_empty.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a]"
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
// clear the container and reinspect
c1.clear();
std::cout << "size == " << c1.size() << std::endl;
std::cout << "empty() == " << std::boolalpha << c1.empty() << std::endl;
std::cout << std::endl;
c1.insert('d');
c1.insert('e');
// display contents "[e] [d]"
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
std::cout << "size == " << c1.size() << std::endl;
std::cout << "empty() == " << std::boolalpha << c1.empty() << std::endl;
return (0);
}
[c] [b] [a]
size == 0
empty() == true
[e] [d]
size == 2
empty() == false
unordered_multiset:: endunordered_multiset::end
Задает конец управляемой последовательности.Designates the end of the controlled sequence.
iterator end();
const_iterator end() const;
local_iterator end(size_type nbucket);
const_local_iterator end(size_type nbucket) const;
ПараметрыParameters
нбуккетnbucket
Номер сегмента.The bucket number.
КомментарииRemarks
Первые две функции-члены возвращают прямой итератор, указывающий на место сразу за концом последовательности.The first two member functions return a forward iterator that points just beyond the end of the sequence. Последние две функции-члена возвращают прямой итератор, указывающий сразу за концом сегмента нбуккет.The last two member functions return a forward iterator that points just beyond the end of bucket nbucket.
ПримерExample
// std__unordered_set__unordered_multiset_end.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a]"
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
// inspect last two items "[a] [b]"
Myset::iterator it2 = c1.end();
--it2;
std::cout << "[" << *it2 << "] ";
--it2;
std::cout << "[" << *it2 << "] ";
std::cout << std::endl;
// inspect bucket containing 'a'
Myset::const_local_iterator lit = c1.end(c1.bucket('a'));
--lit;
std::cout << "[" << *lit << "] ";
return (0);
}
[c] [b] [a]
[a] [b]
[a]
unordered_multiset:: equal_rangeunordered_multiset::equal_range
Находит диапазон, соответствующий указанному ключу.Finds range that matches a specified key.
std::pair<iterator, iterator>
equal_range(const Key& keyval);
std::pair<const_iterator, const_iterator>
equal_range(const Key& keyval) const;
ПараметрыParameters
кэйвалkeyval
Искомое значение ключа.Key value to search for.
КомментарииRemarks
Функция-член возвращает пару итераторов X
, что [X.first, X.second)
разделяет только те элементы управляемой последовательности, которые имеют эквивалентное упорядочение с помощью кэйвал.The member function returns a pair of iterators X
such that [X.first, X.second)
delimits just those elements of the controlled sequence that have equivalent ordering with keyval. Если таких элементов не существует, оба итератора имеют значение end()
.If no such elements exist, both iterators are end()
.
ПримерExample
// std__unordered_set__unordered_multiset_equal_range.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a]"
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
// display results of failed search
std::pair<Myset::iterator, Myset::iterator> pair1 =
c1.equal_range('x');
std::cout << "equal_range('x'):";
for (; pair1.first != pair1.second; ++pair1.first)
std::cout << "[" << *pair1.first << "] ";
std::cout << std::endl;
// display results of successful search
pair1 = c1.equal_range('b');
std::cout << "equal_range('b'):";
for (; pair1.first != pair1.second; ++pair1.first)
std::cout << "[" << *pair1.first << "] ";
std::cout << std::endl;
return (0);
}
[c] [b] [a]
equal_range('x'):
equal_range('b'): [b]
unordered_multiset:: Eraseunordered_multiset::erase
Удаляет элемент или диапазон элементов в объекте unordered_multiset с заданных позиций или удаляет элементы, соответствующие заданному ключу.Removes an element or a range of elements in a unordered_multiset from specified positions or removes elements that match a specified key.
iterator erase(
const_iterator Where);
iterator erase(
const_iterator First,
const_iterator Last);
size_type erase(
const key_type& Key);
ПараметрыParameters
КоторомуWhere
Положение удаляемого элемента.Position of the element to be removed.
НачальFirst
Положение первого удаляемого элемента.Position of the first element to be removed.
ПоследняяLast
Позиция после последнего элемента для удаления.Position just beyond the last element to be removed.
РазделKey
Значение ключа удаляемых элементов.The key value of the elements to be removed.
Возвращаемое значениеReturn Value
Для первых двух функций-членов двунаправленный итератор, указывающий на первый элемент, оставшийся после удаления элементов, или на последний элемент объекта unordered_multiset, если такого элемента не существует.For the first two member functions, a bidirectional iterator that designates the first element remaining beyond any elements removed, or an element that is the end of the unordered_multiset if no such element exists.
Для третьей функции-члена возвращает число элементов, которые были удалены из объекта unordered_multiset.For the third member function, returns the number of elements that have been removed from the unordered_multiset.
КомментарииRemarks
Пример кода см. в разделе set::erase.For a code example, see set::erase.
unordered_multiset:: Findunordered_multiset::find
Определяет элемент, соответствующий указанному ключу.Finds an element that matches a specified key.
const_iterator find(const Key& keyval) const;
ПараметрыParameters
кэйвалkeyval
Искомое значение ключа.Key value to search for.
КомментарииRemarks
Функция – член возвращает unordered_multiset:: equal_range (keyval).first
.The member function returns unordered_multiset::equal_range(keyval).first
.
ПримерExample
// std__unordered_set__unordered_multiset_find.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a]"
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
// try to find and fail
std::cout << "find('A') == "
<< std::boolalpha << (c1.find('A') != c1.end()) << std::endl;
// try to find and succeed
Myset::iterator it = c1.find('b');
std::cout << "find('b') == "
<< std::boolalpha << (it != c1.end())
<< ": [" << *it << "] " << std::endl;
return (0);
}
[c] [b] [a]
find('A') == false
find('b') == true: [b]
unordered_multiset:: get_allocatorunordered_multiset::get_allocator
Возвращает сохраненный объект распределителя.Gets the stored allocator object.
Alloc get_allocator() const;
КомментарииRemarks
Функция-член возвращает сохраненный объект распределителя.The member function returns the stored allocator object.
ПримерExample
// std__unordered_set__unordered_multiset_get_allocator.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
typedef std::allocator<std::pair<const char, int> > Myalloc;
int main()
{
Myset c1;
Myset::allocator_type al = c1.get_allocator();
std::cout << "al == std::allocator() is "
<< std::boolalpha << (al == Myalloc()) << std::endl;
return (0);
}
al == std::allocator() is true
unordered_multiset:: hash_functionunordered_multiset::hash_function
Получает сохраненный объект хэш-функции.Gets the stored hash function object.
Hash hash_function() const;
КомментарииRemarks
Функция-член возвращает сохраненный объект хэш-функции.The member function returns the stored hash function object.
ПримерExample
// std__unordered_set__unordered_multiset_hash_function.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
Myset::hasher hfn = c1.hash_function();
std::cout << "hfn('a') == " << hfn('a') << std::endl;
std::cout << "hfn('b') == " << hfn('b') << std::endl;
return (0);
}
hfn('a') == 1630279
hfn('b') == 1647086
unordered_multiset:: hashunordered_multiset::hasher
Тип хэш-функции.The type of the hash function.
typedef Hash hasher;
КомментарииRemarks
Этот тип является синонимом для параметра шаблона Hash
.The type is a synonym for the template parameter Hash
.
ПримерExample
// std__unordered_set__unordered_multiset_hasher.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
Myset::hasher hfn = c1.hash_function();
std::cout << "hfn('a') == " << hfn('a') << std::endl;
std::cout << "hfn('b') == " << hfn('b') << std::endl;
return (0);
}
hfn('a') == 1630279
hfn('b') == 1647086
unordered_multiset:: INSERTunordered_multiset::insert
Вставляет элемент или диапазон элементов в unordered_multiset.Inserts an element or a range of elements into an unordered_multiset.
// (1) single element
pair<iterator, bool> insert(
const value_type& Val);
// (2) single element, perfect forwarded
template <class ValTy>
pair<iterator, bool>
insert(
ValTy&& Val);
// (3) single element with hint
iterator insert(
const_iterator Where,
const value_type& Val);
// (4) single element, perfect forwarded, with hint
template <class ValTy>
iterator insert(
const_iterator Where,
ValTy&& Val);
// (5) range
template <class InputIterator>
void insert(
InputIterator First,
InputIterator Last);
// (6) initializer list
void insert(
initializer_list<value_type>
IList);
ПараметрыParameters
ValVal
Значение элемента, вставляемого в unordered_multiset.The value of an element to be inserted into the unordered_multiset.
КоторомуWhere
Место начала поиска правильной точки вставки.The place to start searching for the correct point of insertion.
валтиValTy
Параметр шаблона, указывающий тип аргумента, который unordered_multiset может использовать для создания элемента value_type, и идеальное перенаправление Val в качестве аргумента.Template parameter that specifies the argument type that the unordered_multiset can use to construct an element of value_type, and perfect-forwards Val as an argument.
НачальFirst
Позиция первого элемента, который следует скопировать.The position of the first element to be copied.
ПоследняяLast
Позиция непосредственно перед последним элементом, который следует скопировать.The position just beyond the last element to be copied.
InputIteratorInputIterator
Аргумент функции-шаблона, который соответствует требованиям итератора ввода, указывающего на элементы типа, которые можно использовать для создания объектов value_type.Template function argument that meets the requirements of an input iterator that points to elements of a type that can be used to construct value_type objects.
ИнтерфейсIList
Initializer_list , из которого копируются элементы.The initializer_list from which to copy the elements.
Возвращаемое значениеReturn Value
Одноэлементные функции-члены (1) и (2) возвращают итератор в позиции, где был вставлен новый элемент.The single-element-insert member functions, (1) and (2), return an iterator to the position where the new element was inserted into the unordered_multiset.
Одноэлементные функции-члены с подсказкой (3) и (4) возвращают итератор, указывающий на позицию, где был вставлен новый элемент.The single-element-with-hint member functions, (3) and (4), return an iterator that points to the position where the new element was inserted into the unordered_multiset.
КомментарииRemarks
Эта функция не делает никакие указатели или ссылки недействительными, но она может сделать недействительными все итераторы контейнера.No pointers or references are invalidated by this function, but it may invalidate all iterators to the container.
Если исключение вызывается во время вставки одного элемента, но оно не вызывается в хэш-функции контейнера, состояние контейнера не изменяется.During the insertion of just one element, if an exception is thrown but does not occur in the container's hash function, the container's state is not modified. Если исключение вызывается в хэш-функции, результат не определен.If the exception is thrown in the hash function, the result is undefined. Если во время вставки нескольких элементов вызывается исключение, контейнер остается в неопределенном, но допустимом состоянии.During the insertion of multiple elements, if an exception is thrown, the container is left in an unspecified but valid state.
value_type контейнера — это определение типа, принадлежащее контейнеру и, для набора, unordered_multiset<V>::value_type
имеет тип const V
.The value_type of a container is a typedef that belongs to the container, and, for set, unordered_multiset<V>::value_type
is type const V
.
Функция-член Range (5) вставляет последовательность значений элементов в unordered_multiset, соответствующую каждому элементу, адресованному итератором в диапазоне. [First, Last)
следовательно, Last не вставляется.The range member function (5) inserts the sequence of element values into an unordered_multiset that corresponds to each element addressed by an iterator in the range [First, Last)
; therefore, Last does not get inserted. Контейнер функции-члена end()
ссылается на позицию сразу после последнего элемента в контейнере. Например, оператор m.insert(v.begin(), v.end());
пытается вставить все элементы v
в m
.The container member function end()
refers to the position just after the last element in the container—for example, the statement m.insert(v.begin(), v.end());
inserts all elements of v
into m
.
Функция — член списка инициализаторов (6) использует initializer_list для копирования элементов в unordered_multiset.The initializer list member function (6) uses an initializer_list to copy elements into the unordered_multiset.
Сведения о вставке элемента, созданного на месте (т. е. без выполнения операций копирования или перемещения), см. в описании функций unordered_multiset::emplace и unordered_multiset::emplace_hint.For insertion of an element constructed in place—that is, no copy or move operations are performed—see unordered_multiset::emplace and unordered_multiset::emplace_hint.
Пример кода см. в разделе multiset::insert.For a code example, see multiset::insert.
unordered_multiset:: итераторunordered_multiset::iterator
Тип, предоставляющий прямой итератор константы, может считывать элементы в объекте unordered_multiset.A type that provides a constant forward iterator that can read elements in an unordered_multiset.
typedef implementation-defined iterator;
ПримерExample
Пример объявления и использования итератора см. в разделе begin.See the example for begin for an example of how to declare and use an iterator.
unordered_multiset:: key_equnordered_multiset::key_eq
Получает сохраненный объект функции сравнения.Gets the stored comparison function object.
Pred key_eq() const;
КомментарииRemarks
Функция-член возвращает сохраненный объект функции сравнения.The member function returns the stored comparison function object.
ПримерExample
// std__unordered_set__unordered_multiset_key_eq.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
Myset::key_equal cmpfn = c1.key_eq();
std::cout << "cmpfn('a', 'a') == "
<< std::boolalpha << cmpfn('a', 'a') << std::endl;
std::cout << "cmpfn('a', 'b') == "
<< std::boolalpha << cmpfn('a', 'b') << std::endl;
return (0);
}
cmpfn('a', 'a') == true
cmpfn('a', 'b') == false
unordered_multiset:: key_equalunordered_multiset::key_equal
Тип функции сравнения.The type of the comparison function.
typedef Pred key_equal;
КомментарииRemarks
Этот тип является синонимом для параметра шаблона Pred
.The type is a synonym for the template parameter Pred
.
ПримерExample
// std__unordered_set__unordered_multiset_key_equal.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
Myset::key_equal cmpfn = c1.key_eq();
std::cout << "cmpfn('a', 'a') == "
<< std::boolalpha << cmpfn('a', 'a') << std::endl;
std::cout << "cmpfn('a', 'b') == "
<< std::boolalpha << cmpfn('a', 'b') << std::endl;
return (0);
}
cmpfn('a', 'a') == true
cmpfn('a', 'b') == false
unordered_multiset:: key_typeunordered_multiset::key_type
Тип ключа упорядочения.The type of an ordering key.
typedef Key key_type;
КомментарииRemarks
Этот тип является синонимом для параметра шаблона Key
.The type is a synonym for the template parameter Key
.
ПримерExample
// std__unordered_set__unordered_multiset_key_type.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a]"
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
// add a value and reinspect
Myset::key_type key = 'd';
Myset::value_type val = key;
c1.insert(val);
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
return (0);
}
[c] [b] [a]
[d] [c] [b] [a]
unordered_multiset:: load_factorunordered_multiset::load_factor
Подсчитывает среднее число элементов в блоке.Counts the average elements per bucket.
float load_factor() const;
КомментарииRemarks
Функция – член возвращает (float)
unordered_multiset:: size () / (float)
unordered_multiset:: bucket_count ()
, среднее число элементов на сегмент.The member function returns (float)
unordered_multiset::size() / (float)
unordered_multiset::bucket_count()
, the average number of elements per bucket.
ПримерExample
// std__unordered_set__unordered_multiset_load_factor.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a]"
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
// inspect current parameters
std::cout << "bucket_count() == " << c1.bucket_count() << std::endl;
std::cout << "load_factor() == " << c1.load_factor() << std::endl;
std::cout << "max_bucket_count() == "
<< c1.max_bucket_count() << std::endl;
std::cout << "max_load_factor() == "
<< c1.max_load_factor() << std::endl;
std::cout << std::endl;
// change max_load_factor and redisplay
c1.max_load_factor(0.10f);
std::cout << "bucket_count() == " << c1.bucket_count() << std::endl;
std::cout << "load_factor() == " << c1.load_factor() << std::endl;
std::cout << "max_bucket_count() == "
<< c1.max_bucket_count() << std::endl;
std::cout << "max_load_factor() == "
<< c1.max_load_factor() << std::endl;
std::cout << std::endl;
// rehash and redisplay
c1.rehash(100);
std::cout << "bucket_count() == " << c1.bucket_count() << std::endl;
std::cout << "load_factor() == " << c1.load_factor() << std::endl;
std::cout << "max_bucket_count() == "
<< c1.max_bucket_count() << std::endl;
std::cout << "max_load_factor() == "
<< c1.max_load_factor() << std::endl;
std::cout << std::endl;
return (0);
}
unordered_multiset:: local_iteratorunordered_multiset::local_iterator
Тип итератора контейнера.The type of a bucket iterator.
typedef T4 local_iterator;
КомментарииRemarks
Этот тип описывает объект, который можно использовать в качестве прямого итератора для контейнера.The type describes an object that can serve as a forward iterator for a bucket. Он описан здесь как синоним для типа T4
, определяемого реализацией.It is described here as a synonym for the implementation-defined type T4
.
ПримерExample
// std__unordered_set__unordered_multiset_local_iterator.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a]"
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
// inspect bucket containing 'a'
Myset::local_iterator lit = c1.begin(c1.bucket('a'));
std::cout << "[" << *lit << "] ";
return (0);
}
[c] [b] [a]
[a]
unordered_multiset:: max_bucket_countunordered_multiset::max_bucket_count
Получает максимальное количество блоков.Gets the maximum number of buckets.
size_type max_bucket_count() const;
КомментарииRemarks
Функция-член возвращает максимальное количество блоков, которое разрешено в настоящее время.The member function returns the maximum number of buckets currently permitted.
ПримерExample
// std__unordered_set__unordered_multiset_max_bucket_count.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a]"
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
// inspect current parameters
std::cout << "bucket_count() == " << c1.bucket_count() << std::endl;
std::cout << "load_factor() == " << c1.load_factor() << std::endl;
std::cout << "max_bucket_count() == "
<< c1.max_bucket_count() << std::endl;
std::cout << "max_load_factor() == "
<< c1.max_load_factor() << std::endl;
std::cout << std::endl;
// change max_load_factor and redisplay
c1.max_load_factor(0.10f);
std::cout << "bucket_count() == " << c1.bucket_count() << std::endl;
std::cout << "load_factor() == " << c1.load_factor() << std::endl;
std::cout << "max_bucket_count() == "
<< c1.max_bucket_count() << std::endl;
std::cout << "max_load_factor() == "
<< c1.max_load_factor() << std::endl;
std::cout << std::endl;
// rehash and redisplay
c1.rehash(100);
std::cout << "bucket_count() == " << c1.bucket_count() << std::endl;
std::cout << "load_factor() == " << c1.load_factor() << std::endl;
std::cout << "max_bucket_count() == "
<< c1.max_bucket_count() << std::endl;
std::cout << "max_load_factor() == "
<< c1.max_load_factor() << std::endl;
std::cout << std::endl;
return (0);
}
[c] [b] [a]
bucket_count() == 8
load_factor() == 0.375
max_bucket_count() == 8
max_load_factor() == 4
bucket_count() == 8
load_factor() == 0.375
max_bucket_count() == 8
max_load_factor() == 0.1
bucket_count() == 128
load_factor() == 0.0234375
max_bucket_count() == 128
max_load_factor() == 0.1
unordered_multiset:: max_load_factorunordered_multiset::max_load_factor
Возвращает или задает максимальное количество элементов в блоке.Gets or sets the maximum elements per bucket.
float max_load_factor() const;
void max_load_factor(float factor);
ПараметрыParameters
многофакторнойfactor
Новый коэффициент максимальной нагрузки.The new maximum load factor.
КомментарииRemarks
Первая функция-член возвращает сохраненный коэффициент максимальной нагрузки.The first member function returns the stored maximum load factor. Вторая функция – член заменяет хранимую максимальную степень нагрузки на Коэффициент.The second member function replaces the stored maximum load factor with factor.
ПримерExample
// std__unordered_set__unordered_multiset_max_load_factor.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a]"
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
// inspect current parameters
std::cout << "bucket_count() == " << c1.bucket_count() << std::endl;
std::cout << "load_factor() == " << c1.load_factor() << std::endl;
std::cout << "max_bucket_count() == "
<< c1.max_bucket_count() << std::endl;
std::cout << "max_load_factor() == "
<< c1.max_load_factor() << std::endl;
std::cout << std::endl;
// change max_load_factor and redisplay
c1.max_load_factor(0.10f);
std::cout << "bucket_count() == " << c1.bucket_count() << std::endl;
std::cout << "load_factor() == " << c1.load_factor() << std::endl;
std::cout << "max_bucket_count() == "
<< c1.max_bucket_count() << std::endl;
std::cout << "max_load_factor() == "
<< c1.max_load_factor() << std::endl;
std::cout << std::endl;
// rehash and redisplay
c1.rehash(100);
std::cout << "bucket_count() == " << c1.bucket_count() << std::endl;
std::cout << "load_factor() == " << c1.load_factor() << std::endl;
std::cout << "max_bucket_count() == "
<< c1.max_bucket_count() << std::endl;
std::cout << "max_load_factor() == "
<< c1.max_load_factor() << std::endl;
std::cout << std::endl;
return (0);
}
[c] [b] [a]
bucket_count() == 8
load_factor() == 0.375
max_bucket_count() == 8
max_load_factor() == 4
bucket_count() == 8
load_factor() == 0.375
max_bucket_count() == 8
max_load_factor() == 0.1
bucket_count() == 128
load_factor() == 0.0234375
max_bucket_count() == 128
max_load_factor() == 0.1
unordered_multiset:: max_sizeunordered_multiset::max_size
Возвращает максимальный размер управляемой последовательности.Gets the maximum size of the controlled sequence.
size_type max_size() const;
КомментарииRemarks
Функция-член возвращает длину самой длинной последовательности, которой объект может управлять.The member function returns the length of the longest sequence that the object can control.
ПримерExample
// std__unordered_set__unordered_multiset_max_size.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
std::cout << "max_size() == " << c1.max_size() << std::endl;
return (0);
}
max_size() == 4294967295
unordered_multiset:: operator =unordered_multiset::operator=
Копирует хэш-таблицу.Copies a hash table.
unordered_multiset& operator=(const unordered_multiset& right);
unordered_multiset& operator=(unordered_multiset&& right);
ПараметрыParameters
Правильноright
unordered_multiset копируется в unordered_multiset
.The unordered_multiset being copied into the unordered_multiset
.
КомментарииRemarks
После стирания любых существующих элементов в unordered_multiset
operator=
копирует или перемещает содержимое непосредственно в unordered_multiset
.After erasing any existing elements in an unordered_multiset
, operator=
either copies or moves the contents of right into the unordered_multiset
.
ПримерExample
// unordered_multiset_operator_as.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
int main( )
{
using namespace std;
unordered_multiset<int> v1, v2, v3;
unordered_multiset<int>::iterator iter;
v1.insert(10);
cout << "v1 = " ;
for (iter = v1.begin(); iter != v1.end(); iter++)
cout << *iter << " ";
cout << endl;
v2 = v1;
cout << "v2 = ";
for (iter = v2.begin(); iter != v2.end(); iter++)
cout << *iter << " ";
cout << endl;
// move v1 into v2
v2.clear();
v2 = move(v1);
cout << "v2 = ";
for (iter = v2.begin(); iter != v2.end(); iter++)
cout << *iter << " ";
cout << endl;
}
unordered_multiset::p оинтерunordered_multiset::pointer
Тип указателя на элемент.The type of a pointer to an element.
typedef Alloc::pointer pointer;
КомментарииRemarks
Этот тип описывает объект, который можно использовать в качестве указателя на элемент управляемой последовательности.The type describes an object that can serve as a pointer to an element of the controlled sequence.
ПримерExample
// std__unordered_set__unordered_multiset_pointer.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a]"
for (Myset::iterator it = c1.begin();
it != c1.end(); ++it)
{
Myset::key_type key = *it;
Myset::pointer p = &key;
std::cout << "[" << *p << "] ";
}
std::cout << std::endl;
return (0);
}
[c] [b] [a]
unordered_multiset:: Referenceunordered_multiset::reference
Тип ссылки на элемент.The type of a reference to an element.
typedef Alloc::reference reference;
КомментарииRemarks
Тип описывает объект, который можно использовать в качестве ссылки на элемент управляемой последовательности.The type describes an object that can serve as a reference to an element of the controlled sequence.
ПримерExample
// std__unordered_set__unordered_multiset_reference.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a]"
for (Myset::iterator it = c1.begin();
it != c1.end(); ++it)
{
Myset::key_type key = *it;
Myset::reference ref = key;
std::cout << "[" << ref << "] ";
}
std::cout << std::endl;
return (0);
}
[c] [b] [a]
unordered_multiset:: rehashunordered_multiset::rehash
Повторно создает хэш-таблицу.Rebuilds the hash table.
void rehash(size_type nbuckets);
ПараметрыParameters
нбуккетсnbuckets
Требуемое число сегментов.The requested number of buckets.
КомментарииRemarks
Функция-член изменяет количество контейнеров, чтобы они были как минимум нбуккетс и перестраивает хэш-таблицу по мере необходимости.The member function alters the number of buckets to be at least nbuckets and rebuilds the hash table as needed.
ПримерExample
// std__unordered_set__unordered_multiset_rehash.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a]"
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
// inspect current parameters
std::cout << "bucket_count() == " << c1.bucket_count() << std::endl;
std::cout << "load_factor() == " << c1.load_factor() << std::endl;
std::cout << "max_load_factor() == " << c1.max_load_factor() << std::endl;
std::cout << std::endl;
// change max_load_factor and redisplay
c1.max_load_factor(0.10f);
std::cout << "bucket_count() == " << c1.bucket_count() << std::endl;
std::cout << "load_factor() == " << c1.load_factor() << std::endl;
std::cout << "max_load_factor() == " << c1.max_load_factor() << std::endl;
std::cout << std::endl;
// rehash and redisplay
c1.rehash(100);
std::cout << "bucket_count() == " << c1.bucket_count() << std::endl;
std::cout << "load_factor() == " << c1.load_factor() << std::endl;
std::cout << "max_load_factor() == " << c1.max_load_factor() << std::endl;
return (0);
}
[c] [b] [a]
bucket_count() == 8
load_factor() == 0.375
max_load_factor() == 4
bucket_count() == 8
load_factor() == 0.375
max_load_factor() == 0.1
bucket_count() == 128
load_factor() == 0.0234375
max_load_factor() == 0.1
unordered_multiset:: sizeunordered_multiset::size
Подсчитывает количество элементов.Counts the number of elements.
size_type size() const;
КомментарииRemarks
Функция-член возвращает длину управляемой последовательности.The member function returns the length of the controlled sequence.
ПримерExample
// std__unordered_set__unordered_multiset_size.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a]"
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
// clear the container and reinspect
c1.clear();
std::cout << "size == " << c1.size() << std::endl;
std::cout << "empty() == " << std::boolalpha << c1.empty() << std::endl;
std::cout << std::endl;
c1.insert('d');
c1.insert('e');
// display contents "[e] [d]"
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
std::cout << "size == " << c1.size() << std::endl;
std::cout << "empty() == " << std::boolalpha << c1.empty() << std::endl;
return (0);
}
[c] [b] [a]
size == 0
empty() == true
[e] [d]
size == 2
empty() == false
unordered_multiset:: size_typeunordered_multiset::size_type
Тип беззнакового расстояния между двумя элементами.The type of an unsigned distance between two elements.
typedef T2 size_type;
КомментарииRemarks
Целочисленный тип без знака описывает объект, который может представлять длину любой управляемой последовательности.The unsigned integer type describes an object that can represent the length of any controlled sequence. Он описан здесь как синоним для типа T2
, определяемого реализацией.It is described here as a synonym for the implementation-defined type T2
.
ПримерExample
// std__unordered_set__unordered_multiset_size_type.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
Myset::size_type sz = c1.size();
std::cout << "size == " << sz << std::endl;
return (0);
}
size == 0
unordered_multiset:: swapunordered_multiset::swap
Меняет местами содержимое двух контейнеров.Swaps the contents of two containers.
void swap(unordered_multiset& right);
ПараметрыParameters
Правильноright
Контейнер для замены.The container to swap with.
КомментарииRemarks
Функция – член меняет местами управляемые последовательности между *this
и вправо.The member function swaps the controlled sequences between *this
and right. Если unordered_multiset:: get_allocator () == right.get_allocator()
, он делает это в константном времени, он создает исключение только в результате копирования сохраненного объекта признаков типа Tr
и не делает недействительными ссылки, указатели или итераторы, обозначающие элементы в двух управляемых последовательностях.If unordered_multiset::get_allocator() == right.get_allocator()
, it does so in constant time, it throws an exception only as a result of copying the stored traits object of type Tr
, and it invalidates no references, pointers, or iterators that designate elements in the two controlled sequences. В противном случае она выполняет ряд назначений элементов и вызовов конструктора, пропорционально количеству элементов в двух управляемых последовательностях.Otherwise, it performs a number of element assignments and constructor calls proportional to the number of elements in the two controlled sequences.
ПримерExample
// std__unordered_set__unordered_multiset_swap.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a]"
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
Myset c2;
c2.insert('d');
c2.insert('e');
c2.insert('f');
c1.swap(c2);
// display contents "[f] [e] [d]"
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
swap(c1, c2);
// display contents "[c] [b] [a]"
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
return (0);
}
[c] [b] [a]
[f] [e] [d]
[c] [b] [a]
unordered_multiset:: unordered_multisetunordered_multiset::unordered_multiset
Создает объект контейнера.Constructs a container object.
unordered_multiset(
const unordered_multiset& Right);
explicit unordered_multiset(
size_type Bucket_count = N0,
const Hash& Hash = Hash(),
const Comp& Comp = Comp(),
const Allocator& Al = Alloc());
unordered_multiset(
unordered_multiset&& Right);
unordered_set(
initializer_list<Type> IList);
unordered_set(
initializer_list<Typ> IList,
size_type Bucket_count);
unordered_set(
initializer_list<Type> IList,
size_type Bucket_count,
const Hash& Hash);
unordered_set(
initializer_list<Type> IList,
size_type Bucket_count,
const Hash& Hash,
const Key& Key);
unordered_set(
initializer_list<Type> IList,
size_type Bucket_count,
const Hash& Hash,
const Key& Key,
const Allocator& Al);
template <class InputIterator>
unordered_multiset(
InputIterator First,
InputIterator Last,
size_type Bucket_count = N0,
const Hash& Hash = Hash(),
const Comp& Comp = Comp(),
const Allocator& Al = Alloc());
ПараметрыParameters
InputIteratorInputIterator
Тип итератора.The iterator type.
AlAl
Объект распределителя для сохранения.The allocator object to store.
СоответствовалComp
Объект функции сравнения для сохранения.The comparison function object to store.
ФункцииHash
Объект хэш-функции для сохранения.The hash function object to store.
Bucket_countBucket_count
Минимальное количество блоков.The minimum number of buckets.
ПравильноRight
Контейнер для копирования.The container to copy.
ИнтерфейсIList
Объект initializer_list, из которого следует выполнить копирование.The initializer_list from which to copy.
КомментарииRemarks
Первый конструктор задает копию последовательности, управляемой по правому краю.The first constructor specifies a copy of the sequence controlled by Right. Второй конструктор определяет управляемую пустую последовательность.The second constructor specifies an empty controlled sequence. Третий конструктор добавляет последовательность значений элементов [First, Last)
.The third constructor inserts the sequence of element values [First, Last)
. Четвертый конструктор указывает копию последовательности, перемещая ее вправо.The fourth constructor specifies a copy of the sequence by moving Right.
Все конструкторы также инициализируют ряд сохраненных значений.All constructors also initialize several stored values. Для конструктора копии значения получаются справа.For the copy constructor, the values are obtained from Right. В противном случае:Otherwise:
Минимальное число контейнеров — аргумент, Bucket_count, если он есть; в противном случае это значение по умолчанию, описываемое здесь как значение, определяемое реализацией N0
.The minimum number of buckets is the argument Bucket_count, if present; otherwise it is a default value described here as the implementation-defined value N0
.
Объект хэш-функции — это хэшаргумента, если он есть; в противном случае — значение Hash()
.The hash function object is the argument Hash, if present; otherwise it is Hash()
.
Объект функции сравнения — это аргумент comp, если он есть; в противном случае — значение Comp()
.The comparison function object is the argument Comp, if present; otherwise it is Comp()
.
Объект распределителя — это аргумент Al, если он есть; в противном случае — значение Alloc()
.The allocator object is the argument Al, if present; otherwise, it is Alloc()
.
unordered_multiset:: value_typeunordered_multiset::value_type
Тип элемента.The type of an element.
typedef Key value_type;
КомментарииRemarks
Тип описывает элемент управляемой последовательности.The type describes an element of the controlled sequence.
ПримерExample
// std__unordered_set__unordered_multiset_value_type.cpp
// compile with: /EHsc
#include <unordered_set>
#include <iostream>
typedef std::unordered_multiset<char> Myset;
int main()
{
Myset c1;
c1.insert('a');
c1.insert('b');
c1.insert('c');
// display contents "[c] [b] [a]"
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
// add a value and reinspect
Myset::key_type key = 'd';
Myset::value_type val = key;
c1.insert(val);
for (Myset::const_iterator it = c1.begin();
it != c1.end(); ++it)
std::cout << "[" << *it << "] ";
std::cout << std::endl;
return (0);
}
[c] [b] [a]
[d] [c] [b] [a]
См. также разделSee also
<unordered_set><unordered_set>
КонтейнераContainers
Безопасность потоков в стандартной библиотеке C++Thread Safety in the C++ Standard Library
Справочник по стандартной библиотеке C++C++ Standard Library Reference