Skip to content

Commit 6255877

Browse files
committed
examples: use std::span (C++20) to plot 2D C-style arrays
1 parent 13ed23f commit 6255877

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

CMakeLists.txt

+5-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ include(GNUInstallDirs)
55
set(PACKAGE_NAME matplotlib_cpp)
66
set(INSTALL_CONFIGDIR ${CMAKE_INSTALL_LIBDIR}/${PACKAGE_NAME}/cmake)
77

8-
98
# Library target
109
add_library(matplotlib_cpp INTERFACE)
1110
target_include_directories(matplotlib_cpp
@@ -100,6 +99,11 @@ if(Python3_NumPy_FOUND)
10099
add_executable(spy examples/spy.cpp)
101100
target_link_libraries(spy PRIVATE matplotlib_cpp)
102101
set_target_properties(spy PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
102+
103+
add_executable(span examples/span.cpp)
104+
target_link_libraries(span PRIVATE matplotlib_cpp)
105+
target_compile_features(span PRIVATE cxx_std_20)
106+
set_target_properties(span PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
103107
endif()
104108

105109

examples/span.cpp

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
//
2+
// g++ -std=c++20 -g -Wall -o span $(python-config --includes) span.cpp $(python-config --ldflags --embed)
3+
//
4+
#include "../matplotlibcpp.h"
5+
6+
#include <span>
7+
8+
using namespace std;
9+
namespace plt = matplotlibcpp;
10+
11+
int main()
12+
{
13+
// C-style arrays with multiple rows
14+
time_t t[]={1, 2, 3, 4};
15+
int data[]={
16+
3, 1, 4, 5,
17+
5, 4, 1, 3,
18+
3, 3, 3, 3
19+
};
20+
21+
size_t n=sizeof(t)/sizeof(decltype(t[0]));
22+
size_t m=sizeof(data)/sizeof(decltype(data[0]));
23+
24+
// Use std::span to pass data chunk to plot(), without copying it.
25+
// Unfortunately, plt::plot() makes an internal copy of both x and y
26+
// before passing them to python.
27+
for (size_t offset=0; offset<m; offset+=n)
28+
plt::plot(t, std::span {data+offset, n}, "");
29+
plt::show();
30+
31+
plt::detail::_interpreter::kill();
32+
33+
return 0;
34+
}

0 commit comments

Comments
 (0)