This may be a trivial question. Usually, I need to define local std::vector
s like vector<int>
, vector<double>
etc to store some intermediate values for a vector<A>
where A
is a self-defined class. These local vector
s 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 vector
s, 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?
答案 0 :(得分:1)
实际上,std::vector<T>::size_type
可能与任何T
相同,因此您无需担心这一点。
您可以使用std::transform
来避免担心这一点,例如:
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(); });