c++vectorsize-type

Use `vector<A>::size_type ix` to index `vector<B>`


This may be a trivial question. Usually, I need to define local std::vectors like vector<int>, vector<double> etc to store some intermediate values for a vector<A> where A is a self-defined class. These local vectors are supposed to have the same size as the vector<A>.

The problem is, when I write some for to assign values from vector<A> to the local vectors, is it bad practice to write it like (PS: the size of vect_a remains unchanged in the loop.)

vector<A> vect_a;
vector<int> local_vect;
...
for (vector<A>::size_type ix = 0; ix != vect_a.size(); ++ix) {
    local_vect[ix] = vect_a[ix].get_mem_var();
    ...
}

where get_mem_var() simply returns the int mem_var of A. Specifically, my concern is, local_vect is of vector<int>, not vector<A>, but it still uses ix, which is of vector<A>::size_type instead of vector<int>::size_type.

Sometimes I make it a bit more complex, like

for (struct {vector<A>::size_type ix; vector<int>::size_type iy;}
        gi = {0, 0}; gi.ix != vect_a.size(); ++gi.ix, ++gi.iy) {
    local_vect[gi.iy] = vect_a[gi.ix].get_mem_var();
    ...
}

But it feels redundant and unnecessary. I've heard size_type is often simply size_t, and using vector<A>::size_type ix for indexing vector<int> local_vect may just be OK. But is this bad practice in some way? A more general question is, is it OK to use vector<A>::size_type ix to index vector<A> and vector<B> (A and B can be built-in or user-defined) if we know vector<A> and vector<B> are supposed to have the same size?


Solution

  • Realistically, std::vector<T>::size_type is likely to be the same for any T, and so this isn't something that you need to worry about.

    You can avoid worrying about this however by using std::transform, for example something like:

    vector<A> vect_a;
    vector<int> local_vect;
    
    std::transform(std::begin(vect_a), std::begin(vect_b), std::begin(local_vect),
                   [] (const A& a) { return a.get_mem_var(); });