0

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?

greatwolf
  • 20,287
  • 13
  • 71
  • 105
Heidel
  • 3,174
  • 16
  • 52
  • 84

3 Answers3

3

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.

Casper Beyer
  • 2,203
  • 2
  • 22
  • 35
  • Yes, by now I changed my all function and made `Route` the return type, `Route CreateRoute()`. – Heidel Oct 16 '13 at 10:20
2

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);
yamafontes
  • 5,552
  • 1
  • 18
  • 18
1

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();
}
Kevin
  • 97
  • 2