简体   繁体   中英

C++ 11 STL Lists = and != op not defined

I am trying to use C++ list ADT, but I can't seem to make the iterator or call to work right. I don't know how to initialize a new list from an array, and I keep getting the error that = and != operators are not defined for iterator. This code IS based on a friends homework (I was trying to show him he could improve his code by using lists). I've cut out all the logic but the variable declarations and the portion of code that throws error.

#include <list>

using namespace std;

const static char *dias[] = {"Domingo", "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado"};

//Don't know how to initialize list from array
const static list<char *> DIAS (7);

int main (int argc, char *argv[]) {
    list<char *>::iterator iter;

        //ERROR HERE. Says = and != operator not defined for iterator iter.            
    for(iter = DIAS.begin(); iter != DIAS.end(); ++iter){
    }

    return 0;
}

I based my code on the example code and documentation found at: http://www.cplusplus.com/reference/list/list/list/

Your list is const , so you need a const_iterator :

list<char *>::const_iterator iter;

In C++11, you could have avoided this problem with a simple modification to your code:

for(auto iter = DIAS.begin(), end = DIAS.end(); iter != end; ++iter){ ... }

As for the list initialization, C++11 allows you to do this:

static const std::list<const char*> DIAS{"Domingo", "Lunes", "Martes", "Miercoles", 
                                         "Jueves", "Viernes", "Sabado"};

Note that the type should be const char* , since the elements point to string literals.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM