[英]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 文件: string
、 iostream
、 vector
和sstream
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.