-
Notifications
You must be signed in to change notification settings - Fork 1
/
span_demo.cpp
103 lines (78 loc) · 2.24 KB
/
span_demo.cpp
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
// Copyright (c) Microsoft Corporation.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
// Demos MSVC STL implementation for https://wg21.link/P0122R7 (plus various patches)
#include <iostream>
#include <algorithm>
#include <array>
#include <span>
#include <string>
#include <vector>
template<typename T>
void print_span(std::span<T> span)
{
std::cout << "[";
for (const auto& element : span)
{
std::cout << element << " ";
}
std::cout << "] (" << span.size() << " elements)\n";
}
void create_span()
{
std::cout << "\ncreate span demo:\n";
std::array int_array = std::to_array({ 1, 2, 4 });
print_span<int>(int_array);
std::vector<int> int_vector = { 1, 2, 3, 5, 7, 10 };
print_span<int>(int_vector);
std::span<int> int_span(int_vector);
print_span<int>(int_span);
std::span<int> int_span_2(int_vector.begin(), int_vector.end());
print_span<int>(int_span_2);
// This won't work.
//std::span<int> another_int_span(std::to_array({3, 4, 5}));
std::span<const int> const_int_span(std::to_array({3, 4, 5}));
print_span<const int>(const_int_span);
std::span<const int> const_int_span_2({ 1, 2, 3 });
print_span<const int>(const_int_span_2);
}
void modify_span_elements()
{
std::cout << "\nmodify span demo:\n";
std::vector<std::string> vector_of_str = { "span", "view", "contigeous" };
std::span<std::string> span_of_str(vector_of_str);
print_span<std::string>(span_of_str);
// Modify individual elements
for (auto&& str : span_of_str) {
str[0] = (char)std::toupper(str[0]);
}
print_span<std::string>(span_of_str);
}
void iterate_span()
{
std::cout << "\niterate span demo:\n";
std::vector<std::string> vector_of_str = { "span", "view", "contiguous" };
std::span<std::string> span_of_str(vector_of_str);
for (auto&& str : span_of_str)
{
std::cout << "\"" << str << "\" ";
}
std::cout << std::endl;
// Using commonly used iterators
for (auto it = span_of_str.rbegin(); it < span_of_str.rend(); ++it)
{
std::cout << "\"" << *it << "\" ";
}
std::cout << std::endl;
// Or even good old fashioned for loops
for (size_t i = 0; i < span_of_str.size(); i++)
{
std::cout << "\"" << span_of_str[i] << "\" ";
}
std::cout << std::endl;
}
void span_demo()
{
create_span();
modify_span_elements();
iterate_span();
}