Reputation: 3254
I created structure Route.h
#include "stdafx.h"
using namespace std;
struct Route {
string startPoint;
string endPoint;
int number;
};
and I need to pass this structure to function. I used reference:
void CreateRoute(Route &route)
{
int start = rand() % 10;
int end = rand() % 10;
if (start == end)
{
while(true)
{
end = rand()%10;
if(end != start) break;
}
}
route.startPoint = SetPoint(start);
route.endPoint = SetPoint(end);
route.number = SetNumber();
}
but it seems the using of pointers is the better way to do it, but I don't know how to use pointers for it?
Upvotes: 0
Views: 3126
Reputation: 2301
In this case, why aren't you simply returning a newly constructed object?
struct route
{
std::string start_point;
std::string end_point;
int number;
};
route make_random_route()
{
route r;
int start = std::rand() % 10;
int end = std::rand() % 10;
while ( start == end) {
end = std::rand() % 10;
}
r.start_point = make_point(start);
r.end_point = make_point(end);
r.number = make_number();
return r;
}
Its trivial, and with move there is no copy.
Upvotes: 3
Reputation: 97
I think you must improve your C++ basis. Below is my simple answer.
void CreateRoute(Route *route)
{
if (route == NULL)
return;
int start = rand()%10;
int end = rand()%10;
if (start == end)
{
while(true)
{
end = rand()%10;
if(end != start) break;
}
}
route->startPoint = SetPoint(start);
route->endPoint = SetPoint(end);
route->number = SetNumber();
}
Upvotes: 1
Reputation: 5612
but it seems the using of pointers is the better way to do it
One of the reasons C++ has references to begin with is to get around the hassle of dealing with pointers, arrows and lots of parentheses.
You could easily convert it to use a pointer type, but the ref type is just cleaner.
void CreateRoute(Route* route);
would be your declaration, and you would call it using
Route route;
CreateRoute(&route);
Upvotes: 2