Can we use array as priority_queue element in C++?
Asked Answered
F

1

0

Consider following example:

priority_queue<int[3], vector<int[3]>, greater<int[3]>> pq;
pq.push({{2,3,4}}));
int * x=pq.top();

It says that no matching function found for push().

Of course, we can use a tuple to do the same thing. But I'm just curious can we use array directly.

F answered 1/3, 2020 at 9:19 Comment(2)
Why people use int[3] in c++?Plica
Use std::array.Alpenglow
B
4

You can't do std::vector<int[3]>.

std::vector<T> requires T to be Erasable, which means that the expression

allocator_traits<A>::destroy(m, p)

is well formed. When A = std::allocator<int[3]>, this tries to do

p->~T()

which is equivalent to

(*p).~T()

where p is of type int(*)[3] and T is int[3]. Arrays are not allowed to appear in a pseudo destructor call: [expr.pseudo]/2

The left-hand side of the dot operator shall be of scalar type. [...]

(Arrays are not scalar types.)


You can use std::array<int, 3> though. It is compared in lexicographical order by default.

Barahona answered 1/3, 2020 at 9:42 Comment(3)
would it be possible to write a custom allocator such that c arrays are Erasable (with that allocator) ?Arrear
@463035818_is_not_a_number I guess we can, in principle. It would be a pain to use though - we can't resize the vector, for example, as arrays are still not MoveInsertible.Barahona
yeah I was expecting it to be pain. It was just curiosity. Came here from a almost dupe and my answer says just "not possible", now I wasnt sure if that is right, because Erasable merely requires allocator_traits<A>::destroy(m, p) not moreArrear

© 2022 - 2024 — McMap. All rights reserved.