【问题标题】:Iterating Through a Single Vector and Deleting Elements that Are Subsets of Other Elements?遍历单个向量并删除作为其他元素子集的元素?
【发布时间】:2013-12-25 20:16:14
【问题描述】:

我正在尝试遍历单个向量(使用两个迭代器)以删除作为其他元素的子集或副本的元素(向量是 )。我在下面编译但程序执行提前停止(并非所有子集或副本都被删除)。我已从文件中读取字符串并将它们放在向量中: 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());

                                    }

                    }
          }
    }
 }       

【问题讨论】:

    标签: c++ string vector iterator


    【解决方案1】:

    当您从 vector 中擦除时,所有指向已删除项目或超出该项目的迭代器都将失效。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-13
      • 1970-01-01
      相关资源
      最近更新 更多