Awesome features in C++ Standard : std::span and std::string_view
I was going through an interesting lecture by Andreas Fertig on YouTube based on C++ Templates. In one of the sections, he mentioned std::span and I was quite intrigued to understand/learn more about it.
cppreference describes span as “an object which can take it a contiguous memory sequence of objects with the first element of the sequence at 0”. In other words, a span is a non-owning view over a contiguous sequence of objects like C-style arrays, std::array, and also std::vector. This concept seemed to be very similar to that of std::string_view which gives a view over both std::string and const char* type of variables. It also improves the performance of the code.
std::span got me thinking about how can it be used in production code. Well for me I have used string_view when I needed compatibility between C-style Legacy code and Modern C++17 Standard code. I am including some examples below which will help you understand the concept written above better.
Example of std::span:
#include <iostream>
#include <array>
#include <vector>
#include <span>
using namespace std;
void printMe(std::span<int> container)
{
for(auto& e : container)
{
cout<< e <<" ";
}
cout << "\n\n";
}
int main()
{
int arr[]{1,2,3,4};
printMe(arr);
std::vector<int> vec{1,2,3,4,5,6};
printMe(vec);
std::array<int, 4> arr2{1,2,9,10};
printMe(arr2);
return 0;
}
The above code will only be compiled by a compiler that supports the C++20 standard. You can use compiler explorer to test this code. Please remember to use gcc version above 10 with compile options as -std=c++2a.
Output:
1 2 3 41 2 3 4 5 61 2 9 10
So, you can see how no matter the type of container, array, or vector, the span can be used to get a view over it.
Next is an example of std::string_view:
#include <iostream>
using namespace std;void printMe(std::string_view str)
{
cout << str << "\n";
}int main()
{
const char* s = "It is a great day!";
printMe(s);
std::string ss = "I wish you a beautiful day!";
printMe(ss); return 0;
}
Output:
It is a great day!
I wish you a beautiful day!
This will be compiled by GCC version > 7.3 with -std=c++17 flag. In case you wish to read more on std::string_view, please go through this page.
I hope such good concepts are introduced more into our language standard which will make it robust, will improve the performance, and make code written simpler.
HAPPY C++ CODING!!! Please follow, like, comment, share if you like this.