【问题标题】:Assigning unsinged int (with .size()) to 1D float vector将 unsigned int(使用 .size())分配给一维浮点向量
【发布时间】:2021-01-26 04:31:54
【问题描述】:

我是一个完全的编程新手,我的问题对你来说可能完全是微不足道的。我尝试了很多,但无法弄清楚为什么这个程序没有给我错误。这段代码是我一直在做的练习之一。这里的部分代码是将向量vec1中的行数分配给变量rows

当我将unsigned int(带有.size())分配给一维浮点向量时,它应该会给我一个错误,对吧?该练习正在使用此代码并且运行良好。我想知道我错过了什么。

// 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;
}

【问题讨论】:

  • std::vector&lt;float&gt;::size_type 不是向量,是std::vector::size 返回的类型

标签: c++ vector stdvector unsigned-integer size-type


【解决方案1】:

std::vector::size_type是存储容器大小的变量的类型。你想要的是std::vector::value_type。即使这样它也会编译,因为unsigned int 可以分配给float

【讨论】:

  • 我明白了,这很有意义。感谢@krisz 的出色解释!所以,我在某处找到了这样的解释,“将行声明为适合保持向量系统可以容纳的最大可能大小的类型的变量”,那么这样说对吗?跨度>
  • 是的,那句话描述了这行代码的作用:std::vector&lt;float&gt;::size_type rows;
猜你喜欢
  • 2019-10-07
  • 2014-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-28
相关资源
最近更新 更多