how to delete an element in vector pair in cpp
To delete an element in a vector<pair>
in C++, you can follow these steps:
- Identify the element you want to delete by its index or some other criteria.
- Use the
erase
function from thevector
class to remove the element.
Here's an example that demonstrates these steps:
#include <iostream>
#include <vector>
int main() {
// Step 1: Create a vector of pairs
std::vector<std::pair<int, std::string>> pairs;
// Add some elements to the vector
pairs.push_back(std::make_pair(1, "Apple"));
pairs.push_back(std::make_pair(2, "Banana"));
pairs.push_back(std::make_pair(3, "Orange"));
// Step 2: Delete the element at index 1
pairs.erase(pairs.begin() + 1);
// Print the remaining elements
for (const auto& pair : pairs) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
In this example, we first create a vector
of pair
objects called pairs
. We add three elements to the vector using the push_back
function.
Next, we use the erase
function to delete the element at index 1. We access the element using the begin()
function of the vector, and then add the index we want to delete to it (in this case, 1).
Finally, we iterate over the remaining elements in the vector and print their values. The output of this example would be:
1: Apple
3: Orange
This shows that the element with index 1 ("Banana") has been successfully deleted from the vector.