Equivalent of std::pair in C

生来就可爱ヽ(ⅴ<●) 提交于 2021-01-04 02:39:08

问题


What is the C equivalent of std::pair from C++? I'm trying to find the equivalent on the web and can't find anything but explanations of what it does.


回答1:


There isn't one. std::pair is a template, and C doesn't have anything similar to templates.

For a given specialisation of the template, you can define a structure that's more or less equivalent; so that std::pair<int, double> is similar to

struct pair_int_double {
    int first;
    double second;
};

but you've chosen the wrong language if you want a generic template.




回答2:


While the other answers are correct in saying that C does not have templates, the assumption that you can not have a generic pair type is wrong. If you really need a generic type, that is, you don't want to manually define a struct for each pair of types you want to use a pair for, you are left with 3 options.

Firstly, you could use a struct containing two void* types, and use these pointers as generic storage pointers for you data. (This is needlessly complicated and I would not generally recommend it)

Secondly, if the amount of types for your pair structure is known beforehand, you could use a union in your struct, for example

struct pair 
{
  union
  {
    int first_int;
    float first_float;
  };
  union
  {
    int second_int;
    float second_float;
  }
}

Or thirdly, you could use parametric macros to generate struct definitions of types you need, without constantly repeating yourself.

Or, alternatively think of a way to write your code that does not rely on templated types.




回答3:


std::pair in C++:

templte <class t1, class t2>
struct pair {
  t1 first;
  t2 second;
}

std::pair takes advantage of templates, so each concrete instantiation defines a new class std::pair<myT1, myT2>.

There's no such thing in C, you may have to declare a different struct each time, or use void *...

struct pair {
  struct myT1 first;
  struct myT2 second;
}


来源:https://stackoverflow.com/questions/22060251/equivalent-of-stdpair-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!