One Two Three
One Two Three

Reputation: 23537

casting of an int to vector in C++

I've seen this piece of code and had a hard time understanding how casting a int to a vector<int> could possibly have worked!

 std::vector<int> v = static_cast<std::vector<int>>(10);
 cout << v.size(); // this prints 10

From my understanding, an int is sort of one dimensional, so to speak, whereas a vector is two dimensional.

How can one possibly be cast to another? And if it is possible, I can see a least a dozen ways an int can be cast to a collection of it. Why does this instance choose "size"? Is this some built-in convention?

Upvotes: 3

Views: 1054

Answers (1)

R Sahu
R Sahu

Reputation: 206717

How can one possibly be cast to another?

static_cast<T>(a);

is valid if a can be used to construct an instance of T.

It is equivalent to:

T(a);

From the C++11 Standard:

4 Otherwise, an expression e can be explicitly converted to a type T using a static_cast of the form static_cast<T>(e) if the declaration T t(e); is well-formed, for some invented temporary variable t.

In your case, it is valid since std::vector has the following constructor:

explicit vector( size_type count, 
                 const T& value = T(),
                 const Allocator& alloc = Allocator());

PS

The line

 std::vector<int> v = static_cast<std::vector<int>>(10);

can be simplified to

 std::vector<int> v(10);

It's hard telling why the person who wrote that line of code thought of writing it that way.

Upvotes: 4

Related Questions