/*! * Copyright 2015 by Contributors * \file common.h * \brief Common utilities */ #ifndef XGBOOST_COMMON_COMMON_H_ #define XGBOOST_COMMON_COMMON_H_ #include #include #include #include namespace xgboost { namespace common { /*! * \brief Split a string by delimiter * \param s String to be splitted. * \param delim The delimiter. */ inline std::vector Split(const std::string& s, char delim) { std::string item; std::istringstream is(s); std::vector ret; while (std::getline(is, item, delim)) { ret.push_back(item); } return ret; } // simple routine to convert any data to string template inline std::string ToString(const T& data) { std::ostringstream os; os << data; return os.str(); } /* * Range iterator */ class Range { public: class Iterator { friend class Range; public: using DifferenceType = int64_t; XGBOOST_DEVICE int64_t operator*() const { return i_; } XGBOOST_DEVICE const Iterator &operator++() { i_ += step_; return *this; } XGBOOST_DEVICE Iterator operator++(int) { Iterator res {*this}; i_ += step_; return res; } XGBOOST_DEVICE bool operator==(const Iterator &other) const { return i_ >= other.i_; } XGBOOST_DEVICE bool operator!=(const Iterator &other) const { return i_ < other.i_; } XGBOOST_DEVICE void Step(DifferenceType s) { step_ = s; } protected: XGBOOST_DEVICE explicit Iterator(int64_t start) : i_(start) {} XGBOOST_DEVICE explicit Iterator(int64_t start, int step) : i_{start}, step_{step} {} public: int64_t i_; DifferenceType step_ = 1; }; XGBOOST_DEVICE Iterator begin() const { return begin_; } // NOLINT XGBOOST_DEVICE Iterator end() const { return end_; } // NOLINT XGBOOST_DEVICE Range(int64_t begin, int64_t end) : begin_(begin), end_(end) {} XGBOOST_DEVICE Range(int64_t begin, int64_t end, Iterator::DifferenceType step) : begin_(begin, step), end_(end) {} XGBOOST_DEVICE bool operator==(const Range& other) const { return *begin_ == *other.begin_ && *end_ == *other.end_; } XGBOOST_DEVICE bool operator!=(const Range& other) const { return !(*this == other); } XGBOOST_DEVICE void Step(Iterator::DifferenceType s) { begin_.Step(s); } XGBOOST_DEVICE Iterator::DifferenceType GetStep() const { return begin_.step_; } private: Iterator begin_; Iterator end_; }; } // namespace common } // namespace xgboost #endif // XGBOOST_COMMON_COMMON_H_