Alex Rivera | Logout

c++: Select a subset of a std::vector, based predefined element indices

Asked 2012-03-10T22:20:05.013
8

I am looking for an efficient way of either trimming or copying a subset of an existing std::vector. The criteria for elements to be eligible for the subset / remain is that their index is contained in a separate predefined std::vector.

e.g std::vector<String> Test = { "A", "B", "C", "D", "E"}

std::vector<int> SelectionV = {1,2,5}

Result = {"A", "B", "E"}

I will be doing this on a very large vector and probably on a regular basis, so am looking for as efficient method as possible.

An alternative that I am also considering, but again unsure of an efficient method is...

As the object Test is filled (in my case it is 3rd party defined object), it is the result of a single pass through using an iterator (no direct element access is possible). I was wondering if instead it is possible to only add to the Test vector elements that appear in the count defined in SelectionV

e.g

int count = 0

for (Iterator.begin, Iterator.end(), Iterator++) {
    if (count is a number contained in selectionV)
        add to Test
}

but I assume that will result in a pass through the selectionV on each iteration, which would be far less efficient than simply adding all elements and later selecting a subset.

Any help much appreciated.

Edit
Report

1 Answer

1

You could sort your SelectionV vector by increasing order, and then you could rewrite your for loop something like:

int index = 0, nextInSelectionV = 0;
for (Iterator.begin; nextInSelectionV < SelectionV.lengh() && Iterator.end(); Iterator++) {
    if (index == SelectionV[nextInSelectionV]) {
        add to Test
        nextInSelectionV++;
    }
    index++;
}
answered 2012-03-10T22:28:29.643

Your Answer