gpt4 book ai didi

C++ 列表迭代器到函数

转载 作者:行者123 更新时间:2023-11-27 22:51:17 25 4
gpt4 key购买 nike

我试图将迭代器传递给一个单独的函数,然后对列表中该位置的元素执行某些操作。

这对我不起作用。

#include <list>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
void doSomething(iterator::<int> *it);

list<int> intList;

intList.push_back(10);
intList.push_back(20);
intList.push_back(10);
intList.push_back(30);

list<int>::iterator it;



for (it = intList.begin(); it != intList.end(); it++)
{
if (*it == '10')
doSomething(*it);
};

void doSomething(iterator <int> *it)
{
(*it) = 200;
};
}

最佳答案

iterator本身不是独立的类型。它只是一个 typedef(它可能不止于此。但我们可以安全地假设这个问题)

list<int>::iterator是一个单独的类型,vector<int>::iterator 也是。层次结构中没有任何公共(public)类。所有接受 iterator 的函数通常是模板化函数,其中模板类型具有满足 iterator 要求的约束.

对于您的情况,您必须申报 doSomething作为:

void doSomething(list::iterator <int> it);  // will only work with std::list iterators

或者大多数 STL 函数/容器接受迭代器的方式

template<typename Iterator>
void doSomething(Iterator it); // generic. Will work with any container whose iterator has an overload for * operator

无论哪种情况,你都可以在调用方做

for (it = intList.begin(); it != intList.end(); it++)
{
if (*it == 10)
doSomething(it);
};

关于C++ 列表迭代器到函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37042606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com