Convert vector to vector ( elegant way )

后端 未结 3 2136
旧巷少年郎
旧巷少年郎 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:11

    In general, if you have a container of T and want to create a container of U from the container of T, as others have mentioned the algorithm to look for is std::transform.

    If you are not using C++ 11, Here is std::transform usage:

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    std::string Transformer(double d)
    {
        std::ostringstream doubleStr;
        doubleStr << d;
        return doubleStr.str();
    }
    
    int main()
    {
        std::vector doubleVec;
        doubleVec.push_back(1.0);
        doubleVec.push_back(2.1);
        doubleVec.push_back(3.2);
    
        std::vector doubleStr;
        std::transform(doubleVec.begin(), doubleVec.end(), std::back_inserter(doubleStr), Transformer);
        std::copy(doubleStr.begin(), doubleStr.end(), std::ostream_iterator(std::cout, "  "));
    }
    

    Output: 1 2.1 3.2

提交回复
热议问题