[英]remove element from vector and adding that element to a new vector c++
我有一個std::vector<int> numList
,它包含{9,6,3,3,2,1}
。 我想要的是在循環期間,一旦我們達到9 % 3 == 0
,我想將9
放入新的向量v1
,將3
放入v2
,同時從原始列表中刪除這些數字。 每次mod結果為0
時,重復此過程。
我有這個但是崩潰了:
for(i = 0; i < listSize; i++)
{
for(j = 0; j < listSize; j++)
{
if(i != j)
{
remainder = numList[i] % numList[j];
if(numList[i] % numList[j] == 0)
{
//cout<< numList[i] << " " << numList[j]<<endl;
v1.push_back(numList[i]);
v2.push_back(numList[j]);
numList.erase(numList.begin() + i);
numList.erase(numList.begin() + j);
}
}
}
}
您將必須放棄listSize
並使用numList.size()
,這將為您提供當前大小。 您也可以刪除整個remainder = numList[i] % numList[j];
,而我們正在這樣做。 我想您之后沒有使用remainder
,請將其完全刪除。
重要:
i
和j
-您不想跳過任何元素。 1
會與任何事物配對。 解決條件。 總而言之,這並不酷 :
int i; // just absurd
// list of variable declarations that are not needed right now, or not needed at all
for(i = 0; i < listSize; i++)
這樣更好:
for(int i = 0; i < numList.size(); i++)
我認為您需要以下內容
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> v = { 9, 6, 3, 3, 2, 1 };
std::vector<int> v1;
std::vector<int> v2;
for ( std::vector<int>::size_type i = 0; i < v.size(); )
{
std::vector<int>::size_type j = i + 1;
while ( j < v.size() && v[i] % v[j] ) j++;
if ( j != v.size() )
{
v1.push_back( v[i] );
v2.push_back( v[j] );
v.erase( std::next( v.begin(), j ) );
v.erase( std::next( v.begin(), i ) );
}
else
{
i++;
}
}
for ( int x : v1 ) std::cout << x << ' ';
std::cout << std::endl;
for ( int x : v2 ) std::cout << x << ' ';
std::cout << std::endl;
}
程序輸出為
9 6 2
3 3 1
考慮到內部循環中的索引不能小於匹配元素的外部循環中的索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.