Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

Reverse iterator for a list (C++)

Status
Not open for further replies.

rogger123

Advanced Member level 4
Full Member level 1
Joined
Apr 9, 2003
Messages
112
Helped
1
Reputation
2
Reaction score
0
Trophy points
1,296
Activity points
1,232
Hi,
I have a problem compiling the following piece of code using reverse itretor for a list.


#include <iostream>
#include <list>
using namespace std;

// Display elements in reverse order
template <class T>
void displayListRev(const list<T> &lst)
{
list<T>::reverse_iterator rl;
for(rl = lst.rbegin(); rl < lst.rend(); ++rl)
cout << *rl << ' ';
cout << endl;
}

int main()
{
list<int> listType;
listType.push_back(10);
listType.push_back(30);

listType.sort();
cout << "List contents in reverse order: ";
displayListRev(listType);
return 0;
}


it gives me errors for the "for" loop. one of the error is pasted below:
"binary '=' : no operator defined which takes a right-hand operand of type 'class std::reverse_bidirectional_iterator<class std::list<int,class std::allocator<int> >::const"


If I get rid of the function 'displayListRev(listType)' and instead add the correcponding function code within the main function, the error gets resolved and correct output is generated.
Can someone explain the reason for this behaviour.
The modified code is as shown below:

#include <iostream>
#include <list>
using namespace std;

int main()
{
list<int> listType;
list<int>::reverse_iterator rl;
listType.push_back(50);
listType.push_back(30);

listType.sort();
cout << "List contents in reverse order: ";
for(rl = listType.rbegin(); rl != listType.rend(); ++rl)
cout << *rl << ' ';
return 0;
}

regards
rogger123
 

If you look closely at the definition of your function

template <class T>
void displayListRev(const list<T> &lst)

You have declared the parameter lst of type const.
Therefore to iterate over the list you must use one
of the const iterators, i.e.
list<T>::const_reverse_iterator rl;

This should fix your compiler warning about not being able
to do the assignment.

Alpha
 

    rogger123

    Points: 2
    Helpful Answer Positive Rating
thanks for the solution...as you said, it was the 'const' that was creating the problem.
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top