Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector size?

Program:

#include<vector>

int main() {
    std::vector<int>::size_type size=3;
    std::vector<int> v{size};
}

when compiled with

g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3

generates error:

ppp.cpp: In function ‘int main()’:
ppp.cpp:5:28: error: narrowing conversion of ‘size’ from ‘std::vector<int>::size_type {aka long unsigned int}’ to ‘int’ inside { } [-fpermissive]
ppp.cpp:5:28: error: narrowing conversion of ‘size’ from ‘std::vector<int>::size_type {aka long unsigned int}’ to ‘int’ inside { } [-fpermissive]

and on http://www.cplusplus.com/reference/stl/vector/vector/ it is written

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

I expected that constructor to be used.

Can somebody explain?

like image 888
Predrag Avatar asked Oct 03 '12 20:10

Predrag


People also ask

How do I find the size of a std::vector?

To get the size of a C++ Vector, you can use size() function on the vector. size() function returns the number of elements in the vector.

What is sizeof vector in C++?

size() – Returns the number of elements in the vector.

Can you change the size of a vector C++?

Vectors are known as dynamic arrays which can change its size automatically when an element is inserted or deleted. This storage is maintained by container. The function alters the container's content in actual by inserting or deleting the elements from it.

Is std::vector fast?

A std::vector can never be faster than an array, as it has (a pointer to the first element of) an array as one of its data members. But the difference in run-time speed is slim and absent in any non-trivial program. One reason for this myth to persist, are examples that compare raw arrays with mis-used std::vectors.


1 Answers

You're not calling the constructor that sets the vector to an initial size.

std::vector<int> v{size};

The above creates a vector containing a single int element with the value size. You're calling this constructor:

vector( std::initializer_list<T> init, const Allocator& alloc = Allocator() );

The braced-initializer list gets deduced as an std::initializer_list<size_type> and then a narrowing conversion must be performed since the vector itself contains ints.

To set the initial size of the vector use:

std::vector<int> v(size);  // parentheses, not braces

Also, the vector constructor you've listed no longer exists, it was removed in C++11 and replaced by the following two constructors:

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

explicit vector( size_type count );

cppreference.com is a much better reference as compared to cplusplus.com.

like image 124
Praetorian Avatar answered Oct 28 '22 08:10

Praetorian