2009-04-08 73 views
1

我有这个新的类Seq继承向量,并有一些额外的功能。我可以在Seq中使用所有的矢量方法。函数返回向量的迭代器

具有这种数据结构:

Seq< vector<int> > sweepEvents; 

我想有一个函数,它为它的元素向量边搜索中sweepEvents和迭代器返回到发现元件的位置在sweepEvents(当且仅如果找到edge)并且迭代器到该向量的最后元素(当且仅当没有找到edge时)。

然后我想用这个迭代器,因为我想比较迭代器的prev和下一个位置的元素。

我有创始并返回迭代器有以下功能:

Seq< vector<int> >::iterator QSweep::insertSweepEvents(edge_t edge,int currentDim){ 
    int changePosition; 
    int found=0; 

    for (int i=0;i<currentDim;i++){ 
     if (edge[0]==sweepEvents[i][1]){ 
      changePosition=i; 
      found=1; 
      return sweepEvents.begin()+changePosition; 
     } 
    } 
    if (found==1){ 
     sweepEvents.rep().insert(sweepEvents.begin()+changePosition,edge); 
     sweepEvents.rep().erase(sweepEvents.begin()+changePosition+1); 
    } 
    else{ 
     sweepEvents.rep().insert(sweepEvents.end(),edge); 
    } 

    return sweepEvents.end()-1; 
} 

我再调用这个迭代器的主要功能。其实,我试过,但它不编译,我不知道比这要使用什么语法其他:

int main(){ 
    Seq< vector<int> > sweepEvents; 
    vector<int> edge; 
    //.....initialize sweepEvents and edge 

    //declare iterator but not working 
    Seq< vector<int> >::iterator comparePosition; 

    //not working neither 
    comparePosition=insertSweepEvents(edge,sweepEvents.size()); 
} 

上我应该如何正确地调用迭代任何想法?我发现它不能用作数组中的整数索引?

+0

你意思是“不工作”?错误的结果,编译器错误,核心? – bayda 2009-04-08 08:06:02

+0

编译器错误,用于定义comparePosition并随后分配comparePosition。 – madalina 2009-04-08 08:11:46

+0

你的if(found == 1)块永远得不到执行,因为当你设置found = 1时你会返回...... 你在哪个编译器中得到哪些编译器错误? – mentat 2009-04-08 08:12:32

回答

0

代码中的某些东西不合逻辑。看我的意见:

int found = 0; 
for (int i=0;i<currentDim;i++){ 
    if (edge[0]==sweepEvents[i][1]){ 
       changePosition=i; 
       found=1; 
// This place is one, where we assign 1 to found, and we do return after that (maybe you want do break/?) 
       return sweepEvents.begin()+changePosition; 
     } 
} 
if (found==1){ // as you see we reach this place only when found == 0 
1

什么编译错误?如何定义Seq<X>::iterator

#include <vector> 

template<typename T> 
struct Seq 
    : public std::vector<T> 
{ }; 

typedef Seq< std::vector<int> > SeqI; 

SeqI::iterator insertSweepEvents(SeqI &s) 
{ 
    return s.begin(); 
} 

int main() 
{ 
    SeqI s; 
    SeqI::iterator e = insertSweepEvents(s); 
} 

这工作正常。

2

是Seq < vector < T>> ::在您的Seq类中定义的迭代器?

制作模板“载体”的参数,并不意味着所存在的类型SEQ <矢量< INT>>:迭代

0

小旁注:

一个vector之后被改变,尤其是当附加到或插入到迭代器中使其失效。这是因为vector试图为其内部数据分配一个最小尺寸的连续内存块,同时它会尽量减少分配新的更大块所需的次数。所以数据可能会通过内存,所以迭代器之前 a push不再有效之后它。

另一个小记:

您可以通过使用std::difference(it1, it2)找到两个迭代器之间的差异。您可以使用std::advance(it1, d)重新应用该差异。

第三小记:

你似乎有一个“return”语句内的for循环,但代码的其余部分使用返回时只设置变量...