【问题标题】:How to map a list of one type to a list of another type in modern c++ using algorithms如何使用算法将一种类型的列表映射到现代 C++ 中的另一种类型的列表
【发布时间】:2021-08-14 05:49:35
【问题描述】:

似乎每个人都同意您需要避免使用原始循环,例如

for (...)
{
   ...
}

同样适用于while...

我正在寻找一种最佳方式来完成从std::list<type_a> 到std::list<type_b> 的映射并遵循这种做法。我的第一个猜测是我需要使用标准算法。我希望是这样的:

std::list<type_a> list_a= {...};
std::list<type_b> list_b= some_algorithms<type_b>(list_a);

我应该选择什么以及最终的解决方案会是什么样子? 我努力尽可能地提供最优雅、最高效的解决方案。

【问题讨论】:

  • std::transform + std::back_inserter?

标签: c++ algorithm


【解决方案1】:

是的,std::transform 也可以做到这一点。

// convert list function
template<typename to_type, typename from_type>
std::list<to_type> convert_list(const std::list<from_type>& from_list)
{
    std::list<to_type> to_list{ from_list.size() };
    std::transform(from_list.cbegin(), from_list.cend(), to_list.begin(), [](const from_type& value) { return convert<to_type>(value); });
    return to_list;
}

【讨论】:

  • 你觉得在这里使用 std::back_inserter 怎么样?什么更好 - 提前保留新列表或在旅途中构建它?
  • 这完全取决于std::list的实际实现。我的直觉是预分配,因为我们可以确定在向列表中添加新项目时它不必在内部增长(重新分配内存)。
【解决方案2】:

我认为任何解决方案都会有某种循环(即使它隐藏在某些标准库算法中)。

我接了你的电话 std::list list_b= some_algorithms(list_a); 作为基础,想出了这个。

#include <stdlib.h>
#include <list>
#include <string>

// in general converting items is just typecasting them
template<typename to_type, typename from_type>
to_type convert(const from_type& value)
{
    return static_cast<to_type>(value);
}

// add specializations for conversion when needed, in this case int to std::string
template<>
std::string convert(const int& value)
{
    return std::to_string(value);
}

// convert list function
template<typename to_type, typename from_type>
std::list<to_type> convert_list(const std::list<from_type>& from_list)
{
    std::list<to_type> to_list;

    for (const auto& value : from_list)
    {
        to_list.push_back(convert<to_type>(value));
    }

    return to_list;
}

int main()
{
    std::list<int> values{ 0,1,42 };
    auto string_values = convert_list<std::string>(values);
}

【讨论】:

  • 根据@Evg 评论,std::transform 是已经以某种方式实现了您的convert_list 的STL 函数。你的(它是正确的,至少我无法发现其中的任何错误)它与cppreference 建议的 std::transform 的“可能实现”非常相似。很可能,STL 的人确实正确地实现了它,考虑到所有的极端情况,高效且更好,然后我可以编写它:让我们充分利用他们的工作
  • @GianPaolo 看起来我必须更详细地查找转换;)
猜你喜欢
  • 1970-01-01
  • 2017-03-28
  • 2021-04-11
  • 1970-01-01
  • 2011-05-30
  • 1970-01-01
  • 2015-08-12
  • 1970-01-01
  • 2011-01-24
相关资源
最近更新 更多