gpt4 book ai didi

c++ - 我使用 C++ 标准库的 find 有什么问题?

转载 作者:IT老高 更新时间:2023-10-28 22:33:25 25 4
gpt4 key购买 nike

我正在尝试像这样使用 C++ 标准库的 find 算法:

  template<class T>
const unsigned int AdjacencyList<T>::_index_for_node(
const std::vector<T>& list, const T& node
) throw(NoSuchNodeException)
{
std::vector<T>::iterator iter = std::find(list.begin(), list.end(), node);
}

当我尝试编译时,出现以下错误:

In file included from ../AdjacencyList.cpp:8:
../AdjacencyList.h: In member function ‘const unsigned int Graph::AdjacencyList<T>::_index_for_node(const std::vector<T, std::allocator<_Tp1> >&, const T&)’:
../AdjacencyList.h:99: error: expected ‘;’ before ‘iter’
../AdjacencyList.h:100: error: ‘iter’ was not declared in this scope
In file included from ../AdjacencyListTest.cpp:9:
../AdjacencyList.h: In member function ‘const unsigned int Graph::AdjacencyList<T>::_index_for_node(const std::vector<T, std::allocator<_Tp1> >&, const T&)’:
../AdjacencyList.h:99: error: expected ‘;’ before ‘iter’
../AdjacencyList.h:100: error: ‘iter’ was not declared in this scope
../AdjacencyList.h: In member function ‘const unsigned int Graph::AdjacencyList<T>::_index_for_node(const std::vector<T, std::allocator<_Tp1> >&, const T&) [with T = int]’:
../AdjacencyList.h:91: instantiated from ‘const std::vector<T, std::allocator<_Tp1> > Graph::AdjacencyList<T>::neighbours(const T&) [with T = int]’
../AdjacencyListTest.cpp:18: instantiated from here
../AdjacencyList.h:99: error: dependent-name ‘std::vector::iterator’ is parsed as a non-type, but instantiation yields a type
../AdjacencyList.h:99: note: say ‘typename std::vector::iterator’ if a type is meant

我觉得“从属名称'std::vector::iterator'被解析为非类型,但实例化产生类型”位是理解我做错了什么的关键,但我的豌 bean - 大脑无法提取含义。

更新:我需要添加一个 typename,根据接受的答案,并且还使用 const_iterator,所以有问题的行代码变成了:

    typename std::vector<T>::const_iterator iter = std::find(list.begin(), list.end(), node);

最佳答案

std::vector<T>::iterator iter = /* .... */; 

iterator 是一个依赖名称(实际上,它依赖 类型参数T)。除非您使用 typename,否则假定从属名称不会命名类型:

typename std::vector<T>::iterator iter = /* .... */;

有关更多信息,请考虑阅读 Stack Overflow C++ 常见问题解答条目 "Where and why do I have to put “template” and “typename” on dependent names?"

您还需要使用 const_iterator,因为 list 是 const 限定的。您可能也应该删除异常规范;最好是"never write an exception specification."

关于c++ - 我使用 C++ 标准库的 find 有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5719842/

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