PascalVKooten
PascalVKooten

Reputation: 21461

Using a subset of a QVector in a function

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

Answers (3)

Greenflow
Greenflow

Reputation: 3989

Use the mid method:

a.mid(1,3);

Upvotes: 12

Zlatomir
Zlatomir

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

john
john

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

Related Questions