C++ Logo

std-proposals

Advanced search

Re: std::vector::indices()

From: Edward Catmur <ecatmur_at_[hidden]>
Date: Wed, 3 Mar 2021 15:02:04 +0000
It seems to me that what you really want is a uniform_int_distribution that
accepts a half-open interval. I assume the reason the Standard specifies a
closed interval is to allow a distribution over the whole of an integer
type?

On Wed, Mar 3, 2021 at 9:59 AM Gašper Ažman via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> Not sure if I understand, because it seems so obvious otherwise: you just
> want a function that returns size()-1?
>
> On Wed, Mar 3, 2021 at 7:56 AM Kurt Raburn via Std-Proposals <
> std-proposals_at_[hidden]> wrote:
>
>> hello,
>>
>> i'm not sure if this was my fault, but this is the issue i was having.
>>
>> std::uniform_int_distribution<int> dist(0, vec.size()); // runtime error
>>
>> std::uniform_int_distribution<int> dist(0, vec.size() - 1); // ok
>>
>> after some thought, i wrote a function that returns the index count.
>>
>> template<typename T>
>> int indices(const std::vector<T>& vec)
>> {
>> int cnt = 0;
>>
>> for (T i : vec) {
>> ++cnt;
>> }
>>
>> return --cnt;
>> }
>>
>> then, i modified the size() function, and it returned the same result.
>>
>> _NODISCARD size_type indices() const noexcept
>> {
>> return (static_cast<size_type>(this->_Mylast() - this->_Myfirst()
>> - 1));
>> }
>>
>> usage:
>>
>> std::uniform_int_distribution<int> dist(0, vec.indices());
>>
>> forgive me if i overlooked a library function that would've solved this.
>>
>>
>>
>>
>>
>> --
>> Std-Proposals mailing list
>> Std-Proposals_at_[hidden]
>> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>>
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>

Received on 2021-03-03 09:02:18