Bob
Bob

Reputation: 354

c++ and the type size_type

The following code fragment fails to compile:

#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();

I am using the Microsoft Visual Stdio but I would not expect this to be compiler dependent. I believe the problem is that I am failing to include the correct header. What header should I be including?

Bob

Upvotes: 1

Views: 888

Answers (1)

NathanOliver
NathanOliver

Reputation: 180510

size_type is a dependent name of the container you are using. You need

std::vector<int>::size_type

You could use std::size_t as that is what size_type generally boils down to but std::vector<int>::size_type is guaranteed to be correct.

If you are using C++11 or higher then you can forgot about this detail and just use

auto s1 = list1.size();

The compiler will deduce the correct type and if you ever change the container type this line does need to be changed.

Upvotes: 5

Related Questions