Do you know how to insert structure into std set tree?
- User
Do you know how to insert structure into std set tree?
- Assistant
- User
Do I need to insert the id in my structure if I need to add it to std set? Answer shortly.
- Assistant
No, you do not need to use the
idspecifically, but you do need some form of unique, comparable criteria to determine the order of elements in thestd::set. This could be based on any member(s) of your structure as long as you provide a way to compare the elements either through overloading the<operator or using a custom comparator. - User
I need to compate my structure by raw data that is natively in it.
- Assistant
If you need to compare your structure by raw data that is natively within it, you can achieve this by overloading the
<operator for your structure based on the raw data, or by using a custom comparator that directly accesses the raw data. Here’s a brief example:Example with
<OperatorLet's say your structure has an array or some raw data:
#include <iostream> #include <set> #include <array> struct MyStruct { std::array<int, 4> data; bool operator<(const MyStruct& other) const { return data < other.data; // Leverage the std::array's < operator for lexicographical comparison } }; int main() { std::set<MyStruct> mySet; // Insertion mySet.insert({{1, 2, 3, 4}}); mySet.insert({{4, 3, 2, 1}}); mySet.insert({{2, 3, 1, 4}}); // Accessing elements for (const auto& elem : mySet) { for (int x : elem.data) { std::cout << x << ' '; } std::cout << '\n'; } return 0; } - User
Is it faster to use std map instead to add my structure as value? Answer shortly.
- Assistant
The choice between
std::setandstd::mapprimarily depends on your specific use case:-
std::set: Stores elements directly, ensuring they are unique and sorted based on the comparison criteria. Use this if you just need a collection of unique elements. -
std::map: Stores key-value pairs, ensuring keys are unique and sorted based on the comparison criteria. Use this if you need to associate values with keys.
In terms of performance, both are typically implemented as Red-Black Trees and therefore have similar insertion, deletion, and search complexity—
O(log n). Usingstd::mapto add a structure as a value won't be inherently faster or slower than usingstd::setfor storing the same structure directly. The performance difference would generally be negligible and should not be a deciding factor unless the use case explicitly requires key-value associations. -