通过单个向量迭代并删除属于其他元素子集的元素?

时间:2013-12-08 20:12:25

标签: c++ string vector iterator

我试图迭代单个向量(使用两个迭代器)来删除作为子集的元素或其他元素的副本(向量是)。我在下面编译但编程执行提前停止(并非所有子集或副本都被删除)。我从文件中读取了字符串,并将它们放在向量中:sequence_1和sequence_2。任何帮助将非常感谢。

int c,j; string first_sequence, second_sequence;
vector<string>::iterator ivector1; vector<string>::iterator ivector2;
vector<string>::iterator ishort;

 // all relevant headers to the material are included in original code
//comparison of vector elements

size_t location,x,y,k,s;

k = sequence_1.size();
s = sequence_2.size();

for(ivector1 = sequence_1.begin(); ivector1< sequence_1.end(); ++ivector1){

    for(ivector2= sequence_1.begin()+1;ivector2<sequence_1.end(); ++ivector2){
        first_sequence = *ivector1; second_sequence = *ivector2;

        if(*ivector1 == *ivector2){
           cout << "Deleting the sequence with id: <" << endl << *ivector2 << endl;                                                         
        sequence_1.erase(remove(ivector2,sequence_1.end(),*ivector2),sequence_1.end());

        } else if(*ivector1 != *ivector2){
                    x = first_sequence.size();
                    y = second_sequence.size();

                    if(x > y){
                        location = first_sequence.find(second_sequence);
                        if (location != -1){
                             cout << "Deleting the sequence with id: <"<< endl << *ivector2 << endl;
                                                sequence_1.erase(remove(ivector2,sequence_1.end(),*ivector2),sequence_1.end()); 
                    }

                    } else if (y > x) {
                            location = second_sequence.find(first_sequence);
                                    if (location != -1){
                                            cout << "Deleting the sequence with id: <"<< *ivector1 << endl;
                                            sequence_1.erase(remove(sequence_1.begin(),ivector1+1,*ivector1),sequence_1.end());

                                    }

                    }
          }
    }
 }       

1 个答案:

答案 0 :(得分:1)

当您从vector擦除指向已删除项目或其后的所有迭代器时,它将失效。

您的第一个erase调用看起来会使ivector2无效,这意味着该循环的其余部分将不可靠,并且您的第二个erase调用看起来可能会使您的迭代器无效