C++ Logo

std-proposals

Advanced search

std::vector::indices()

From: Kurt Raburn <kurtekat_at_[hidden]>
Date: Wed, 3 Mar 2021 07:55:46 +0000 (UTC)
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.






Received on 2021-03-03 01:55:53