簡體   English   中英

std::transform 和 move 語義

[英]std::transform and move semantics

我正在使用 Boost.Filesystem 在目錄中創建文件列表。 我使用boost::filesystem::recursive_directory_iteratorstd::copy將每個路徑放入 std::vector 作為boost::filesystem::directory_entry object。 我希望將 output 作為 std::strings 寫入文件,所以我做了以下操作(\n 以避免使用 <<):

std::vector<boost::filesystem::directory_entry> buffer; //filled with paths
...
std::vector<std::string> buffer_native(buffer.size());
//transform directory_entry into std::string, and add a \n, so output is formatted without use of <<
std::transform(buffer.begin(),buffer.end(),buffer_native.begin(), [](boost::filesystem::directory_entry de)->std::string
    {
        std::string temp=de.path().string();
        temp+="\n";
        return temp;
    }
    buffer.clear();
    std::copy(buffer_native.begin(),buffer_native.end(),std::ostream_iterator<std::string>(out_file));

然而,這樣做的問題是它創建了兩個向量,其中的原始向量立即被清除,因為它不需要。 這聽起來像是移動語義的完美場所,但 n3242 僅提供與 C++98 中相同的兩個變換重載。 是否可以使用std::transform實現移動語義? 如果不是,編寫自定義循環會更好嗎?

我在 Windows XP 上使用 GCC 4.5.2 (MinGW)。

這看起來像是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;
}

移動迭代器只是一個移動其解引用結果的迭代器。 請注意,class 需要支持移動語義才能發揮作用; 我不知道Boost FS是否可以。


請注意,如果您的目標是 output 將它們放在單獨的行上,那么您做錯了。 格式化打印不應該要求輸入數據采用某種格式,這違背了目的。 在數據中添加換行符只是為了將其格式化為具有換行符是令人討厭的。 無論如何,它都是由ostream_iterator為您處理的:

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

更復雜的,制作一個 lambda 用於打印; 不要事先修改您的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM