Reputation: 21461
How to send a portion of a QVector to a function?
QVector<int> a;
a.append(1);
a.append(2);
a.append(3);
a.append(4);
a.append(5);
Some printing function should print "2 3 4" taking the subset of the vector as an argument.
In R this would be possible using a[2:4]
.
Is this at all possible?
Note: In the std::vector
, it is advised to use the insert
function to create a new variable. This is a different insert though than QVector
has, and thus I cannot find a recommended method.
Upvotes: 2
Views: 3423
Reputation: 7034
Yes it is possible, but you must pass a pair of iterators (begin and end of the range you want, you can use std::pair to pass only one argument or use a clearer method that take two QVector::iterator
arguments and that way it's clearer that you meant that function to take a range) or if it's simpler to you (or the elements you want are not in continuous order in original QVector) construct another QVector that contains only the selected elements (kind of the solution proposed by john).
Upvotes: 1
Reputation: 88007
You could always write a function to do this operation for you, e.g.
QVector<int> sub_vector(const QVector<int>& vec, size_t from, size_t to)
{
QVector<int> subvec;
for (size_t i = from; i <= to; ++i)
subvec.append(vec[i]);
return subvec;
}
Upvotes: 1