Remove the jth object from the subset
#include <iostream>
#include <vector>
void removeJthObject(std::vector<int> &subset, int j) {
subset.erase(subset.begin() + j);
}
int main() {
std::vector<int> subset = {1, 2, 3, 4, 5};
int j = 2; // Remove the 3rd element (0-based index)
std::cout << "Subset before removal: ";
for (int num : subset) {
std::cout << num << " ";
}
std::cout << std::endl;
removeJthObject(subset, j);
std::cout << "Subset after removing element at index " << j << ": ";
for (int num : subset) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
Explanation:
#include <iostream>
and#include <vector>
: Including necessary header files for input-output operations and using vectors.void removeJthObject(std::vector<int> &subset, int j)
: Declaring a functionremoveJthObject
that takes a reference to a vector of integers (subset
) and an integer (j
) as parameters. This function removes the jth element from the subset.subset.erase(subset.begin() + j);
: Inside theremoveJthObject
function, theerase
function is used to remove the element at indexj
from thesubset
vector.int main() { / ... / }
: The main function where the program execution begins.std::vector<int> subset = {1, 2, 3, 4, 5};
: Initializing a vector namedsubset
with integers 1, 2, 3, 4, and 5.int j = 2;
: Assigning the value 2 to the variablej
, indicating the index of the element to be removed (0-based index).- Printing the elements of the
subset
vector before the removal operation. removeJthObject(subset, j);
: Calling theremoveJthObject
function to remove the jth element from thesubset
vector.- Printing the elements of the
subset
vector after the removal operation at indexj
.
This code demonstrates how to remove the jth object (element at index j
) from a subset represented as a vector in C++.