Container Template Parameter Value_type

In his presentation over the years, Going Native C ++ Essence (go to 40:30) Bjarne Stroustrup gives the following code example:

template<typename C, typename V>
vector<Value_type<C>*> find_all(C& cont, V v) 
{
    vector<Value_type<C>*> res; 

    for (auto& x : cont) 
        if (x == v) 
            res.push_back(&x)

    return res;
}

This function is used to search for all occurrences of a value in a container and returns pointers to found elements. Video example:

string m{"Mary had a little lamb"}; 
for (const auto p: find_all(m,'a')) // p is a char*
    if (*p != 'a')
        cerr << "string bug!\n"; 

My question is about . Is there something similar in the standard library? I searched for him and did not find it. How can this be implemented if it is not in std? Value_Type<C>*

+4
source share
2 answers

I do not know this in the standard, but it is not difficult to implement it:

    template <class C>
    struct value_type
    {
       typedef typename C::value_type type;
    };

    template <class T, int N>
    struct value_type<T[N]>
    {
       typedef T type;
    };

    template <class T>
    struct value_type<T*>
    {
      typedef T type;
    };

typename value_type<C>::type , . , , value_type typedef ( - ), .

typename ...::type, :

    template <class C>
    using Value_Type = typedef value_type<C>::type;

Value_Type<C> .


stefan, std::begin, , , /, std::begin std::end :

    template <class C>
    using Value_Type = typename std::remove_reference<
        decltype(*std::begin(std::declval<
            typename std::add_lvalue_reference<C>::type>()))>::type;

, . - , , .

+8

Value_type<C> - typedef C::value_type. , , :

template <class T>
using Value_type = typename T::value_type;

template<typename C, typename V>
std::vector<Value_type<C>*> find_all(C& cont, V v)
{
    std::vector<Value_type<C>*> res;

    for (auto& x : cont)
        if (x == v)
            res.push_back(&x);

    return res;
}

int main()
{
    std::vector<int> v{1, 2, 3, 3, 5};

    for(const auto x: find_all(v, 3))
    {
        std::cout << *x << std::endl;
    }
}

, @stefan, . std::begin ( ), @GuyGreer

+3

All Articles