0

Here is the code to my main method, it should be obvious what i'm trying to do with trying to get the iterator to access an element by name

#include <iostream>
#include <list>
#include "PC.h"
#include "SunServer.h"

using namespace std;

int main(){
    PC mypc1("John", "645.22.55.34", 128, "admin");
    PC mypc2("Mike", "645.22.55.34", 128, "admin");
    PC mypc3("Rick", "645.22.55.34", 128, "admin");
    PC mypc4("Bill", "645.22.55.34", 128, "admin");

    list<PC> my_group;

    my_group.push_front(mypc1);
    my_group.push_front(mypc2);
    my_group.push_front(mypc3);
    my_group.push_front(mypc4);
    list<PC>::iterator curr = my_group.begin();

    while (curr != mypc2){
        // do something
    }

}

Now obviously it doesn't work, but is there something I can do that would be equivalent to this? Thank you

2
  • Do you increment your iterator inside while {} ? Do like this: ++curr Commented Apr 24, 2015 at 2:53
  • yes that is what I would be doing, the problem is with the (curr != mypc2), it wont except being compared to an object, it wants to be compared to a location in the list, such as (curr != my_group.end()) Commented Apr 24, 2015 at 2:54

1 Answer 1

5

That's because curr is an iterator, and you need something that is a PC to compare against. To get a reference to what the iterator is pointing to, you just have to dereference it (just as if it were a pointer, not a coincidence):

while (*curr != mypc2) {

I'm not sure what you're planning on doing within the loop, but if what you want is just to find the mypc2, you can use std::find:

std::list<PC>::iterator it = std::find(my_group.begin(),
                                       my_group.end(),
                                       mypc2);
Sign up to request clarification or add additional context in comments.

7 Comments

sounds like a solid idea, ill be sure to try it, thanks I did not know that "find" was a thing
@HunterTipton, I recommend reading through this reference and seeing what other algorithms there are. I also recommend std::vector unless you have a good reason not to use it.
Well I have to be able to add and delete at any point in the container, which to my knowledge a vector cannot do
@HunterTipton It definitely can. It's just O(N), whereas list would be O(1).
also @Barry I attempted to use the find algorithm and recieved this error "error C2678: binary '==' : no operator found which takes a left-hand operand of type 'PC' ", I did try this after including <algorithm> and it did not help
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.