簡體   English   中英

如何使用 C++ lambda 函數到 map 字符串到向量<int> ?</int>

[英]How to use C++ lambda functions to map string to vector<int>?

我想通過使用 lambda function 來實現轉換

std::string str= "1 2 3";
std::vector<int> result = []()->{}; // result = {1, 2, 3}

如果您想使用 lambda 初始化變量,您的代碼將不會被編譯:

using vec_string_t = std::vector<std::string>;

auto  initializer = [](const std::string &sample)
  {
    vec_string_t  result;
    std::stringstream  stream(sample);

    for (std::string i; stream >> i; )
    {
      result.push_back(i);
    }

    return result;
  };

const auto  test = initializer("1 2 3");

for (const auto &item : test)
{
  std::clog << item << std::endl;
}

需要 header 文件: stringiostreamvectorsstream

暫無
暫無

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

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