I need help deleting from a vector. My program is about the josephus problem. It has to delete soldiers. It does deletes the first one but then it stops. Thank you!

Well I see that you will need to delete all the members until you are left with one.

So you will need to do this.

#include <iostream> 
#include <list>

using namespace std;
int main() {
  int n;//number of soldiers 
  int k;//number skipped between  
     
       cout << "Welcome to The Josephus Problem" << endl;
       cout << "Please enter the number of soldiers in the army." << endl; 
       cin >> n;
       cout << "Please enter the number to be skipped between sucessive executions." << endl; 
       cin >> k; 

       list < int > soldiers;
	    for ( int i = 0; i < n; i++ ) 
	   soldiers.push_back ( i + 1 );
	   
  list < int > :: iterator p;
	 
  p = soldiers.begin ();
while(soldiers.size()==1)
{
  for ( int i = 0; i < k-1; i++ ) {
	   p++;
	   if ( p == soldiers.end() )
		   p = soldiers.begin ();
	   }
	   p = soldiers.erase ( p );
       
       
	   for ( p = soldiers.begin(); p != soldiers.end(); p++ ){

	   cout << *p;
	   }
 }
	   

	   system("pause"); 
        
        return 0;
}

I dint check the code. But it should work.

Something is wrong because it is not outputting anything. Thank you!

while(soldiers.size()==1)

This while statement is ill

#include <iostream> 
#include <list>

using namespace std;
int main() {
  int n;//number of soldiers 
  int k;//number skipped between  
     
       cout << "Welcome to The Josephus Problem" << endl;
       cout << "Please enter the number of soldiers in the army." << endl; 
       cin >> n;
       cout << "Please enter the number to be skipped between sucessive executions." << endl; 
       cin >> k; 

       list < int > soldiers;
	    for ( int i = 0; i < n; i++ ) 
	   soldiers.push_back ( i + 1 );
	   
  list < int > :: iterator p;
	 
  p = soldiers.begin ();
while(soldiers.size()!=1)
{
  for ( int i = 0; i < k-1; i++ ) {
	   p++;
	   if ( p == soldiers.end() )
		   p = soldiers.begin ();
	   }
	   p = soldiers.erase ( p );
       
       
	   for ( p = soldiers.begin(); p != soldiers.end(); p++ ){

	   cout << *p;
	   }
 }
	   

	   system("pause"); 
        
        return 0;
}

I guess it is solved now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.