简体   繁体   English

矢量擦除功能无法正常工作

[英]Vector erase function not working properly

I am trying one of the practice problems on hackerrank.我正在尝试hackerrank上的练习题之一。
I'm aware there is a better way to do it, but I would like to know why this way didn't work to understand it better.我知道有更好的方法来做到这一点,但我想知道为什么这种方法不能更好地理解它。
The vector erase function seems to work as intended until the last couple of times and then erases at the wrong index, even though nothing changes.矢量擦除功能似乎按预期工作,直到最后几次,然后在错误的索引处擦除,即使没有任何变化。

debugger output:调试器输出:
1, 1, 3, 1, 2, 1, 3, 3, 3, 3, //what is currently in the vector 1, 1, 3, 1, 2, 1, 3, 3, 3, 3, //当前在向量中的是什么
Delete indx 0 & 1 //The first pair that I will erase and increment count Delete indx 0 & 1 //我将擦除的第一对并递增计数

3, 1, 2, 1, 3, 3, 3, 3, //continue... 3, 1, 2, 1, 3, 3, 3, 3, //继续...
Delete indx 0 & 4删除索引 0 & 4

1, 2, 1, 3, 3, 3, 1, 2, 1, 3, 3, 3,
Delete indx 0 & 2删除索引 0 & 2

2, 3, 3, 3, 2, 3, 3, 3,
Delete indx 1 & 2 //says to delete the first and second three Delete indx 1 & 2 //表示删除前三个和后三个

3, 3, //it looks like the 0th and some other index was erased instead 3, 3, //看起来第0个和其他一些索引被删除了
Delete indx 0 & 1删除索引 0 & 1

count returned is: 5返回的计数为:5
let me know if I can add to this question to make it better, thanks如果我可以添加到这个问题以使其更好,请告诉我,谢谢

int i, count = 0;

for (i=0;i<ar.size()-1;i++)
{
    for (int j=i+1;j<ar.size();j++)
    {
        if (ar[i] == ar[j])
        {
            ar.erase(ar.begin()+i-1);
            ar.erase(ar.begin()+j-1);
            count++;
            i=-1;
            break;
        }
    }
    if (ar.size()== 0)
        break;
}

From what I understood, you only need the count of pairs (considering the removals).据我了解,您只需要对的数量(考虑到删除)。

for(int i = 0; i < ar.size() - 1; i++){
    for(int j = i + 1; j < ar.size(); j++){
        if(ar[i] == ar[j]) {
            ar.erase( ar.begin() + j );
            count++; 
            break;
        }
    }
}

This way you only need to perform 1 call of erase (which is slow, considering it moves all the elements in the right of the deleted element 1 slot to the left).这样您只需要执行 1 次擦除调用(这很慢,考虑到它将已删除元素 1 插槽右侧的所有元素向左移动)。

If you have big vectors, also consider not using ar.size() all the time (at least in j loop, since in i loop it's kind of essential).如果你有大向量,也不要一直使用ar.size() (至少在j循环中,因为在i循环中它是必不可少的)。 Try for(int j = i + 1, len = ar.size(); j < len; j++) .尝试for(int j = i + 1, len = ar.size(); j < len; j++)

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

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