[英]Converting void* to vector<int>
我有一個名為deserialize的函數,它將作為輸入:
int(*cmp)(void*,void*)
因此,該函數可以將該類型的任何函數用作參數。
例如,如果我具有這樣的Point結構:
typedef struct{
int x, y;
}Point;
現在,為此,我的cmp函數如下所示:
int point_cmp(void* _p1, void* _p2){
Point* p1=(Point*)_p1;
Point* p2=(Point*)_p2;
return (!((p1->x==p2->x) && (p1->y==p2->y)));
}
這可行。
但是我想這樣做是為了向量。
我想編寫一個vector_cmp函數,可以像point_cmp這樣傳遞以反序列化。 所以,我為此嘗試了一些類似的方法,但是它是錯誤的:
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;
}
正確的方法是什么?
我想您正在這樣做是為了遇到某種外部接口(它將回調到您的函數中); 在純C ++中,永遠都不需要這樣做。 無論如何:
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;
}
應該是所有必要的。
直接的問題是您將其投放錯誤。 如果采用C樣式,則強制類型轉換應類似於:
vector<int> *v1 = (vector<int> *) (_v1);
vector<int> *v2 = (vector<int> *) (_v2);
然后,該程序將編譯並運行(一旦您還在循環v2_int
v2_it
更改為v2_it
,這就是一個錯字)。
更大的問題是,您不應在C ++中執行類似的操作。 void *
魔術通常適用於C,而不適用於C ++。 在C ++中,可以使用諸如模板之類的工具來編寫通用代碼,並且在可能的情況下,應依賴標准實現來進行比較操作。 毫不奇怪, std::vector
有它們-盡管當然自己做是一個很好的練習。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.