I am working with gnuplot.
In the header file I have the following function:
void PlotPath(Gnuplot& gp, const char* title, bool first_plot = true, bool last_plot = true);
Then, in the cpp file:
template <typename T>
void Path<T>::PlotPath(Gnuplot& gp, const char* title, bool first_plot, bool last_plot)
{
std::vector<WaypointPath<T>> waypoints = GenerateWaypoints(5000);
std::vector<std::pair<T, T>> plot_points(5000);
for (size_t i = 0; i < waypoints.size(); ++i) {
plot_points[i] = std::make_pair(waypoints[i].position[0], waypoints[i].position[1]);
}
if (first_plot) {
gp << "plot" << gp.file1d(plot_points) << "with lines title '" << title << "',";
} else {
gp << gp.file1d(plot_points) << "with lines title '" << title << "',";
}
if (last_plot) {
gp << std::endl;
}
}
What I want to do is instead of using const char* title, I want to use std::string title. So what I did is as follows and it works but I was wondering whether there is a better way of achieving this task.
template <typename T>
void Path<T>::PlotPath(Gnuplot& gp, const char* title, bool first_plot, bool last_plot)
{
std::vector<WaypointPath<T>> waypoints = GenerateWaypoints(5000);
std::vector<std::pair<T, T>> plot_points(5000);
// Convert const char * to std::string
std::string string_title = title;
for (size_t i = 0; i < waypoints.size(); ++i) {
plot_points[i] = std::make_pair(waypoints[i].position[0], waypoints[i].position[1]);
}
if (first_plot) {
gp << "plot" << gp.file1d(plot_points) << "with lines title '" << string_title << "',";
} else {
gp << gp.file1d(plot_points) << "with lines title '" << string_title << "',";
}
if (last_plot) {
gp << std::endl;
}
}
Here, I am converting the const char* to std::string by creating another variable. But Is there a way of including the std::string title
in the function argument itself ?
What I have done here is working fine but I am just searching for a more elegant way of solving this.
Thanking You in anticipation.
Make your argument std::string
. std::string
has a constructor that takes a const char*
so it should not be a problem.