将迭代器转换为指针? [英] Convert iterator to pointer?

查看:199
本文介绍了将迭代器转换为指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有n元素的std::vector.现在,我需要传递一个指向向量的指针,该向量具有最后一个n-1元素到函数.

I have a std::vector with n elements. Now I need to pass a pointer to a vector that has the last n-1 elements to a function.

例如,我的vector<int> foo包含(5,2,6,87,251).一个函数使用vector<int>*,我想将其传递给(2,6,87,251)的指针.

For example, my vector<int> foo contains (5,2,6,87,251). A function takes vector<int>* and I want to pass it a pointer to (2,6,87,251).

我是否可以(安全地)使用迭代器++foo.begin(),将其转换为指针并将其传递给函数?还是使用&foo[1]?

Can I just (safely) take the iterator ++foo.begin(), convert it to a pointer and pass that to the function? Or use &foo[1]?

更新:人们建议我将函数更改为采用迭代器而不是指针.在我的情况下,这似乎是不可能的,因为我提到的函数是unordered_set<std::vector*>find函数.因此,在那种情况下,是否将foo中的n-1元素复制到新的向量中,并用指向该唯一对象的指针调用find?效率很低!就像画家Shlemiel一样,尤其是因为我必须查询许多子集:最后一个n-1,然后是n-2等元素,并查看它们是否在unordered_set中.

UPDATE: People suggest that I change my function to take an iterator rather than a pointer. That seems not possible in my situation, since the function I mentioned is the find function of unordered_set<std::vector*>. So in that case, is copying the n-1 elements from foo into a new vector and calling find with a pointer to that the only option? Very inefficient! It's like Shlemiel the painter, especially since i have to query many subsets: the last n-1, then n-2, etc. elements and see if they are in the unordered_set.

推荐答案

在我的情况下,这似乎是不可能的,因为我提到的功能是unordered_set<std::vector*>的查找功能.

您是否正在使用自定义哈希/谓词函数对象?如果不是,则必须将unordered_set<std::vector<int>*>::find()指针传递给要查找的确切向量.指向具有相同内容的另一个向量的指针将不起作用.至少可以说,这对于查找不是很有用.

Are you using custom hash/predicate function objects? If not, then you must pass unordered_set<std::vector<int>*>::find() the pointer to the exact vector that you want to find. A pointer to another vector with the same contents will not work. This is not very useful for lookups, to say the least.

使用unordered_set<std::vector<int> >会更好,因为这样您就可以按值执行查找.我认为这也需要自定义哈希函数对象,因为据我所知hash并不具有vector<int>的专门化.

Using unordered_set<std::vector<int> > would be better, because then you could perform lookups by value. I think that would also require a custom hash function object because hash does not to my knowledge have a specialization for vector<int>.

无论哪种方式,指向向量中间的指针本身都不是向量,正如其他人所解释的那样.您不能在不复制其内容的情况下将迭代器转换为向量的指针.

Either way, a pointer into the middle of a vector is not itself a vector, as others have explained. You cannot convert an iterator into a pointer to vector without copying its contents.

这篇关于将迭代器转换为指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆