Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 592
oracle3001 Avatar asked Mar 10 '12 22:03

oracle3001


People also ask

How do you choose an element from a vector?

The way you tell R that you want to select some particular elements (i.e., a 'subset') from a vector is by placing an 'index vector' in square brackets immediately following the name of the vector. For a simple example, try x[1:10] to view the first ten elements of x.

How do you find a sub vector in C++?

Getting a subvector from a vector in C++auto last = v. begin() + n + 1. Declare a variable vector of vector type. Pass the value of first and last position of vector.


1 Answers

You can also use the standard library:

std::vector<std::string> Result(SelectionV.size(), 0);

std::transform(SelectionV.begin(), SelectionV.end(), Result.begin(), [Test](size_t pos) {return Test[pos];});

like image 109
user3319226 Avatar answered Oct 28 '22 06:10

user3319226