c++ - 将 vector 从一类转换为另一类 vector

标签 c++ c++11

我正在尝试使用动态转换将 1 个类 vector 的值推送到其他类 vector 。但是我遇到了段错误。

当我使用 gdb 调试程序时,我发现 dynamic_cast没有发生,因此没有值(value)可以推送到 vector 。

这里我试图从 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);
}

关于c++ - 将 vector 从一类转换为另一类 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23949268/

相关文章:

c++ - C++ 中是否有 'override' 说明符的反转?

c++ - 整数模板参数的类型推断

c++ - 我应该使用什么 IDE 来试验 Chromium 源代码

c++ - 公开模板类型的模板参数

c++ - XCode 如何使用 LLDB?

c++ - 为什么 stoi 比没有 -O3 的 stringstream 慢得多?

c++ - 在 Xcode 5 中找不到 glm/glm.hpp 文件

c++ - 对 C++ 字符串的二进制搜索不起作用

Android Application.mk 设置能够使用 c++11 <random> 和 dynamic_cast

c++ - 将 union 转换为其成员类型之一