将一个向量从一个类转换为另一个类向量

Casting vector from one class to other class vector

本文关键字:向量 一个 另一个 转换      更新时间:2023-10-16

我试图使用动态转换将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 *>。然后你就可以把任何东西放在那里了。

虽然我仍然很确信,你做错了什么。如果你真的知道你在做什么,你可以随意使用所描述的解决方案。