[英]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.