【问题标题】:How can I make a pointer to list iterator to pass into function as an argument?如何使指向列表迭代器的指针作为参数传递给函数?
【发布时间】:2015-05-01 16:38:03
【问题描述】:

我有这个函数names_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;
}

我该怎么做?

【问题讨论】:

    标签: c++ list pointers iterator


    【解决方案1】:

    实现函数的最佳方式是按值传递 2 个迭代器(这是 C++ 标准库中有多少算法起作用):一个迭代器到列表的开头,一个迭代器到结尾:

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

    然后简单地调用你的函数

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

    通过这种方式,您可以将算法与数据结构分开。更好的是,您可以通过模板传递任意迭代器,然后您的函数将适用于任意容器:

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

    【讨论】:

      【解决方案2】:
      for (std::set<std::string>::const_iterator it = NameList.begin(); it != NameList.end(); ++it)
          std::cout << *it << std::endl;
      

      迭代器取消引用 (*it) 将为您提供包含名称的字符串。

      在您的方法中,您应该传递对名称列表的引用并使用我提供的代码打印每个名称。

      编辑最终代码如下所示:

      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
      }
      

      确保包含以下库:iostream、list、string

      【讨论】:

      • 你能给出你遇到的错误吗?您是否包含
      猜你喜欢
      • 2019-08-17
      • 2015-03-17
      • 2021-07-18
      • 2014-04-16
      • 2014-11-26
      • 2020-09-06
      • 2014-11-04
      • 1970-01-01
      • 2012-01-24
      相关资源
      最近更新 更多