簡體   English   中英

將向量從一類轉換為另一類向量

[英]Casting vector from one class to other class vector

我正在嘗試使用動態轉換將1類向量的值推到其他類向量。 但是我遇到了細分錯誤。

當我使用gdb調試程序時,我發現dynamic_cast沒有發生,因此沒有值可推到向量。

在這里,我嘗試將std::vector<BPatch_point *> *points的元素復制到std::vector<ldframework::Point *> *lpoints

BPatch_pointPoint是完全不相關的類。

您能幫我嗎?

int main(int argc , char *argv[])
{

        BPatch bpatch;
        int pid;
        if (argc != 3) {

                exit(1);
        }

        pid=atoi(argv[1]);

        char name[ 40 ];
        cout<<"The attached pid is "<<pid<<endl;


        BPatch_process *appProc = bpatch.processAttach("",pid);
        BPatch_image *img = appProc->getImage();

        std::vector<BPatch_function *> functions;
        std::vector<BPatch_point *> *points;


        img->findFunction(argv[2], functions);
        if(functions.size()==0) {
                cout<<"unable to find the function "<<argv[2]<<endl;
                return -1;
        }
        else {
              cout<<"The "<<argv[2]<<" function is found"<<endl;
        }
        points = functions[0]->findPoint(BPatch_entry);
        if ((*points).size() == 0) {
                cout<<"Not able to find the points"<<endl;
        }
        cout<<"The points is "<<(*points)[0];
        std::vector<ldframework::Point *> *lpoints=NULL;
        for(unsigned int i=0; i<(*points).size();i++)
    {
        lpoints->push_back(dynamic_cast<ldframework::Point *>((*points).at(i)));
    }
}

您需要做的是一個接一個地變換對象,而不是強制轉換它們。 幸運的是,標准庫使它非常容易。

#include <vector>
#include <algorithm>
#include <iterator>

ClassB * ConvertAtoB(ClassA * a)
{
    // create a new object of type ClassB here
}

int main()
{
    std::vector<ClassA*> a;

    // fill 'a' with data
    // ...

    // then transform it into 'b'
    std::vector<ClassB*> b;
    std::transform(a.begin(), a.end(), std::back_inserter(b), ConvertAtoB);
}

在這里,我試圖將元素從std :: vector * points復制到std :: vector * lpoints。 您能幫我嗎?

BPatch_point和Point是完全不相關的類。

可以將其翻譯為:

我有一個帶大象的動物園。 您能幫我把這些大象變成橙色,然后將它們放入橙色的容器盒中嗎?

當類不相關時,它們唯一的共同點是void * -“指向某物的指針”。 另一種選擇是將占位符用於任何值,例如boost::any

但是核心問題是: 為什么要將一種類型的類移動到另一種類型的容器中。 首先有99.8%的機會您在做錯事,而這正是您應該找到解決辦法的地方。


編輯:(回應評論)

您能建議使用boost :: any方法或void *方法如何完成嗎?

std::vector<ldframework::Point *>替換為std::vector<boost::any> (如果可以在項目中使用boost庫)或std::vector<void *> 然后,您將可以在此處放置任何內容。

盡管我仍然很確信,但您做錯了什么。 即使您確實知道自己在做什么,也可以自由使用所描述的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM