繁体   English   中英

遍历 C++ 中的向量并擦除某些元素

[英]Iterating over vectors in C++ and erasing certain elements

只是为了提供背景,我正在尝试在 C++ 中编写一个 function ,它采用整数向量和特定整数,并删除与特定整数匹配的向量的所有元素,同时返回它的次数出现。

我不是在寻求帮助来解决问题。 我一直试图弄清楚为什么错误的元素被删除了。 这是代码:

int removeElement(vector<int>& nums, int val) {
    int output = 0;
    int i = 0;
    while (i < nums.size()) {
        cout << nums[i] << "  " << i << "  " << (nums[i] == val) << "\n";
        if (nums[i] == val) {
            nums.erase(nums.begin() + i);
            output+=1;
        }
        else {
            i += 1;
        }
    }
    cout << "---------------\n";
    return output;
    }

这是我用来测试它的内容:

int main() {
    vector<int> firstOne = {3,2,2,3};
    cout << removeElement(firstOne,2) << "\n";
    firstOne = {3,2,2,3};
    cout << removeElement(firstOne,3) << "\n";
}

output 应该是 {3,3} 然后是 {2,2} 但它是 {3,3} 两次。 不仅如此,当我尝试使用只有 2 个元素的向量对其进行测试时,整个事情都会崩溃。 我怀疑我对向量如何工作的理解存在差距。 谁能向我解释我做错了什么?

最好使用erase-remove成语

int removeElement(vector<int>& nums, int val) {
    int output = 0;
    int i = 0;
    // remove if moves elements "to be removed" in the end
    auto newend = std::remove_if(nums.begin(), nums.end(), [&](int element){
        cout << element << "  " << i << "  " << (element == val) << "\n";
        
        i++;
        if(element == val) {
            output++;
            return true; // if true, element will be removed
        }

        return false; // if false, element will not be removed
    });

    nums.erase(newend, nums.end());

    cout << "---------------\n";
    return output;
}

除了您刚刚修复的评论中建议的问题外,您的代码工作正常。 您也没有在任何地方更新output ,因此 function 始终返回0而不是int在传递的vector中出现的次数。 我稍微编辑了你的 function,对 go 很好:

int removeElement(vector<int>& nums, int val) {
    int output = 0;
    int i = 0;
    while (i < nums.size()) {
        cout << nums[i] << "  " << i << "  " << (nums[i] == val) << "\n";
        if (nums[i] == val) {
            nums.erase(nums.begin() + i);
            output++;
        }
        else {
            i += 1;
        }
    }
    cout << "---------------\n";
    return output;
}

暂无
暂无

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

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