分享C++11代码片段-tuple和chrono

元组,我也不清楚,c++是不是借鉴了python从而引入了元组。

tuple元组定义了一个有固定数目元素的容器,其中的每个元素类型都可以不相同,这与其他容器有着本质的区别.是对pair的泛化。

首先来介绍元组的创建和元组元素的访问。通过make_tuple()创建元组,通过get<>()来访问元组的元素。

tuple

#include <iostream>
#include <tuple>

using namespace std;

int main() {
  tuple<int, string, double> firstRecord(42, "myFirstName", 1.303);
  tuple<int, string, double> secondRecord(21, "mySecondName", 2.638);

  auto concat = tuple_cat(firstRecord, secondRecord);

  /* for printing a tuple of any size you have to recursively use templates */
  cout << get<1>(concat) << " " << get<4>(concat) << endl;


  const int a = 1;
  const int b = 2;
  const double x = 2.34;
  const double y = 4.27;

  /* tie creates a tuple from lvalue references */
  if(tie(a, x) < tie(b, y))
    cout << "second arguments are larger" << endl;

  /* * use this to easily implement e.g. * bool operator<(const A& rhs) const { return tie(n, s, d) < tie(rhs.n, rhs.s, rhs.d); } */


  int f = 1;
  int g = 2;
  int h = 3;

  /* unpack variables */
  tie(f, g, h) = tie(g, f, h);

  cout << "f " << f << ", g " << g << ", h " << h << endl;
  /* * f=2, g=2, h=3, because it is evaluated as follows: * f = g; -> f=2 * g = f; -> g=2 * h = h; -> h=3 */
}

chrono
chrono是一个time library, 源于boost,现在已经是C++标准。

要使用chrono库,需要#include,其所有实现均在std::chrono namespace下。注意标准库里面的每个命名空间代表了一个独立的概念。所以下文中的概念均以命名空间的名字表示! chrono是一个模版库,使用简单,功能强大,只需要理解三个概念:duration、time_point、clock

#include <iostream>
#include <chrono>
#include <thread>

using namespace std;

int main() {
  /* * nanoseconds * microseconds * milliseconds * seconds * minutes * hours */

  const chrono::seconds sec(chrono::hours(1) + chrono::minutes(9) + chrono::seconds(8));
  cout << "1h 9m 8s = " << sec.count() << "s" << endl;

  /* get the duration of a section */
  const auto start(chrono::steady_clock::now());
  this_thread::sleep_for(chrono::seconds(3));
  const auto end(chrono::steady_clock::now());

  chrono::nanoseconds duration(end - start);

  cout << "duration of section: " << duration.count() << "ns"<< endl;
  cout << "duration of section: " << chrono::duration_cast<chrono::microseconds>(duration).count() << "ms"<< endl;
}

你可能感兴趣的:(Tuple,C++11,chrono)