如何修改函数中的迭代器?

时间:2013-12-31 02:42:08

标签: c++

假设我们有:

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

typedef map<int,int>::iterator it;

void some_func(it the_iterator)
{
   the_iterator->second += 1; //I want this value to change in main()
}

int main()
{
   //construct/populate map here

   for(it the_iterator = my_map.begin(); the_iterator != my_map.end(); the_iterator++)
   {
      some_func(the_iterator);
   }
}

我本质上是试图通过引用传递迭代器来更改函数中的map值,但我不确定如何执行此操作,因为迭代器使用起来有点棘手。我有什么想法可以做到这一点吗?

1 个答案:

答案 0 :(得分:-2)

问题是您的代码正在传递集成商by value

要传递它by reference,您的变量类型需要作为参考:

void some_func(it & the_iterator )

&是关键。