Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use size_type in my code [closed]

Tags:

c++

I have a set of containers of different types, each of which is associated with a string id. The following function should print the id if the associated container is not empty.

If I want to pass the size of a std::vector to a function, should I pass it as a size_type object? Like this:

void printIfNotEmpty(const std::string& id, size_type sizeOfContainer)
{
   if(sizeOfContainer)
   {
     output << id << " is not empty";
   }
   else
   {
     output << id << " is empty";
   }
}

If so, in what namespace is size_type? How do I included its definition in my code?

Perhaps this is a solution:

template<class T>
void printIfNotEmpty(const std::string& id, const T& container)
{
  if(container.size())
  {
     output << id << " is not empty";
  }
  else
  {
     output << id << " is empty";
  }
}
like image 506
Baz Avatar asked Mar 03 '26 03:03

Baz


2 Answers

should I pass it as a size_type object?

That's the most portable thing to do. (By the way, it's not an "object" in the sense of being a class type; it's an unsigned integer type, large enough to represent the size of any vector).

If you know that it's a vector with a standard allocator, and that's not likely to change in the future, then it might be less verbose to use std::size_t instead.

(Of course, in this simple example, it would make more sense to pass a boolean flag, or to remove the conditional and make the caller responsible for deciding whether to call the function; but I'm assuming that it's intended to represent more complex situations where it does make sense to pass a size around).

If so, in what namespace is size_type?

Each of the standard containers (and any other container that's designed to meet the standard container requirements) defines it as a nested type.

How do I included its definition in my code?

The definition is in <vector>; you must qualify it as std::vector<whatever>::size_type.

std::size_t is defined in <cstddef>.

like image 159
Mike Seymour Avatar answered Mar 05 '26 17:03

Mike Seymour


size_type is in std and, by the way, is not an object. And yes, you ought to use it for portability. For example, in Win64, if you use an int you'll get conversion warnings as size_type is larger than an int on that platform.

But before delving much deeper, see 'size_t' vs 'container::size_type'.

like image 35
Bathsheba Avatar answered Mar 05 '26 17:03

Bathsheba