Repository navigation
Expand file tree
/
Copy pathtest_cpp_stl_usage.py
More file actions
1209 lines (971 loc) · 38.5 KB
/
Copy pathtest_cpp_stl_usage.py
File metadata and controls
1209 lines (971 loc) · 38.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from pathlib import Path
from unittest.mock import MagicMock
import pytest
from codebase_rag.tests.conftest import get_node_names, get_relationships, run_updater
@pytest.fixture
def cpp_stl_project(temp_repo: Path) -> Path:
"""Create a comprehensive C++ project with STL usage."""
project_path = temp_repo / "cpp_stl_test"
project_path.mkdir()
(project_path / "src").mkdir()
(project_path / "include").mkdir()
return project_path
def test_stl_containers(
cpp_stl_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test STL containers including vector, map, set, deque, list."""
test_file = cpp_stl_project / "stl_containers.cpp"
test_file.write_text(
encoding="utf-8",
data="""
#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <deque>
#include <list>
#include <forward_list>
#include <stack>
#include <queue>
#include <priority_queue>
#include <array>
#include <string>
#include <algorithm>
// STL Container demonstration class
class STLContainerDemo {
private:
std::vector<int> numbers_;
std::map<std::string, int> scores_;
std::set<std::string> unique_names_;
public:
STLContainerDemo() {
// Initialize containers
numbers_ = {1, 2, 3, 4, 5};
scores_["Alice"] = 95;
scores_["Bob"] = 87;
scores_["Charlie"] = 92;
unique_names_.insert("Alice");
unique_names_.insert("Bob");
unique_names_.insert("Charlie");
}
void demonstrateSequenceContainers() {
std::cout << "=== Sequence Containers ===" << std::endl;
// Vector operations
std::vector<int> vec = {10, 20, 30, 40, 50};
vec.push_back(60);
vec.insert(vec.begin() + 2, 25);
std::cout << "Vector contents: ";
for (const auto& val : vec) {
std::cout << val << " ";
}
std::cout << std::endl;
// Deque operations
std::deque<std::string> deq = {"first", "second", "third"};
deq.push_front("zero");
deq.push_back("fourth");
std::cout << "Deque contents: ";
for (const auto& str : deq) {
std::cout << str << " ";
}
std::cout << std::endl;
// List operations
std::list<double> lst = {1.1, 2.2, 3.3};
lst.push_front(0.0);
lst.push_back(4.4);
lst.sort(); // List has its own sort method
std::cout << "List contents: ";
for (const auto& val : lst) {
std::cout << val << " ";
}
std::cout << std::endl;
// Array operations (C++11)
std::array<int, 5> arr = {100, 200, 300, 400, 500};
std::sort(arr.begin(), arr.end(), std::greater<int>());
std::cout << "Array contents (sorted desc): ";
for (const auto& val : arr) {
std::cout << val << " ";
}
std::cout << std::endl;
}
void demonstrateAssociativeContainers() {
std::cout << "=== Associative Containers ===" << std::endl;
// Map operations
std::map<std::string, int> grades;
grades["Mathematics"] = 95;
grades["Physics"] = 88;
grades["Chemistry"] = 92;
grades["Biology"] = 90;
std::cout << "Subject grades:" << std::endl;
for (const auto& [subject, grade] : grades) {
std::cout << " " << subject << ": " << grade << std::endl;
}
// Multimap for duplicate keys
std::multimap<int, std::string> score_to_student;
score_to_student.insert({95, "Alice"});
score_to_student.insert({87, "Bob"});
score_to_student.insert({95, "Diana"}); // Duplicate score
score_to_student.insert({92, "Charlie"});
std::cout << "Students by score:" << std::endl;
for (const auto& [score, student] : score_to_student) {
std::cout << " " << student << ": " << score << std::endl;
}
// Set operations
std::set<int> unique_scores = {95, 87, 92, 95, 88, 90}; // Duplicates ignored
std::cout << "Unique scores: ";
for (const auto& score : unique_scores) {
std::cout << score << " ";
}
std::cout << std::endl;
// Set operations: union, intersection
std::set<int> set1 = {1, 2, 3, 4, 5};
std::set<int> set2 = {4, 5, 6, 7, 8};
std::set<int> result;
std::set_union(set1.begin(), set1.end(),
set2.begin(), set2.end(),
std::inserter(result, result.begin()));
std::cout << "Union of sets: ";
for (const auto& val : result) {
std::cout << val << " ";
}
std::cout << std::endl;
}
void demonstrateUnorderedContainers() {
std::cout << "=== Unordered Containers ===" << std::endl;
// Unordered map (hash table)
std::unordered_map<std::string, int> word_count;
std::vector<std::string> words = {"apple", "banana", "apple", "cherry", "banana", "apple"};
for (const auto& word : words) {
word_count[word]++;
}
std::cout << "Word frequencies:" << std::endl;
for (const auto& [word, count] : word_count) {
std::cout << " " << word << ": " << count << std::endl;
}
// Unordered set
std::unordered_set<std::string> unique_words(words.begin(), words.end());
std::cout << "Unique words: ";
for (const auto& word : unique_words) {
std::cout << word << " ";
}
std::cout << std::endl;
// Performance comparison hint
std::cout << "Hash table bucket count: " << word_count.bucket_count() << std::endl;
std::cout << "Load factor: " << word_count.load_factor() << std::endl;
}
void demonstrateContainerAdaptors() {
std::cout << "=== Container Adaptors ===" << std::endl;
// Stack (LIFO)
std::stack<int> stk;
for (int i = 1; i <= 5; ++i) {
stk.push(i);
}
std::cout << "Stack contents (popped): ";
while (!stk.empty()) {
std::cout << stk.top() << " ";
stk.pop();
}
std::cout << std::endl;
// Queue (FIFO)
std::queue<std::string> que;
que.push("first");
que.push("second");
que.push("third");
std::cout << "Queue contents (dequeued): ";
while (!que.empty()) {
std::cout << que.front() << " ";
que.pop();
}
std::cout << std::endl;
// Priority queue (max heap by default)
std::priority_queue<int> pq;
std::vector<int> values = {30, 10, 50, 20, 40};
for (int val : values) {
pq.push(val);
}
std::cout << "Priority queue (max heap): ";
while (!pq.empty()) {
std::cout << pq.top() << " ";
pq.pop();
}
std::cout << std::endl;
// Priority queue with custom comparator (min heap)
std::priority_queue<int, std::vector<int>, std::greater<int>> min_pq;
for (int val : values) {
min_pq.push(val);
}
std::cout << "Priority queue (min heap): ";
while (!min_pq.empty()) {
std::cout << min_pq.top() << " ";
min_pq.pop();
}
std::cout << std::endl;
}
void demonstrateAdvancedOperations() {
std::cout << "=== Advanced Container Operations ===" << std::endl;
// Container capacity and memory management
std::vector<int> vec;
std::cout << "Vector capacity progression:" << std::endl;
for (int i = 0; i < 10; ++i) {
vec.push_back(i);
std::cout << " Size: " << vec.size() << ", Capacity: " << vec.capacity() << std::endl;
}
// Reserve memory to avoid reallocations
std::vector<int> reserved_vec;
reserved_vec.reserve(100);
std::cout << "Reserved vector capacity: " << reserved_vec.capacity() << std::endl;
// Container swapping
std::vector<int> vec1 = {1, 2, 3};
std::vector<int> vec2 = {4, 5, 6, 7, 8};
std::cout << "Before swap - vec1 size: " << vec1.size() << ", vec2 size: " << vec2.size() << std::endl;
vec1.swap(vec2);
std::cout << "After swap - vec1 size: " << vec1.size() << ", vec2 size: " << vec2.size() << std::endl;
// Container comparison
std::vector<int> v1 = {1, 2, 3};
std::vector<int> v2 = {1, 2, 3};
std::vector<int> v3 = {1, 2, 4};
std::cout << "v1 == v2: " << std::boolalpha << (v1 == v2) << std::endl;
std::cout << "v1 < v3: " << std::boolalpha << (v1 < v3) << std::endl;
}
};
void testSTLContainers() {
STLContainerDemo demo;
demo.demonstrateSequenceContainers();
demo.demonstrateAssociativeContainers();
demo.demonstrateUnorderedContainers();
demo.demonstrateContainerAdaptors();
demo.demonstrateAdvancedOperations();
}
// Graph-like structure using STL containers
class GraphStructure {
private:
std::unordered_map<int, std::vector<int>> adjacency_list_;
std::unordered_map<int, std::string> node_labels_;
public:
void addNode(int id, const std::string& label) {
node_labels_[id] = label;
if (adjacency_list_.find(id) == adjacency_list_.end()) {
adjacency_list_[id] = std::vector<int>();
}
}
void addEdge(int from, int to) {
adjacency_list_[from].push_back(to);
}
void printGraph() const {
std::cout << "Graph structure:" << std::endl;
for (const auto& [node, neighbors] : adjacency_list_) {
std::cout << "Node " << node << " (" << node_labels_.at(node) << "): ";
for (int neighbor : neighbors) {
std::cout << neighbor << " ";
}
std::cout << std::endl;
}
}
std::vector<int> getNeighbors(int node) const {
auto it = adjacency_list_.find(node);
return (it != adjacency_list_.end()) ? it->second : std::vector<int>();
}
size_t getNodeCount() const { return node_labels_.size(); }
size_t getEdgeCount() const {
size_t count = 0;
for (const auto& [node, neighbors] : adjacency_list_) {
count += neighbors.size();
}
return count;
}
};
void testGraphStructure() {
std::cout << "=== Graph Structure Demo ===" << std::endl;
GraphStructure graph;
// Add nodes
graph.addNode(1, "Function A");
graph.addNode(2, "Function B");
graph.addNode(3, "Function C");
graph.addNode(4, "Class X");
graph.addNode(5, "Class Y");
// Add edges (function calls, inheritance, etc.)
graph.addEdge(1, 2); // A calls B
graph.addEdge(1, 3); // A calls C
graph.addEdge(2, 4); // B uses X
graph.addEdge(3, 4); // C uses X
graph.addEdge(5, 4); // Y inherits from X
graph.printGraph();
std::cout << "Graph statistics:" << std::endl;
std::cout << " Nodes: " << graph.getNodeCount() << std::endl;
std::cout << " Edges: " << graph.getEdgeCount() << std::endl;
// Query neighbors
auto neighbors = graph.getNeighbors(1);
std::cout << "Node 1 neighbors: ";
for (int neighbor : neighbors) {
std::cout << neighbor << " ";
}
std::cout << std::endl;
}
void demonstrateSTLContainers() {
testSTLContainers();
testGraphStructure();
}
""",
)
run_updater(cpp_stl_project, mock_ingestor)
project_name = cpp_stl_project.name
expected_classes = [
f"{project_name}.stl_containers.STLContainerDemo",
f"{project_name}.stl_containers.GraphStructure",
]
expected_functions = [
f"{project_name}.stl_containers.testSTLContainers",
f"{project_name}.stl_containers.testGraphStructure",
f"{project_name}.stl_containers.demonstrateSTLContainers",
]
created_classes = get_node_names(mock_ingestor, "Class")
missing_classes = set(expected_classes) - created_classes
assert not missing_classes, (
f"Missing expected classes: {sorted(list(missing_classes))}"
)
created_functions = get_node_names(mock_ingestor, "Function")
missing_functions = set(expected_functions) - created_functions
assert not missing_functions, (
f"Missing expected functions: {sorted(list(missing_functions))}"
)
def test_stl_algorithms(
cpp_stl_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test STL algorithms including sorting, searching, and transforming."""
test_file = cpp_stl_project / "stl_algorithms.cpp"
test_file.write_text(
encoding="utf-8",
data="""
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <functional>
#include <iterator>
#include <string>
#include <random>
// STL Algorithms demonstration
class STLAlgorithmsDemo {
private:
std::vector<int> numbers_;
std::vector<std::string> words_;
public:
STLAlgorithmsDemo() {
numbers_ = {64, 34, 25, 12, 22, 11, 90, 5, 77, 30};
words_ = {"apple", "banana", "cherry", "date", "elderberry", "fig", "grape"};
}
void demonstrateSortingAlgorithms() {
std::cout << "=== Sorting Algorithms ===" << std::endl;
// Copy original data
auto nums = numbers_;
std::cout << "Original: ";
printContainer(nums);
// std::sort (default ascending)
std::sort(nums.begin(), nums.end());
std::cout << "std::sort (asc): ";
printContainer(nums);
// std::sort with comparator (descending)
std::sort(nums.begin(), nums.end(), std::greater<int>());
std::cout << "std::sort (desc): ";
printContainer(nums);
// std::partial_sort (sort first n elements)
nums = numbers_; // Reset
std::partial_sort(nums.begin(), nums.begin() + 5, nums.end());
std::cout << "partial_sort (first 5): ";
printContainer(nums);
// std::nth_element (find nth element in sorted order)
nums = numbers_; // Reset
std::nth_element(nums.begin(), nums.begin() + 4, nums.end());
std::cout << "nth_element (5th): " << nums[4] << " at position 4" << std::endl;
// std::stable_sort (maintains relative order of equal elements)
std::vector<std::pair<int, char>> pairs = {{3, 'a'}, {1, 'b'}, {3, 'c'}, {2, 'd'}};
std::stable_sort(pairs.begin(), pairs.end(),
[](const auto& a, const auto& b) { return a.first < b.first; });
std::cout << "stable_sort pairs: ";
for (const auto& [num, letter] : pairs) {
std::cout << "(" << num << "," << letter << ") ";
}
std::cout << std::endl;
}
void demonstrateSearchingAlgorithms() {
std::cout << "=== Searching Algorithms ===" << std::endl;
auto sorted_nums = numbers_;
std::sort(sorted_nums.begin(), sorted_nums.end());
std::cout << "Sorted array: ";
printContainer(sorted_nums);
// std::binary_search
int target = 25;
bool found = std::binary_search(sorted_nums.begin(), sorted_nums.end(), target);
std::cout << "binary_search for " << target << ": " << std::boolalpha << found << std::endl;
// std::lower_bound and std::upper_bound
auto lower = std::lower_bound(sorted_nums.begin(), sorted_nums.end(), target);
auto upper = std::upper_bound(sorted_nums.begin(), sorted_nums.end(), target);
if (lower != sorted_nums.end()) {
std::cout << "lower_bound for " << target << ": position "
<< std::distance(sorted_nums.begin(), lower) << std::endl;
}
// std::find and std::find_if
auto it = std::find(numbers_.begin(), numbers_.end(), 77);
if (it != numbers_.end()) {
std::cout << "find 77: found at position "
<< std::distance(numbers_.begin(), it) << std::endl;
}
auto even_it = std::find_if(numbers_.begin(), numbers_.end(),
[](int n) { return n % 2 == 0; });
if (even_it != numbers_.end()) {
std::cout << "find_if (first even): " << *even_it << std::endl;
}
// std::count and std::count_if
int count_above_30 = std::count_if(numbers_.begin(), numbers_.end(),
[](int n) { return n > 30; });
std::cout << "count_if (> 30): " << count_above_30 << std::endl;
}
void demonstrateTransformingAlgorithms() {
std::cout << "=== Transforming Algorithms ===" << std::endl;
// std::transform (unary operation)
std::vector<int> squares(numbers_.size());
std::transform(numbers_.begin(), numbers_.end(), squares.begin(),
[](int n) { return n * n; });
std::cout << "Original: ";
printContainer(numbers_);
std::cout << "Squares: ";
printContainer(squares);
// std::transform (binary operation)
std::vector<int> sums(numbers_.size());
std::transform(numbers_.begin(), numbers_.end(), squares.begin(), sums.begin(),
[](int a, int b) { return a + b; });
std::cout << "Sums (orig + square): ";
printContainer(sums);
// std::for_each
std::cout << "for_each (multiply by 2): ";
auto doubled = numbers_;
std::for_each(doubled.begin(), doubled.end(), [](int& n) { n *= 2; });
printContainer(doubled);
// std::generate
std::vector<int> random_nums(10);
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 100);
std::generate(random_nums.begin(), random_nums.end(),
[&]() { return dis(gen); });
std::cout << "Generated random: ";
printContainer(random_nums);
}
void demonstrateNumericAlgorithms() {
std::cout << "=== Numeric Algorithms ===" << std::endl;
// std::accumulate
int sum = std::accumulate(numbers_.begin(), numbers_.end(), 0);
std::cout << "Sum (accumulate): " << sum << std::endl;
// std::accumulate with custom operation
int product = std::accumulate(numbers_.begin(), numbers_.begin() + 5, 1,
[](int a, int b) { return a * b; });
std::cout << "Product of first 5: " << product << std::endl;
// std::inner_product
std::vector<int> weights = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int weighted_sum = std::inner_product(numbers_.begin(), numbers_.end(),
weights.begin(), 0);
std::cout << "Weighted sum: " << weighted_sum << std::endl;
// std::partial_sum
std::vector<int> cumulative_sums(numbers_.size());
std::partial_sum(numbers_.begin(), numbers_.end(), cumulative_sums.begin());
std::cout << "Original: ";
printContainer(numbers_);
std::cout << "Cumulative sums: ";
printContainer(cumulative_sums);
// std::adjacent_difference
std::vector<int> differences(numbers_.size());
std::adjacent_difference(numbers_.begin(), numbers_.end(), differences.begin());
std::cout << "Adjacent differences: ";
printContainer(differences);
// std::iota (fill with sequential values)
std::vector<int> sequence(10);
std::iota(sequence.begin(), sequence.end(), 1);
std::cout << "iota sequence: ";
printContainer(sequence);
}
void demonstrateSetOperations() {
std::cout << "=== Set Operations ===" << std::endl;
std::vector<int> set1 = {1, 2, 3, 4, 5, 6};
std::vector<int> set2 = {4, 5, 6, 7, 8, 9};
// Ensure sets are sorted
std::sort(set1.begin(), set1.end());
std::sort(set2.begin(), set2.end());
std::cout << "Set 1: ";
printContainer(set1);
std::cout << "Set 2: ";
printContainer(set2);
// std::set_union
std::vector<int> union_result;
std::set_union(set1.begin(), set1.end(),
set2.begin(), set2.end(),
std::back_inserter(union_result));
std::cout << "Union: ";
printContainer(union_result);
// std::set_intersection
std::vector<int> intersection_result;
std::set_intersection(set1.begin(), set1.end(),
set2.begin(), set2.end(),
std::back_inserter(intersection_result));
std::cout << "Intersection: ";
printContainer(intersection_result);
// std::set_difference
std::vector<int> difference_result;
std::set_difference(set1.begin(), set1.end(),
set2.begin(), set2.end(),
std::back_inserter(difference_result));
std::cout << "Difference (1-2): ";
printContainer(difference_result);
// std::set_symmetric_difference
std::vector<int> symmetric_diff;
std::set_symmetric_difference(set1.begin(), set1.end(),
set2.begin(), set2.end(),
std::back_inserter(symmetric_diff));
std::cout << "Symmetric difference: ";
printContainer(symmetric_diff);
}
void demonstratePermutationAlgorithms() {
std::cout << "=== Permutation Algorithms ===" << std::endl;
std::vector<int> small_set = {1, 2, 3, 4};
std::cout << "Original: ";
printContainer(small_set);
// std::next_permutation
std::cout << "All permutations:" << std::endl;
int count = 0;
do {
std::cout << " ";
printContainer(small_set);
++count;
} while (std::next_permutation(small_set.begin(), small_set.end()) && count < 10);
// std::prev_permutation
std::vector<int> reverse_set = {4, 3, 2, 1};
std::cout << "Reverse permutations (first 5):" << std::endl;
count = 0;
do {
std::cout << " ";
printContainer(reverse_set);
++count;
} while (std::prev_permutation(reverse_set.begin(), reverse_set.end()) && count < 5);
// std::random_shuffle (deprecated) / std::shuffle
auto shuffled = numbers_;
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(shuffled.begin(), shuffled.end(), g);
std::cout << "Original: ";
printContainer(numbers_);
std::cout << "Shuffled: ";
printContainer(shuffled);
}
private:
template<typename Container>
void printContainer(const Container& container) {
for (const auto& item : container) {
std::cout << item << " ";
}
std::cout << std::endl;
}
};
void testSTLAlgorithms() {
STLAlgorithmsDemo demo;
demo.demonstrateSortingAlgorithms();
demo.demonstrateSearchingAlgorithms();
demo.demonstrateTransformingAlgorithms();
demo.demonstrateNumericAlgorithms();
demo.demonstrateSetOperations();
demo.demonstratePermutationAlgorithms();
}
void demonstrateSTLAlgorithms() {
testSTLAlgorithms();
}
""",
)
run_updater(cpp_stl_project, mock_ingestor)
project_name = cpp_stl_project.name
expected_classes = [
f"{project_name}.stl_algorithms.STLAlgorithmsDemo",
]
created_classes = get_node_names(mock_ingestor, "Class")
found_classes = [cls for cls in expected_classes if cls in created_classes]
assert len(found_classes) >= 1, (
f"Expected at least 1 STL algorithms class, found {len(found_classes)}: {found_classes}"
)
def test_stl_iterators_functors(
cpp_stl_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test STL iterators and function objects."""
test_file = cpp_stl_project / "stl_iterators_functors.cpp"
test_file.write_text(
encoding="utf-8",
data="""
#include <iostream>
#include <vector>
#include <list>
#include <iterator>
#include <algorithm>
#include <functional>
#include <string>
// Custom iterator example
template<typename T>
class SimpleVector {
private:
T* data_;
size_t size_;
size_t capacity_;
public:
// Iterator class
class Iterator {
private:
T* ptr_;
public:
using iterator_category = std::random_access_iterator_tag;
using value_type = T;
using difference_type = std::ptrdiff_t;
using pointer = T*;
using reference = T&;
Iterator(T* ptr) : ptr_(ptr) {}
reference operator*() const { return *ptr_; }
pointer operator->() const { return ptr_; }
Iterator& operator++() { ++ptr_; return *this; }
Iterator operator++(int) { Iterator temp = *this; ++ptr_; return temp; }
Iterator& operator--() { --ptr_; return *this; }
Iterator operator--(int) { Iterator temp = *this; --ptr_; return temp; }
Iterator operator+(difference_type n) const { return Iterator(ptr_ + n); }
Iterator operator-(difference_type n) const { return Iterator(ptr_ - n); }
difference_type operator-(const Iterator& other) const { return ptr_ - other.ptr_; }
bool operator==(const Iterator& other) const { return ptr_ == other.ptr_; }
bool operator!=(const Iterator& other) const { return ptr_ != other.ptr_; }
bool operator<(const Iterator& other) const { return ptr_ < other.ptr_; }
};
SimpleVector() : data_(nullptr), size_(0), capacity_(0) {}
SimpleVector(size_t capacity) : size_(0), capacity_(capacity) {
data_ = new T[capacity_];
}
~SimpleVector() { delete[] data_; }
void push_back(const T& value) {
if (size_ < capacity_) {
data_[size_++] = value;
}
}
Iterator begin() { return Iterator(data_); }
Iterator end() { return Iterator(data_ + size_); }
size_t size() const { return size_; }
};
// Custom function objects
class Multiplier {
private:
int factor_;
public:
Multiplier(int factor) : factor_(factor) {}
int operator()(int value) const {
return value * factor_;
}
};
class StringLengthComparator {
public:
bool operator()(const std::string& a, const std::string& b) const {
return a.length() < b.length();
}
};
// Predicate functors
struct IsEven {
bool operator()(int n) const { return n % 2 == 0; }
};
struct IsPositive {
bool operator()(int n) const { return n > 0; }
};
class STLIteratorsFunctorsDemo {
private:
std::vector<int> numbers_;
std::vector<std::string> words_;
public:
STLIteratorsFunctorsDemo() {
numbers_ = {1, -2, 3, -4, 5, 6, -7, 8, 9, -10};
words_ = {"a", "hello", "world", "cpp", "programming", "iterators", "stl", "test"};
}
void demonstrateIteratorTypes() {
std::cout << "=== Iterator Types ===" << std::endl;
// Input iterator (read-only, forward)
std::vector<int> vec = {1, 2, 3, 4, 5};
std::cout << "Forward iteration: ";
for (auto it = vec.begin(); it != vec.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
// Bidirectional iterator
std::list<int> lst = {10, 20, 30, 40, 50};
std::cout << "Reverse iteration: ";
for (auto it = lst.rbegin(); it != lst.rend(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
// Random access iterator
std::cout << "Random access: ";
auto random_it = vec.begin();
std::cout << "vec[0] = " << *random_it << ", ";
std::cout << "vec[3] = " << *(random_it + 3) << ", ";
std::cout << "vec[4] = " << vec[4] << std::endl;
// Distance between iterators
auto distance = std::distance(vec.begin(), vec.end());
std::cout << "Distance from begin to end: " << distance << std::endl;
}
void demonstrateIteratorAdaptors() {
std::cout << "=== Iterator Adaptors ===" << std::endl;
// Back insert iterator
std::vector<int> target;
std::copy(numbers_.begin(), numbers_.begin() + 5, std::back_inserter(target));
std::cout << "Back inserter result: ";
for (int n : target) std::cout << n << " ";
std::cout << std::endl;
// Front insert iterator (with deque)
std::deque<int> deq;
std::copy(numbers_.begin(), numbers_.begin() + 5, std::front_inserter(deq));
std::cout << "Front inserter result: ";
for (int n : deq) std::cout << n << " ";
std::cout << std::endl;
// Insert iterator
std::vector<int> vec = {100, 200};
auto insert_pos = vec.begin() + 1;
std::copy(numbers_.begin(), numbers_.begin() + 3, std::inserter(vec, insert_pos));
std::cout << "Insert iterator result: ";
for (int n : vec) std::cout << n << " ";
std::cout << std::endl;
// Reverse iterator
std::cout << "Reverse iterator: ";
for (auto rit = numbers_.rbegin(); rit != numbers_.rbegin() + 5; ++rit) {
std::cout << *rit << " ";
}
std::cout << std::endl;
}
void demonstrateStreamIterators() {
std::cout << "=== Stream Iterators ===" << std::endl;
// Ostream iterator
std::cout << "Numbers with ostream_iterator: ";
std::copy(numbers_.begin(), numbers_.begin() + 5,
std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
// Using ostream iterator with transform
std::cout << "Squared numbers: ";
std::transform(numbers_.begin(), numbers_.begin() + 5,
std::ostream_iterator<int>(std::cout, " "),
[](int n) { return n * n; });
std::cout << std::endl;
}
void demonstrateCustomIterator() {
std::cout << "=== Custom Iterator ===" << std::endl;
SimpleVector<int> custom_vec(10);
for (int i = 1; i <= 5; ++i) {
custom_vec.push_back(i * 10);
}
std::cout << "Custom vector contents: ";
for (auto it = custom_vec.begin(); it != custom_vec.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
// Use STL algorithms with custom iterator
std::cout << "Custom vector sorted: ";
std::sort(custom_vec.begin(), custom_vec.end());
for (const auto& value : custom_vec) {
std::cout << value << " ";
}
std::cout << std::endl;
}
void demonstrateStandardFunctors() {
std::cout << "=== Standard Function Objects ===" << std::endl;
auto nums = numbers_;
// Arithmetic functors
std::transform(nums.begin(), nums.end(), nums.begin(),
std::bind(std::multiplies<int>(), std::placeholders::_1, 2));
std::cout << "Multiplied by 2: ";
for (int n : nums) std::cout << n << " ";
std::cout << std::endl;
// Comparison functors
nums = numbers_;
std::sort(nums.begin(), nums.end(), std::greater<int>());
std::cout << "Sorted descending: ";
for (int n : nums) std::cout << n << " ";
std::cout << std::endl;
// Logical functors
std::vector<bool> even_flags(numbers_.size());
std::transform(numbers_.begin(), numbers_.end(), even_flags.begin(),
[](int n) { return n % 2 == 0; });
std::cout << "Even flags: ";
for (bool flag : even_flags) std::cout << std::boolalpha << flag << " ";
std::cout << std::endl;
}
void demonstrateCustomFunctors() {
std::cout << "=== Custom Function Objects ===" << std::endl;
// Custom multiplier functor
Multiplier times3(3);
std::vector<int> multiplied(numbers_.size());
std::transform(numbers_.begin(), numbers_.end(), multiplied.begin(), times3);
std::cout << "Original: ";
for (int n : numbers_) std::cout << n << " ";
std::cout << std::endl;