C++ List STL's Etherator Usage

Asked 2 years ago, Updated 2 years ago, 50 views

#include <iostream>
#include <list>

int main() {
    std::list<std::string&> list = {"January", "February", "March", "April", "May"};

    std::list<std::string&>::iterator listItr = list.begin();

    while (listItr != list.end()) {
        std::cout << (*listItr).at(0) << "\n";
        ++listItr;
    }

    return 0;
}

If you write and compile the code like this, you'll get a huge amount of error messages that are hard to upload here.

We put five strings in a list that stores a string pointer (reference), and we had the first character of each string output while circulating the list with an iterator for this list...What's wrong?

c++ list

2022-09-22 10:40

1 Answers

    std::list<std::string> list = { ... };

There's no problem doing this.

I looked it up and found the following questions and answers in stackoverflow.

https://stackoverflow.com/questions/4010937/why-does-storing-references-not-pointers-in-containers-in-c-not-work


2022-09-22 10:40

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.