Search code examples
c++vectorstdvectorunsigned-integersize-type

Assigning unsinged int (with .size()) to 1D float vector


I am a complete newbie in programming and my question might be completely trivial to you. I tried a lot but just could not figure out why this program is not giving me an error. This code is part of one of the exercise I have been doing. Part of the code here is to assign number of rows in vector vec1 to variable rows

When I assign a unsigned int (with .size()) to a 1D float vector, it should give me an error, right? The exercise is using this code and its running fine. I am wondering what I am missing to understand.

// Example program
#include <iostream>
#include <vector>

int main()
{
  //declaring a float 1D vector
  std::vector<float> vec1(4,0); 
  //declaring new variable 'row' - Type float - 1D vector
  std::vector<float>::size_type rows;
  
  rows = vec1.size(); // this should give me error because i am assigning a unsigned int(with .size()) to row - 'float 1d vector'.
  
  std::cout<<rows<<std::endl;
}

Solution

  • std::vector::size_type is the type of the variable that stores the size of the container. What you want is std::vector::value_type. Even then it will compile because an unsigned int can be assigned to a float.