Convert vector to vector ( elegant way )

后端 未结 3 2124
旧巷少年郎
旧巷少年郎 2021-02-13 14:46

I would like to know if there is an elegant way or a built-in function to convert vector to vector. What I\'ve done is simp

3条回答
  •  无人及你
    2021-02-13 15:08

    There are many ways, but a standard solution is to use std::transform with a lambda using std::to_string for the conversion :

    std::transform(std::begin(doubleVec),
                   std::end(doubleVec), 
                   std::back_inserter(doubleStr),
                   [](double d) { return std::to_string(d); } 
                  );
    

    And you can wrap that in a function template to make it work with any Standard compliant container :

    template
    void to_string(IteratorIn first, IteratorIn last, IteratorOut out)
    {
        std::transform(first, last, out,
                       [](typename std::iterator_traits::value_type d) { return std::to_string(d); } );
    }
    

    Or in C++14, with a generic lambda :

    template
    void to_string(IteratorIn first, IteratorIn last, IteratorOut out)
    {
        std::transform(first, last, out, [](auto d) { return std::to_string(d); } );
    }
    

    And call it with any container (i.e. it works with std::list, for instance) :

    to_string(std::begin(doubleVec), std::end(doubleVec), std::back_inserter(doubleStr));
    

    Notes :

    • If you don't have a C++11 compiler, write your own to_string function template :

    Example:

    template
    std::string my_to_string(T v)
    {
        std::stringstream ss;
        ss << v;
        return ss.str();
    }
    

    And use it in a similar way :

    std::transform(doubleVec.begin(),
                   doubleVec.end(),
                   std::back_inserter(doubleStr), 
                   my_to_string );
    
    • You should reserve() the memory in the output vector to avoid reallocations during std::transform() :

    e.g. do this :

    std::vector stringVec;
    stringVec.reserve(v.size());   // reserve space for v.size() elements
    

    Live demo

提交回复
热议问题