LouieV1994
LouieV1994

Reputation: 11

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}. 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. And repeat the process every time the mod results in 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);
            }
        }
    }
}

Upvotes: 0

Views: 140

Answers (2)

LogicStuff
LogicStuff

Reputation: 19607

You'll have to discard listSize and use numList.size(), that will give you the current size. You might as well delete the whole remainder = numList[i] % numList[j];, while we're at it. I guess you're not using remainder afterwards, remove it completely.

Important:

  1. The element of larger index should be removed first, then the smaller.
  2. You shouldn't increment i and j in the cycle where erasing occurred - you don't want to skip any elements.
  3. There's 1 in among the elements that will pair up with anything. 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++)

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

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.

Upvotes: 0

Related Questions