Junior — Middle
Could you provide a situation where using std::set is the most appropriate solution?
sobes.tech AI
Answer from AI
std::set in C++ is a container that stores unique elements in sorted order. It is ideal when you need to:
- Store unique values without duplicates.
- Quickly check for the presence of an element (logarithmic search time).
- Iterate over elements in sorted order.
Example scenario: you have a list of users, and you need to store unique user IDs, as well as quickly check if a user is registered.
#include <set>
#include <iostream>
int main() {
std::set<int> userIds;
userIds.insert(101);
userIds.insert(202);
userIds.insert(101); // will not be added again, as it already exists
if (userIds.find(202) != userIds.end()) {
std::cout << "User with ID 202 is registered" << std::endl;
}
}
In such cases, std::set is the optimal choice.