簡體   English   中英

用boost :: algorithms :: join提取和連接字符串

[英]Extracting and joining strings with boost::algorithms::join

我有一個特定結構的集合,我想將每個這些結構的字符串成員加入以分號分隔的列表中。 充分利用標准算法庫和Boost,可以輕松解決問題:

  1. 使用std::transform獲取字符串的集合,然后
  2. 調用boost::algorithm::join將它們連接在一起。

但是,僅復制字符串以供它們join是很愚蠢的,因此我嘗試在字符串周圍使用reference_wrapper作為std::transform的輸出。 相應的代碼可以在這里看到:

struct IPAddress {
    vector<uint8_t> binaryValue;
    string stringValue;
}

// ---snip---

vector<IPAddress> addresses;

// Populate and manipulate the addresses vector
// ---snip---

// Join the list.
vector<reference_wrapper<string>> addressStrings(addresses.size());
transform(begin(addresses), end(addresses), begin(addressStrings),
    [](const IPAddress& addr) {
        return ref(addr.stringValue); // Expodes
    });

return boost::algorithm::join(addressStrings, ";"); // Also explodes

提供給std::transform的lambda無法編譯,聲稱盡管兩個reference_wrapper<string>都已記錄在案 ,但對reference_wrapper的整個要點也沒有匹配。

然后,如果我注釋掉了transform調用,則boost::algorithm::join仍然會通過嘗試調用reference_wrapper的默認構造函數(沒有)而不是string來失敗。

我是否缺少一些簡單明了的東西,還是應該放棄並在迭代器中使用for循環?

在增強范圍的一點幫助下,您可以吃蛋糕並食用。

它消除了這種混合的麻煩:復雜之處在於,您想使用std::string const&的中間集合,但是顯然不適用於std::vector

因此,我們刪除中間集合,而不是使用適應的視圖boost::adaptors::transformed ),並且也不需要lambda [¹],只需使用std::mem_fun :觀看Live on Coliru

#include <boost/algorithm/string.hpp>
#include <boost/range/adaptors.hpp>

#include <vector>
#include <string>
#include <functional>

struct IPAddress {
    std::vector<uint8_t> binaryValue;
    std::string stringValue;
};

std::string foo(std::vector<IPAddress> const& addresses)
{
    using namespace boost::adaptors;
    return boost::algorithm::join(
        addresses | transformed(std::mem_fn(&IPAddress::stringValue)), 
        ";");
}

#include <iostream>

int main()
{
    std::vector<IPAddress> const addresses {
        { {}, "test1" },
        { {}, "test2" },
    };

    std::cout << foo(addresses);
}

打印

test1;test2

[¹]除非stringValue是重載的成員函數

暫無
暫無

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

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