[英]remove element from vector and adding that element to a new vector c++
I have a std::vector<int> numList
and it contains {9,6,3,3,2,1}
. 我有一个
std::vector<int> numList
,它包含{9,6,3,3,2,1}
。 What I want, is during the loop, once we hit 9 % 3 == 0
, I want to put 9
into a new vector v1
and 3
into v2
, while erasing these numbers from the original list. 我想要的是在循环期间,一旦我们达到
9 % 3 == 0
,我想将9
放入新的向量v1
,将3
放入v2
,同时从原始列表中删除这些数字。 And repeat the process every time the mod results in 0
. 每次mod结果为
0
时,重复此过程。
I have this but it crashes: 我有这个但是崩溃了:
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);
}
}
}
}
You'll have to discard listSize
and use numList.size()
, that will give you the current size. 您将必须放弃
listSize
并使用numList.size()
,这将为您提供当前大小。 You might as well delete the whole remainder = numList[i] % numList[j];
您也可以删除整个
remainder = numList[i] % numList[j];
, while we're at it. ,而我们正在这样做。 I guess you're not using
remainder
afterwards, remove it completely. 我想您之后没有使用
remainder
,请将其完全删除。
Important: 重要:
i
and j
in the cycle where erasing occurred - you don't want to skip any elements. i
和j
-您不想跳过任何元素。 1
in among the elements that will pair up with anything. 1
会与任何事物配对。 Fix the condition. To conclude, this is not cool : 总而言之,这并不酷 :
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++)
This is much better: 这样更好:
for(int i = 0; i < numList.size(); i++)
I think you need something like the following 我认为您需要以下内容
#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;
}
The program output is 程序输出为
9 6 2
3 3 1
Take into account that the index in the inner loop can not be less than the index in the outer loop for matching elements. 考虑到内部循环中的索引不能小于匹配元素的外部循环中的索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.