简体   繁体   English

从具有特定字符串长度的向量中删除元素

[英]removing elements from vector with specific string length

I have a vector that has random strings as elements. 我有一个向量,其中有随机字符串作为元素。 I am trying to loop through to find strings that are not a length of 2. If they are not a length of 2 then it should be removed from the vector. 我试图遍历以查找长度不为2的字符串。如果长度不为2,则应将其从向量中删除。 For some reason, my code is not removing all of the strings that are not a length of 2. 由于某些原因,我的代码没有删除所有长度不为2的字符串。

I have tried individually removing the elements but when it is in a loop it doesn't seem to be working for elements. 我尝试过单独删除元素,但是当它处于循环中时,它似乎不适用于元素。

This is my output: ho ao lol cd ef wq yo 这是我的输出:ho ao lol cd ef wq yo

and expected output should not include the string "lol" 并且预期输出不应包含字符串“ lol”

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector <string> numbers = {"ho","ao", "tom", "lol", "cd", "ef", "wq", "hello","yo","sup","boi"};

// loop deletes string elements from vector that don't have length of 2
for(int i=0; i < numbers.size(); i++){
    if(numbers[i].length() != 2){
        numbers.erase(numbers.begin() + i); 
    }
}

// this makes sure the last element in vector gets deleted
if( numbers[numbers.size() - 1].length() != 2  )
    numbers.pop_back();


for(int i=0; i < numbers.size(); i++){
    cout << numbers[i] << endl; // prints out vector elements
}
}

When you erase for the first time (in you situation when you erase "tom") the id of the next elements are decreased, so in next iteration you don't check the length of "lol". 第一次擦除时(在您所处的情况下,当您擦除“ tom”时)下一个元素的ID会减少,因此在下一次迭代中,您无需检查“ lol”的长度。

It's not the best solution but you can decrement i in if and your code will work. 这不是最好的解决方案,但是您可以在i减1的情况下使用,并且您的代码将正常工作。

if(numbers[i].length() != 2){
    numbers.erase(numbers.begin() + i);
    i--;
}

It's because after you erased "tom" the index has changed. 这是因为删除“ tom”后索引已更改。


Before erased "tom" 之前抹掉“ tom”

  • [0] "ho" [0]“ ho”
  • [1] "ao" [1]“ ao”
  • [2] "tom" [2]“ tom”
  • [3] "lol" [3]“哈哈”
  • ... ...

After

  • [0] "ho" [0]“ ho”
  • [1] "ao" [1]“ ao”
  • [2] "lol" [2]“大声笑”
  • [3] "cd" [3]“ cd”
  • ... ...

    You can fix it by decreasing i; 您可以通过减小i来解决它;


if(numbers[i].length() != 2){
    numbers.erase(numbers.begin() + i);
    i--;
}

or you can do this 或者你可以这样做


for( auto i = numbers.begin(); i != numbers.end(); )
{
    if( i->length() != 2 ) i = numbers.erase(i); else ++i;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM