Untitled
unknown
c_cpp
2 years ago
1.2 kB
18
Indexable
#include <iostream>
#include <map>
int main() {
// Initialize a dictionary (std::map in this case)
std::map<std::string, int> myDictionary;
// Add items to the dictionary
myDictionary["apple"] = 5;
myDictionary["banana"] = 3;
myDictionary["orange"] = 7;
// Check if an item is present
std::string keyToCheck = "banana";
if (myDictionary.find(keyToCheck) != myDictionary.end()) {
std::cout << keyToCheck << " is present. Value: " << myDictionary[keyToCheck] << std::endl;
} else {
std::cout << keyToCheck << " is not present." << std::endl;
}
// Remove an item
std::string keyToRemove = "banana";
auto it = myDictionary.find(keyToRemove);
if (it != myDictionary.end()) {
myDictionary.erase(it);
std::cout << keyToRemove << " removed." << std::endl;
} else {
std::cout << keyToRemove << " not found, cannot remove." << std::endl;
}
// Iterate over the dictionary
std::cout << "Dictionary elements:" << std::endl;
for (const auto& pair : myDictionary) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
Editor is loading...
Leave a Comment