我有一个
vector<int>
和只接受 vector<unsigned int>
引用的函数。我知道我可以更改/模板化函数(这可能是最好的事情),但理想情况下我会有一种方法来投射/将 vector<unsigned int>
引用转换为 vector<int>
引用。我知道向量中的所有值都是正数,并且没有一个函数会接近溢出整数。
我尝试过使用
static_cast<vector<int>>
但不起作用。
编辑:
我说的是引用的转换/转换,但我不想创建一个新的副本并引用它。
你不能投射,但你提到转换是一个选项,这很容易完成,如下所示:
void foo(const std::vector<unsigned int>& data)
{
// ...
}
void main()
{
std::vector<int> vec;
foo({ vec.begin(), vec.end() });
}
使用 std::transform 使用转换后的值创建向量的新副本。你不能也不应该用reinterpret_cast在不相关的类型之间进行转换(
std::vector<int> != std::vector<unsigned int>
)
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
int main()
{
std::vector<int> values{ 1,2,3,4,5 };
std::vector<unsigned int> converted_values;
// avoid raw for loops
std::transform(values.begin(), values.end(), std::back_inserter(converted_values), [](const int value)
{
return static_cast<unsigned int>(value);
});
for (const auto& value : convered_values)
{
std::cout << value << " ";
}
return 0;
}
一种 C++20,23 方法是使用范围:
#incluce <ranges>
template<typename result>
constexpr auto cast_trans = std::views::transform( // C++20
[](auto const& x)
{ return static_cast<result>(x); });
std::vector<int> vint;
auto ruint = vint | cast_trans<unsigned>;
auto vuint = ruint | std::ranges::to<std::vector>; // C++23
Ranges 库有很多探索。
没有任何强制转换不会导致未定义的行为,但如果你真的想这样做,那么这可能会在实践中起作用
*reinterpret_cast<vector<unsigned int>*>(&vec)
创建一个指针,转换该指针,然后取消引用。当我还是一名 C 程序员时,我经常做这种事情。
实际上,你不应该这样做。