简体   繁体   中英

Index type for user-defined containers

I'm writing a matrix class in C++; which type should I use for indices into the matrix? That is, in the following code:

template <class elem_type>
class matrix
{
public:
  // snip
  elem_type const &operator()(INDEX_TYPE row, INDEX_TYPE column) const;
};

what should INDEX_TYPE be? If the matrix is restricted to small sizes, should I use a potentially smaller integral type?

The type should be unsigned and integer as an index (It's not a general advice). So std::size_t which is compatible with standard types, is suitable.

std::size_t can store the maximum size of a theoretically possible object of any type (including array).

std::size_t is commonly used for array indexing and loop counting.

Small size types have no major benefits for you. Do you have memory limitations? I don't think so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM