有什么方法可以将 vector::iterator
转换为指针而无需访问 vector 本身?这仅在 vector
可用时有效:
typedef vector<int> V;
int* to_pointer1( V& v, V::iterator t )
{
return v.data() + (t-v.begin() );
}
但是如果没有 vector
如何做到这一点呢?这行不通:
int* to_pointer2( V::iterator t )
{
// the obvious approach doesn't work for the end iterator
return &*t;
}
事实上,我本以为这是一个非常基本和流行的问题,但由于某种原因我找不到它。
最佳答案
通常,您不能保证有一个指针对应于指向普通 vector 项的迭代器。
特别是std::vector<bool>
是专门的,所以 &*it
甚至不会编译。
但是,对于其他 vector ,它只是1 形式上的迂腐阻止你做 &*it
也用于结束迭代器。在 C99 中,我记得,做 &*p
是正式有效的什么时候p
是一个结束指针,目标是std::vector
是支持所有普通的原始数组表示法。如果我需要这个,我会忽略形式上的迂腐,并编写代码,着眼于 future 对标准的修订,以消除想象中的障碍。
因此,在实践中,只需执行 &*it
. :)
#include <iostream>
#include <vector>
using namespace std;
auto main() -> int
{
vector<int> x( 5 );
cout << &*x.begin() << " " << &*x.end() << endl;
cout << &*x.end() - &*x.begin() << endl; // Works nicely IN PRACTICE.
}
但请记住,您不能为 vector<bool>
执行此操作.
1) 在评论中 elsewhere用户 pentadecagon备注:“试试-D_GLIBCXX_DEBUG
,如此处所述:gcc.gnu.org/onlinedocs/libstdc++/manual/debug_mode_using.html ” g++ 通常提供一些方法将任何正式的 UB 带到前面,例如正式 UB 循环的“优化”。在这种特殊情况下,一种解决方案就是不要求它这样做,但更一般地说,可能必须明确要求它不要这样做。
关于c++ - 将 vector 迭代器转换为指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24280812/