Question

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.

Was it helpful?

Solution

I must write at least 30 characters so I can tell you, you should try:

a.mid(1,3);

OTHER TIPS

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;
}

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top