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.
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.
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.
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];});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With