2016-11-26 58 views
1

我是C++的新手,我遇到了Java中的问题。我知道C++中的Vectors类似于Java中的ArrayList,但我有一些问题完全理解。在Vector中插入特定项目

假设我有vector<PetStore*> pets,并且每个PetStore对象都有一些getter和setter。我想在向量中的特定索引处设置/插入特定元素。我也想在插入的宠物上调用方法bool setAdopted(bool adopted)并将其设置为true

/* 
    Pseudo code 
    pets.insert(pets.begin()+i, setAdopted(true)); 
*/ 
+1

我不能理解你的例子,但这里是一个关于如何插入矢量的例子:http://stackoverflow.com/questions/6726805/insert-an-element-into-a-specific-position-of-a- vector – Yves

+1

试试这个:'pets [specific_index] .setadopted(true);' – ruhul

+0

@Thomas我之前看到过,但我正在使用OOP。 – jdog

回答

0

我想设置/在指定索引插入一个特定的元素

插入

PetStore *item; 
item = new PetStore(); 
vector<PetStore*> pets; 
vector<PetStore*>::iterator it; 
it = pets.begin(); 
it = pets.insert (it , item); 
// another way.. 
pets.insert (it,2,item); 

集:

pets.at(indx)->setadopted(true); 

链接:vector/insert

+0

假设'PetStore'被定义为一个指针类型,那么你的回答将是正确的 – smac89

+0

谢谢!它终于编译完成 – jdog