0

My question can be split into two parts:

  1. Is there any advantage in using a shorter integer variable (e.g. short or unsigned char) to loop over array (or stl container) indexes; and
  2. What are the advantages (if any) of using iterators with stl containers.

Code example for problem 1:

const size_t a=100000000;
const unsigned char b=5;
float array[a][b];

for (size_t j=0; j<a; ++j)
  for (unsigned char i=0; i<b; ++i)
    std::cout << array[j][i] << std::endl;

Does using unsigned char in the i-loop save me anything? Does array[j][i] implicitly cast i into a size_t?

Code example for problem 2:

vector<float> a(1000,0.);
vector<float> b(a);

for (size_t i=0; i<a.size(); ++i)
  cout << a[i] << endl;

for (vector<float>::iterator it=b.begin(); it!=b.end(); ++it)
  cout << *it << endl;

Is there an advantage in using the iterator approach? If not in this case, then when? And Why?

Bonus question: In for (size_t i=0; i<a.size(); ++i), is a.size() re-evaluated every time? Do I win anything by getting the size first?

const size_t size = a.size();
for (size_t i=0; i<size; ++i)

Does std::vector simply return the value of a member variable when I call vector::size() or does it do something more elaborate?

SU3
  • 5,064
  • 3
  • 35
  • 66

0 Answers0