【问题标题】:Returning two strings in C++在 C++ 中返回两个字符串
【发布时间】:2017-05-30 12:57:44
【问题描述】:

我正在为即将参加的 C++ 考试解答练习题。考虑以下练习:

一家旅行社使用列表来管理其行程。对于每次旅行,该机构都会记录其出发点、到达点、距离和时间/持续时间

1) 定义表示行程列表的必要结构

2) 编写一个函数,给定整数 i,返回位置 i 的行程的出发点和到达点

定义结构很简单:

struct list{
    char departure[100];
    char arrival[100];
    double distance;
    double time;
    list* next = NULL;
};

我的问题是功能。实际工作中,找第i趟很容易。但是我怎样才能返回两个字符数组/字符串离开和到达?如果这是我考试中的一个问题,我会这样解决:

typedef list* list_ptr;

list_ptr get_trip(list_ptr head, const int i){
    if(i<0 || head==NULL){
        return NULL;
    }

    for(int k = 0; k<i;k++){
        head = head->next;
        if(head==NULL){
            return NULL;
        }
    }

    return head;
}

我正在返回一个指向列表元素的指针。然后必须打印出发和到达。通过使用返回类型为 char* 的函数,我可以轻松地返回出发或到达。如何正确返回 2 个字符串? 我知道使用 std::tuple 可以做到这一点,但我不能使用它,因为我们在讲座中没有使用它(我们只有非常基本的东西,直到上课)。

如果不使用其他库就无法返回两个字符串,我说得对吗?

干杯

【问题讨论】:

标签: c++ list return return-type


【解决方案1】:

好的,首先,您的list 类型有一些问题。不要在 C++ 中使用char[],除非你真的必须这样做(注意:如果你认为你必须这样做,那你可能错了)。 C++ 提供了一个标准库,它的应用程序非常棒(嗯,与 C 相比),你应该使用它。特别是,我说的是std::string。使用double 表示距离和持续时间可能没问题,尽管缺少单位意味着您将度过一段糟糕的时光。

让我们试试这个:

struct Trip {
    std::string departure;
    std::string arrival;
    double distance_km;
    double duration_hours;
};

现在您可以使用std::vectorstd::liststd::slist,也可以创建自己的列表。让我们假设最后一个。

class TripList {
  public:
      TripList() = default;

      // Linear in i.
      Trip& operator[](std::size_t i);
      const Trip& operator[](std::size_t i) const;

      void append_trip(Trip trip);
      void remove_trip(std::size_t i);

  private:
      struct Node {
          Trip t;
          std::unique_ptr<Node> next;
      };
      std::unique_ptr<Node> head;
      Node* tail = nullptr;  // for efficient appending
};

我将把它的实现留给你。请注意,列表和行程是不同的概念,因此我们编写了不同的类型来处理它们。

现在你可以写一个简单的函数了:

std::pair<string, string> GetDepartureAndArrival(const TripList& list, std::size_t index) {
    const auto& trip = list[index];
    return {trip.departure, trip.arrival};
}

【讨论】:

    猜你喜欢
    • 2012-10-15
    • 2014-06-27
    • 2013-05-06
    • 2014-12-15
    • 1970-01-01
    • 2021-10-12
    • 2019-08-18
    • 2018-05-09
    • 2014-12-18
    相关资源
    最近更新 更多