std::transform and move semantics

后端 未结 1 1449
南旧
南旧 2021-02-14 16:48

I\'m using Boost.Filesystem to create a listing of files in a directory. I use boost::filesystem::recursive_directory_iterator and std::copy to put eac

相关标签:
1条回答
  • 2021-02-14 17:45

    This looks like a job for make_move_iterator:

    std::transform(make_move_iterator(buffer.begin()),
                    make_move_iterator(buffer.end()), buffer_native.begin(),
                    [](boost::filesystem::directory_entry&& de) -> std::string
    {
        // still makes copy :/ perhaps native() would work better, I don't know
        std::string temp = de.path().string();
        temp += "\n";
    
        return temp;
    }
    

    A move iterator is simply an iterator which moves its dereference result. Note that the class needs to support move semantics for this to even make a difference; I don't know if Boost FS does.


    Note if your goal is to output them on separate lines, you're doing it wrong. Formatted printing shouldn't require the input data be in a certain format, that defeats the purpose. Adding newlines to your data just to format it to have newlines is nasty. It's handled for you by ostream_iterator anyway:

    std::copy(buffer.begin(), buffer.end(), //               vvvv
                std::ostream_iterator<std::string>(out_file, "\n"));
    

    Anything more complex, make a lambda in for printing; don't modify your data beforehand.

    0 讨论(0)
提交回复
热议问题