我正在尝试使用动态转换将 1 个类 vector 的值推送到其他类 vector 。但是我遇到了段错误。
当我使用 gdb 调试程序时,我发现 dynamic_cast
没有发生,因此没有值(value)可以推送到 vector 。
这里我试图从 std::vector<BPatch_point *> *points
中复制元素至 std::vector<ldframework::Point *> *lpoints
.
BPatch_point
和 Point
是完全不相关的类。
你能帮我解决这个问题吗?
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/