【问题标题】:std::vector size?标准::向量大小?
【发布时间】:2012-10-03 20:17:54
【问题描述】:

程序:

#include<vector>

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

编译时使用

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

产生错误:

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]

http://www.cplusplus.com/reference/stl/vector/vector/ 上写着

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

我希望使用该构造函数。

谁能解释一下?

【问题讨论】:

  • 与您的问题无关,但您不需要typename 前面的std::vector&lt;int&gt;::size_type:这里没有依赖名称。
  • @Luc 我删除了它。之所以出现在这里,是因为代码片段取自更复杂的上下文。

标签: c++ vector c++11 std initializer-list


【解决方案1】:

您没有调用将向量设置为初始大小的构造函数。

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

上面创建了一个vector,其中包含一个int 元素,其值为size。你正在调用这个构造函数:

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

花括号初始化器列表被推导出为std::initializer_list&lt;size_type&gt;,然后必须执行缩小转换,因为vector 本身包含ints。

要设置向量的初始大小,请使用:

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

另外,您列出的 vector 构造函数不再存在,它在 C++11 中被删除并被以下两个构造函数替换:

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

explicit vector( size_type count );

cppreference.com 是比 cplusplus.com 更好的参考。

【讨论】:

  • 我确信缩小转换是不允许的,§8.5.4 似乎证实了这一点。但是,我的 GCC 4.8 快照似乎通过警告吞下了这一点。
  • @juanchopanza 我很惊讶它确实如此,也许是回归错误? 4.7.2 complains 符合预期
  • @Prætorian 所以如果我为value_type 选择了其他一些(不能隐式转换为无符号长整数)类型,比如enum A { a, b, c };,会很好吗?
  • @Predrag 反过来,如果 value_type 可以隐式转换为 size_type 并且转换将保留原始值,编译器不会抱怨.但是结果仍然会有所不同,因为您想要一个包含 n 默认初始化元素的向量,而不是得到一个包含单个元素的向量,其中包含值 n
  • @Prætorian:从技术上讲,他是正确的;如果他使用不能隐式转换为size_typevalue_type,那么他可以在初始化器列表中传递size_type 字段,并且由于它无法将其转换为initializer_list&lt;value_type&gt;,它会调用对的。
猜你喜欢
  • 1970-01-01
  • 2020-04-26
  • 1970-01-01
  • 2015-02-17
  • 1970-01-01
  • 2014-12-22
  • 1970-01-01
  • 2021-08-05
相关资源
最近更新 更多