stl find函数从双端队列返回什么

Mar*_*cik 0 c++ deque c++14

我有一个std双端队列并在其中搜索元素。我的问题是我不明白查找功能返回的是哪种形式。

std::deque< DataCellHandle > dataCellHandleArray;
std::_Deque_iterator<DataCellHandle, const DataCellHandle&, const DataCellHandle*> it =
    std::find( dataCellHandleArray.cbegin(), dataCellHandleArray.cend(), releaseHandle ); // works

std::deque< DataCellHandle >::iterator itr =
    std::find( dataCellHandleArray.cbegin(), dataCellHandleArray.cend(), releaseHandle ); // does not work
Run Code Online (Sandbox Code Playgroud)

我预计将返回索引或迭代器。

Yks*_*nen 5

std::find返回与firstlast参数类型相同的对象,在您的情况下为std::deque<DataCellHandle>::const_iterator


lub*_*bgr 5

的返回类型std::find与用于实例化此函数模板的迭代器的类型相同。就您而言,您传递了dataCellHandleArray.cbegin()and .cend(),其类型为std::deque::const_iterator,而不是std::deque::iterator。因此,这是你的修复:

std::deque<DataCellHandle>::const_iterator it = ...
Run Code Online (Sandbox Code Playgroud)

请注意,这可以开箱即用:

auto it = std::find(dataCellHandleArray.cbegin(), dataCellHandleArray.cend(),
   releaseHandle);
Run Code Online (Sandbox Code Playgroud)

请注意,aconst_iterator可以由 an 构造而成iterator,但不能由其逆构造。

// Ok, iterator to const_iterator
std::deque<DataCellHandle>::const_iterator ci = dataCellHandleArray.begin();

// Ok, compare const_iterator and iterator:
assert(ataCellHandleArray.begin() == ataCellHandleArray.cbegin());

// Error, can't loose constness of the "pointee"
std::deque<DataCellHandle>::iterator ci = dataCellHandleArray.cbegin();
Run Code Online (Sandbox Code Playgroud)