Rishi
Rishi

Reputation: 2017

Converting void* to vector<int>

I have a function named deserialize which takes as an input:

int(*cmp)(void*,void*)

So, any function of that type can be taken as a parameter by the function.

For example, if I have a Point structure like this:

typedef struct{
    int x, y;
}Point;

Now, for this my cmp function is like this:

int point_cmp(void* _p1, void* _p2){
    Point* p1=(Point*)_p1;
    Point* p2=(Point*)_p2;
    return (!((p1->x==p2->x) && (p1->y==p2->y)));
}

This works.

But I want to do this for a vector.

I want to write a vector_cmp function which can be passed like point_cmp to deserialize. So, I have tried some thing like this for it, but its wrong:

int vector_int_cmp(void* _v1, void* _v2){
    vector<int> *v1 = vector<int> *_v1;
    vector<int> *v2 = vector<int> *_v2;
    auto diff = 0;
    auto v1_it = v1->begin();
    auto v2_it = v2->begin();
    while(v1_it != v1->end() && v2_int != v2->end()){
        if(*v1_it != *v2_it) diff++;
        v1_it++;
        v2_it++;
   } 
   if(0 == diff && (v1_it != v1->end() || v2_it != v2->end())) diff = 1;
   return diff;
}

What is the correct way to do this?

Upvotes: 1

Views: 5672

Answers (2)

James Kanze
James Kanze

Reputation: 153899

I suppose that you're doing this to meet some sort of external interface (which will call back into your function); in pure C++, there should never be a need for this. Anyhow:

int
vector_compare( void const* p1, void const* p2 )
{
    std::vector<int> const* v1 = static_cast<std::vector<int> const*>( p1 );
    std::vector<int> const* v2 = static_cast<std::vector<int> const*>( p2 );
    return *v1 < *v2
        ? -1
        : *v2 < *v1
        ? 1
        : 0;
}

should be all that's necessary.

Upvotes: 4

DUman
DUman

Reputation: 2590

The immediate problem is that you are casting it wrong. The casts, if C-style, should be like:

vector<int> *v1 = (vector<int> *) (_v1);
vector<int> *v2 = (vector<int> *) (_v2);

Then the program compiles and works (once you also change v2_int to v2_it in the loop, that's a typo).

The larger problem is that you should not do things like that in C++. void * magic is generally for C, not C++. In C++, you can use tools like templates for writing generic code, and you should rely on standard implementations for comparison operations where possible. Unsurprisingly, std::vector has them - although of course doing your own is a good exercise.

Upvotes: 3

Related Questions