I would like to use an unsigned integer type for indexing a vector,
but I want to use the best and optimal on every platform.
How to implemet?

Recommended Answers

All 3 Replies

Can you give example/timing data of your problem? Maybe you should read up on premature optimization? Int type is supposed to be most optimal in every platform.

I suppose the optimal type would be the one std::vector exposes for you:

std::vector<T> v;

...

// Use the provided size_type
for (std::vector<T>::size_type i = 0; i < v.size(); ++i)
{
    ...
}

That's rather verbose, so you can hide it behind a typedef prior to C++11, or use auto to figure out the type in C++11:

std::vector<T> v;

...

// Use the provided size_type
for (auto i = 0; i < v.size(); ++i)
{
    ...
}

If you need random access to the vector then deceptikons answer is what you should consider. However, if you are iterating over the vector sequentially you would be much better off using an iterator.
As pyTony mentions, it really depends on your situation and application.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.