Good way to copy a std:set<int32_t> to a std::set<uint32_t>

Viewed 476

There is an implicit conversion available between uint32_t and int32_t. I was a little surprised to find that I could not say:

void somefunc(std::set<uint32_t> arg);

std::set<int32_t> ary1;
somefunc(ary1);

Why is this? Is there a short-and-sweet syntax to do it without writing out a for loop to copy the first int32_t array into a temporary uint32_t array?

Thank you.

1 Answers

Standard containers can generally be constructed using ranges from other containers, specified by pairs of iterators. Consider the following example :

#include <cstdint>
#include <set>

void foo(std::set<uint32_t> arg) {}

int main()
{
    std::set<int32_t> x;
    foo({ x.begin(), x.end() });
}

foo expects a std::set<uint32_t> but x is a std::set<int32_t>. {x.begin(), x.begin()} is creating a new temporary std::set<uint32_t> which copies all the values from x. It's similar to std::set<uint32_t>(x.begin(), x.end()) that you might find in older code. This also works between different kinds of containers, provided the contained elements are compatible.

Related