Span View in C++
Level 5440 keystrokes
span<const int> is a non-owning view of contiguous ints: one function accepts a vector, an array and a plain C array without copying them. sum() adds the elements with accumulate.
C++ code
// span is just a pointer plus a size, so passing it by value is cheap1void printSpan(span<const int> data) {2 cout << "["; // Indexes the viewed elements3 for (size_t i = 0; i < data.size(); i++) { // Puts ", " between elements, not before the first4 if (i > 0) cout << ", ";5 cout << data[i];6 }7 cout << "]" << endl;8}9 // Sums the elements of any contiguous int sequence10int sum(span<const int> data) {11 return accumulate(data.begin(), data.end(), 0);12}13 // Three different containers with contiguous storage14vector<int> vec = {1, 2, 3, 4, 5};15array<int, 4> arr = {10, 20, 30, 40};16int raw[] = {100, 200, 300};17 // Each converts implicitly to span: prints [1, 2, 3, 4, 5]18printSpan(vec);// Prints [10, 20, 30, 40]19printSpan(arr);// The C array's size is known too: prints [100, 200, 300]20printSpan(raw);// 1 + 2 + 3 + 4 + 5: prints "Sum of vec: 15"21cout << "Sum of vec: " << sum(vec) << endl;Output
[1, 2, 3, 4, 5] [10, 20, 30, 40] [100, 200, 300] Sum of vec: 15
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this C++ code and how often they appear.
<× 21;× 14,× 13(× 12)× 12"× 8{× 6}× 6>× 5=× 4