deque small problem

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <queue>
#include <deque>

using namespace std;

int main(){

	deque<int> d;
	queue<int> q;

	q.push(5);
	q.push(11);
	q.push(34);
	q.push(67);
	q.push(43);
	q.push(55);


	while( !q.empty() ){
		d.push_back( q.front() );
		q.pop();
	}

	deque<int>::iterator it = d.begin();
	for( ; it != d.end() ; ++it ){
		cout << *it << endl;
	}

	cout << "Enter a position : ";
	int n = 0;
	cin  >> n;

	int temp = 0;
	it = d.begin();
	cout<<*it;
	cout << endl;
	
	it = it + n - 1;
	temp = *it;
	d.erase( it );

	d.push_front( temp );
	for( ; it != d.end() ; ++it ){
		cout << *it << endl;
	}


	system( "pause" );
	return 0;
}


why when i debugging my program.
the erase there already got problem?

my question is

queue = {5, 11, 34, 67, 43, 55} and n = 3.

After a call to the function, queue = {34, 5, 11, 67, 43, 55}.

After d.erase(it), the iterator it is no longer valid.

@JL. so i just redeclare again?

but fail..
deque<int>::iterator it2 = d.begin();

how should i do?
mind provide?
> so i just redeclare again?

Not redeclare it; just reset it to a valid value. eg. it = d.begin() ;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <queue>
#include <deque>

using namespace std;

int main()
{

	deque<int> d { 5, 11, 34, 67, 43, 55 } ;

	deque<int>::iterator it = d.begin() ;
	for( ; it != d.end() ; ++it ) cout << *it << ' ' ;
	cout << '\n' ;

	// at this point it == d.end()
	it = d.begin() ; // reset it to the beginning

	cout << "Enter a position (zero based): ";
	std::size_t n = 0 ;
	cin  >> n ;

	if( n < d.size() )
        {
            it = d.begin() + n ;
            int temp = *it ;
            d.erase(it) ;
            d.push_front( temp );
        }

        // at this point 'it' is invalid
	it = d.begin() ; // reset it
	for( ; it != d.end() ; ++it ) cout << *it << ' ' ;
	cout << '\n' ;
}
Topic archived. No new replies allowed.