【问题标题】:c++ and the type size_typec++ 和类型 size_type
【发布时间】:2016-02-05 18:20:34
【问题描述】:

以下代码片段编译失败:

#include <vector>
#include <string.h>
#include <cstddef.h>
#include <stddef.h>

using namespace std;
vector<int> list1{1,3,5,7,11};
size_type s1 = list1.size();

我正在使用 Microsoft Visual Stdio,但我不希望它依赖于编译器。我认为问题在于我没有包含正确的标题。我应该包括什么标题?

鲍勃

【问题讨论】:

  • 您肯定包括了您不需要的标头,以及不存在的标头...#include &lt;cstddef.h&gt; #include &lt;stddef.h&gt;?
  • 当我们这样做的时候,摆脱using namespace std;

标签: c++ visual-studio stl


【解决方案1】:

size_type 是您正在使用的容器的从属名称。你需要

std::vector<int>::size_type

您可以使用std::size_t,因为这是size_type 通常归结为但std::vector&lt;int&gt;::size_type 保证是正确的。

如果你使用的是 C++11 或更高版本,那么你可以忘记这个细节而直接使用

auto s1 = list1.size();

编译器将推断出正确的类型,如果您更改了容器类型,则需要更改此行。

【讨论】:

  • 或者,当然,auto s1 = list1.size();(如果您使用的是 C++11)
  • @rici 我把它加进去了。宣传使用汽车是个好建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-11
  • 2021-04-11
  • 2011-01-14
  • 2011-06-18
  • 2011-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多