开发者

using pair and make_pair in standard C

Is there any way to use std::pair and std::make_pair in C? seems that they are applicable in C++.

As I used

#include "utility"

it says it can not find such file开发者_如何学C

thansk for any suggestion


It's C++-only. C has no templates, so you will have to roll your own with macros to emulate them to some extent, for example:

#define PAIR_TYPE(type1, type2)\
    typedef struct {\
        type1 first;\
        type2 second;\
    }
#define MAKE_PAIR(val1, val2) {val1, val2}

PAIR_TYPE(int, float) mypair;
mypair p = MAKE_PAIR(1, 12.0);

But it's really not worth the trouble, result code is more verbose and less obvious than just using plain structs.


No, you cannot use the STL in C (as the STL only works with C++ and Objective-C++). You can mimic std::pair with a struct and with pointers (as C doesn't support templates):

struct pair {
  void *first;
  void *second;
};

void FreePair(struct pair* pair) {
  free(pair->first);
  free(pair->second);
  free(pair);
}

struct pair* MakePair(void *f, void *s, size_t fsize, size_t ssize) {
  struct pair* p = malloc(sizeof(struct pair));
  if (p == NULL) return NULL;
  p->first = malloc(fsize);
  p->second = malloc(ssize);
  if (p->first == NULL || p->second == NULL) {
    FreePair(p);
    return NULL;
  }
  memcpy(p->first, f, fsize);
  memcpy(p->second, s, ssize);
  return p;
}

int main() {
  int a = 42;
  const char* str = "Hello";
  struct pair* p = MakePair(&a, &str, sizeof(a), sizeof(str));
  printf("%d, %s", *(int*)p->first, *(const char**)p->second); // output: "42, Hello"
  FreePair(p);                              //  ^^ yes, this pointer pointer is correct
  return 0;
}


Is there any way to use std::pair and std::make_pair in C? seems that they are applicable in C++.

No. std::pair is a template class in C++, and there are no classes in C.

There is nothing similar (ie. easily usable predefined data structure) to pairs in C either.


No, those are types from the C++ standard library. Which explains the std:: namespace syntax (C doesn't support namespaces either).


"utility" is not a standard C header.

And no, the standard C++ library depends entirely on templates which are not part of the C language.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜