c++ - 迭代器作为 C++ 中的函数输入?

标签 c++ iterator

我在下面的简单代码中遇到了问题:

  void foo (vector<int>:: iterator it, vector<int> n)
  {
       vector<int>:: iterator it2 = it +1;
       while (it2!=n.end())
       {
           cout<<*it2<<endl;
           it2++;
       }
  }
  main()
  {
        vector<int> m{1,2,3,4};
        vector<int>:: iterator it = m.begin();
        foo (it, m);
  }

我希望终端中有 2、3 和 4,但我在输出中得到了一些愚蠢的结果。基本上可以使用迭代器作为函数的输入吗?这段代码有什么问题?我怎样才能使它正确?

最佳答案

你通过了vector<int> n作为拷贝。因此你的 it2指向不同的 vector (在 main 中创建的 vector )。您的支票it2!=n.end()it2 起无效是另一个 vector 的迭代器。

传递 n通过引用是一种解决方案。其他方法将传递结束迭代器而不是 vector 。

将 vector 作为常量引用传递:

void foo (vector<int>:: iterator it, const vector<int>& n)

传递结束迭代器:

void foo (vector<int>::iterator it, vector<int>::iterator end)
{
 ...
     while ( it2 != end )
 ...
}

关于c++ - 迭代器作为 C++ 中的函数输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43804842/

相关文章:

c++ - 返回 C++ 迭代器引用

python - 如何并行遍历两个列表?

java - 我应该如何正确地迭代优先级队列?

c++ - 我是否在 Visual Studio 中正确设置了 boost 包含和链接器路径? (提供的步骤)

c++ - 在Visual Studio 2013终极项目中使用FFMPEG,链接错误LNK2019

c++ - 通过 mpi 发送 c++ std::vector<bool>

Python 迭代器 : What does iglob( )'s Iterator provide over glob()' s list?

c++ - 没有这样的插槽 QProgressBar::setValue(const int)

C++:xcode中退出代码为-1的链接器命令

c++ - 如果对象位于可能的最高地址怎么办