简体   繁体   中英

How to handle std::vector<…>::size_type being int

I have two vectors:

std::vector<const A> v_a;
std::vector<B> v_b;    

during the program v_a is filled with values. Now i want to transform the values of type A into B and fill v_b .

I start by resizing v_b , please note that std::transform ist not working for me:

v_b.resize(v_a.size());        // Auto-construct new elements using default c-tor

This leads to the following warning:

Value Conversion Issue
-Wsign-conversion
202:55: warning: implicit conversion changes signedness: 'std::vector<const A, std::allocator<const A> >::size_type' (aka 'int') to 'std::vector<B, std::allocator<B> >::size_type' (aka 'unsigned long long')

How is it possible that a vectors size_type is int, it should at least be an unsigned?

How is it possible that two vectors have different size_types? Even if they are defined in different source files the compiler should use the same type. Is it possible to modify the size_type?

How can i (safely) check if v_a.size() < v_b.max_size() without producing new warnings?


The QT-Creator states that i use "Microsof Visual C++ Compiler 15.0 (amd64)" as compiler.

How is it possible that a vector 's size_type is int , it should at least be an unsigned?

This is a problem with the implementation. Per [container.requirements.general]/4 , X::size_type is an unsigned integer type, where X is a Container. A vector is a Container.

How is it possible that two vector s have different size_type s? Even if they are defined in different source files the compiler should use the same type.

Not exactly. Two vector s (with different element types or allocator types) are free to have different size_type s, as long as they are unsigned integer types and can represent any non-negative value of the corresponding difference_type .

Is it possible to modify the size_type ?

No. You cannot directly change the library.

How can I (safely) check if v_a.size() < v_b.max_size() without producing new warnings?

For your current situation, you can use a cast as a workaround.

v_b.resize(static_cast<std::vector<B>::size_type>(v_a.size()));

Again, this is a bug of the implementation anyway, and it is not your fault.

Thanks to LF for answering the questions.

The real problem, as AMA pointed out, is the use of const in the type parameter of v_a . This lead to a compiler-error and ultimately to the warning stated in my question.

The solution was to remove the const-qualifier and fix the dependent types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM