gpt4 book ai didi

C++,将 vector 转换为 vector

转载 作者:行者123 更新时间:2023-11-30 01:40:58 25 4
gpt4 key购买 nike

我有一个函数签名,需要 vector<specific_type>作为参数并调用另一个具有 vector<boost::variant<specific_type, ...>> 的函数作为论据。简单的参数转移是行不通的。我发现重新打包是唯一的解决方案,但这可能不是最高效的解决方案。是否可以进行简单的转换?

最小的例子:

#include "boost/variant.hpp"

#include <string>
#include <vector>

typedef boost::variant<int, std::string> test_t;

void inner(std::vector<test_t> a) {}

void outer(std::vector<int> a) {
// the following does not work:
//inner(a);
//inner((std::vector<test_t>) a);
//inner(const_cast<std::vector<test_t>>(a));
//inner(reinterpret_cast<std::vector<test_t>>(a));
//inner(static_cast<std::vector<test_t>>(a));
//inner(dynamic_cast<std::vector<test_t>>(a));

// only "valid" solution
std::vector<test_t> b;
for (const int i : a) {
b.push_back(i);
}
inner(b);
}

int main()
{
std::vector<int> a = { 1, 4, 2 };
outer(a);
}

最佳答案

Is a simple cast somehow possible?

没有。没有这样的类型转换。

this is likely not the most performant solution

正确,我们可以使用 vector range constructor 做得更好:

template< class InputIt >
vector( InputIt first, InputIt last,
const Allocator& alloc = Allocator() );

我们会这样使用:

void outer(std::vector<int> const& a) {
inner({a.begin(), a.end()});
}

关于C++,将 vector<specific_type> 转换为 vector<boost::variant>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42307948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com