Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
ashawkey committed Jul 3, 2024
1 parent 13f8696 commit 0a27b7a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions docs/c/cpitfalls.md → docs/c/c_pitfalls.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,3 +180,29 @@
```


* Sorting vector of pointers should use actual object's comparator:

```cpp
struct Node {
int val;
Node(int val): val(val) {}
// define the comparator
bool operator<(const Node& other) const {
return val < other.val;
}
};


int main() {
vector<Node*> v;
v.push_back(new Node(3));
v.push_back(new Node(1));
v.push_back(new Node(2));

// direct sort will compare **pointer values**, which is totally wrong!
sort(v.begin(), v.end());

// use the actual object's comparator
sort(v.begin(), v.end(), [](Node* a, Node* b) { return *a < *b; });
}
```
File renamed without changes.

0 comments on commit 0a27b7a

Please sign in to comment.