简体   繁体   中英

How can I make a pointer to list iterator to pass into function as an argument?

I have this function names_list() to display the list and I want to pass the reference to my string list iterator to this function and print the whole list.

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

void names_list(list<string>::iterator *i,list<string> *n){
     while(*i != *(n.end()))
    {
        cout<<i<<endl;
        i++;
    }
}
int main(){
    list<string> names;
    list<string> *name_ptr = names;
    names.push_back("vivek");
    names.push_back("Anup");
    names.push_back("kali");
    list<string>:: iterator iter = names.begin();
    names_list(&iter,&name_ptr);
    return 0;
}

How can I do it?

for (std::set<std::string>::const_iterator it = NameList.begin(); it != NameList.end(); ++it)
    std::cout << *it << std::endl;

The iterator dereference (*it) will give you the string containing the name.

In your method you should pass a reference to the list of name and print each of them using the code I have provided.

EDIT The final code would look like this:

void names_list(list<string>& n){
    for (list<string>::const_iterator it = n.begin(); it != n.end(); ++it)
        std::cout << *it << std::endl;
}

int main()
{
    list<string> names;
    names.push_back("vivek");
    names.push_back("Anup");
    names.push_back("kali");

    names_list(names);


    system("pause"); // return 0
}

Make sure you include the following libraries: iostream, list, string

The best way of implementing your function is to pass 2 iterators by value (this is how many algorithms in the C++ Standard Library work): an iterator to the beginning of the list, and one to the end:

void names_list(list<string>::iterator beg, list<string>::iterator end){
    while( beg != end)
    {
        cout << *beg++ << endl; // we increment here
    }
}

then invoke your function simply as

names_list(names.begin(), names.end());

In this way you separate your algorithm from the data structure. Even better, you can pass arbitrary iterators via templates, and your function will work then with arbitrary containers:

template<typename T>
void names_list(typename T::iterator beg, typename T::iterator end)
{
    while( beg != end)
    {
        cout << *beg++ << endl; // we increment here
    }
}

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