【发布时间】:2017-12-09 07:34:18
【问题描述】:
给定一个 std:: 列表
std::list< int > myList
以及对该列表中元素的引用(或指针)
int& myElement | int* pElement
所以,基本上我知道那个元素的地址
如何有效地为该元素获取std::list<int>::iterator?
一个缓慢但有效的例子是
const_iterator it
for( it = myList.begin(); it != &myElement; ++it)
{
// do nothing, for loop terminates if "it" points to "myElem"
}
有没有更快的方法?喜欢
const_iterator it = magicToIteratorConverter( myList, myElem )
向量案例(但我需要列表):
对于向量,您可以执行以下操作:
const int* pStart = &myVector[0] // address of first element
const int* pElement = &myElem; // address of my element
const idx = static_cast< int >( pElement- pStart ); // no need to divide by size of an elem
std::vector< int >::iterator it = myVector.begin() + idx;
std::list 案例:
【问题讨论】:
-
您的“缓慢而有效”的示例通常不起作用。
-
std::find也许? -
@LightnessRacesinOrbit:
v.begin() + (&element - &v[0]) -
@S.H. : 做不到。我建议您首先查看对元素的引用的位置。因为无论它在哪里,它一开始都是一个迭代器。因此,如果您一开始就需要一个迭代器,为什么要丢弃它?
-
那么你要么重写它,要么坚持使用 O(n) 算法。因为你所要求的是不可能的。
标签: c++ list c++11 stl iterator