user1238193
user1238193

Reputation:

Equivalent of C++ set container in C

I am required to convert some C++ codes to C and I am having some problems regarding the STL container. In the original C++ code, set container is used as in set< pair<int, int>, sortMapped> mySet; where sortMapped is a custom comparator to "sort" the entry by mapped value instead of the key value. And of course basic insertion, removal and iterator are included in the original C++ code as well.

So my problem is, does anyone knows the C equivalent of such "always sorted" container where I can write my own comparator as well? Thank you.

Upvotes: 2

Views: 1768

Answers (3)

SKi
SKi

Reputation: 8466

does anyone knows the C equivalent of such "always sorted" container where I can write my own comparator as well?

The simplest, it is an array, that is sorted by using qsort() after every change. With qsort() you can write own comparators.

With bsearch(), you can add functionality of std::set to it.

It is really cheap operation to find items from the sorted array. But inserting is quite expensive operation. So, this is not solution for all time critical applications.

Upvotes: 0

Ed Heal
Ed Heal

Reputation: 60007

You have a couple of choices

  1. Write code for a binary tree.
  2. Write code for a B-Tree.
  3. Write code for a hash table.
  4. Think of another solution to the problem that might be simpler to write in C.

... And I probably missed off a few other data structures - but it rather depends on the nature and usage of the data in question.

EDIT

You can always Google the data structures that I have mentioned above to get examples of code to work from.

Upvotes: 2

mathematician1975
mathematician1975

Reputation: 21351

There is no such container within the C language. C does not have nice things like STL and so I think you will just have to write it yourself.

Upvotes: 6

Related Questions