<set>
The <set>
header in C++ provides the std::set
container, which is an associative container that stores unique elements in a specific sorted order. It is part of the C++ Standard Template Library (STL).
std::set
: The main container class for storing unique sorted elementsstd::multiset
: Similar to set
, but allows duplicate elements#include <iostream>
#include <set>
int main() {
std::set<int> numbers = {5, 2, 8, 1, 9};
numbers.insert(3);
numbers.insert(1); // Duplicate, won't be inserted
for (const auto& num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
set
#include <iostream>
#include <set>
int main() {
std::set<int> set1 = {1, 2, 3, 4, 5};
std::set<int> set2 = {4, 5, 6, 7, 8};
// Find element
auto it = set1.find(3);
if (it != set1.end()) {
std::cout << "Found: " << *it << std::endl;
}
// Erase element
set1.erase(4);
// Check if element exists
if (set1.count(4) == 0) {
std::cout << "4 is not in the set" << std::endl;
}
return 0;
}
#include <iostream>
#include <set>
#include <string>
struct CompareLength {
bool operator()(const std::string& lhs, const std::string& rhs) const {
return lhs.length() < rhs.length();
}
};
int main() {
std::set<std::string, CompareLength> words = {"apple", "banana", "cherry", "date"};
for (const auto& word : words) {
std::cout << word << " ";
}
std::cout << std::endl;
return 0;
}
set
is less efficient than unordered_set
for simple storage and retrieval, but maintains a sorted orderlower_bound()
, upper_bound()
, and equal_range()
functions can be used for efficient range queriesset
is particularly useful when you need to maintain a sorted collection of unique elementsThe <set>
header in C++ provides the std::set
container, which is ideal for storing unique elements in a sorted order. It offers logarithmic time complexity for most operations and is implemented as a balanced binary search tree.
set
are unique and sortedBy leveraging std::set
, C++ developers can efficiently manage collections of unique elements that need to be kept in a sorted order, making it valuable for tasks such as maintaining a sorted list of unique identifiers or implementing algorithms that require quick lookups in a sorted collection.
[1] https://www.geeksforgeeks.org/set-in-cpp-stl/ [2] https://www.tutorialspoint.com/cpp_standard_library/set.htm [3] https://stackoverflow.com/questions/63050845/using-set-in-c-standard-template-library-stl [4] https://en.wikipedia.org/wiki/C%2B%2B_standard_library [5] https://cplusplus.com/reference/set/set/ [6] https://learn.microsoft.com/en-us/cpp/standard-library/basic-ofstream-class?view=msvc-170 [7] https://www.machinet.net/tutorial-eng/common-pitfalls-with-cpp-fstream-and-how-to-avoid-them [8] https://stackoverflow.com/questions/72999240/initializing-stdofstream-object-in-header-file-v-s-source-file
Previous Page | Course Schedule | Course Content