将一个向量从一个类转换为另一个类向量
Casting vector from one class to other class vector
我试图使用动态转换将1类向量的值推到其他类向量。但是我得到一个分割错误。
当我使用gdb调试程序时,我发现dynamic_cast
没有发生,所以没有值可以推入向量。
这里我试图将元素从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);
}
这里我试图将元素从std::vector *points复制到std::vector *lpoints。你能帮我一下吗?
BPatch_point和Point是完全不相关的类。
这可以翻译成:
我有一个有大象的动物园。你能帮我如何把这些大象变成橙子,并把它们放在一个橙色的集装箱里吗?
当类不相关时,它们唯一的共同点是void *
——"指向某物的指针"。另一种选择是为任何值使用占位符-例如boost::any
。
编辑:(回复评论)
你能建议如何使用boost::any方法或void *方法吗
将std::vector<ldframework::Point *>
替换为std::vector<boost::any>
(如果您可以在项目中使用boost库)或std::vector<void *>
。然后你就可以把任何东西放在那里了。
虽然我仍然很确信,你做错了什么。如果你真的知道你在做什么,你可以随意使用所描述的解决方案。
相关文章:
- 函数向量_指针有不同的原型,我可以构建一个吗
- C++从另一个类访问公共静态向量的正确方法是什么
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- 给定一个向量,如何找到该向量的所有子集和的原始索引
- 获取向量C++中第一个值和最后一个值的和
- 从多个源构造一个对象,包括一个对象向量
- 为什么一个向量上的多线程操作很慢
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 如何在 C++11 中查找和更新向量中的一个嵌套结构
- Lower_bound不适用于具有 3 个元素的向量的最后一个元素
- 将一个向量插入另一个向量的某个位置
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- 将指向给定子类的指针从一个向量复制到另一个向量
- 如何创建一个类,以便向量工作 std::vector<MyClass<int>> v{ 1,2,3 };
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- 如何在不复制的情况下将一个向量移动到另一个向量中
- 创建一个函数的 Python 绑定,返回指向带有 boost 的向量的指针
- 紧凑向量一个小的内存足迹向量