简体   繁体   English

通过迭代器访问另一个向量内的向量元素?

[英]Accessing vector elements inside another vector through an iterator?

std::vector< std::vector<coords> >::iterator iter;
for(iter = characters.begin(); iter != characters.end(); iter++) 
{
    std::vector<coords>* cha = iter; // doesn't work.
}

// does work.
std::vector<coords>* character = &characters.at(0);
coords* first = &character->at(0);

And I don't get why. 我不明白为什么。 Isn't iter supposed to be a pointer to an element of the type that it's container is supposed to 'contain'? Iter是否应该是指向容器应该包含的类型的元素的指针?

Anyone willing to shed light on this? 有人愿意对此进行阐明吗?

By doesn't work I mean: 通过不起作用,我的意思是:

error C2440: 'initializing' : cannot convert from 'std::_Vector_iterator<_Ty,_Alloc>' to 'std::vector<_Ty> *'

Which doesn't make a whole lot of sense to me. 这对我来说毫无意义。

An iterator is a type that can be dereferenced like a pointer, ie, it has an explicit operator*() and operator->() . 迭代器是一种可以像指针一样被取消引用的类型,即,它具有显式的operator*()operator->() It doesn't have to be a pointer. 它不必是指针。

So use &*iter if you want to get the address of the vector. 因此&*iter如果要获取向量的地址,请使用&*iter

To clarify further on MSN's answer, you can think of the iterator as a wrapper to an individual item of the container, but it also has some smarts for incrementing (++iter), decrementing (++iter) etc. Remember, the underlying data structure may not be a contiguous block of memory depending on the container type / implementation. 为了进一步阐明MSN的答案,您可以将迭代器视为容器中单个项目的包装器,但是它还具有一些用于递增(++ iter),递减(++ iter)等的技巧。取决于容器的类型/实现,数据结构可能不是连续的内存块。 To access the actual value, you can 要访问实际值,您可以

1) derefence the iterator, eg 1)取消引用迭代器,例如

Type t = *iter;

2) treat the iterator as a pointer to the container type, eg 2)将迭代器视为指向容器类型的指针,例如

iter->someFuncOnTheContainerType();

I know it's obvious now (in hindsight), but in your for loop you could also try: 我知道这很明显(事后看来),但是在您的for循环中,您也可以尝试:

std::vector<coords> & cha = * iter;

Also, not what you are asking for, and just FYI, but vectors support random access iterators. 同样,不是您要的,而是FYI,但是向量支持随机访问迭代器。 Meaning you could also write: 意思是你也可以写:

for( size_t i=0; i<characters.size();  i ++ )

And, if you needed to convert back to an iterator, you could use: 而且,如果您需要转换回迭代器,则可以使用:

characters.begin() + i

It's not the C++ way of doing things, it breaks the generic iterator philosophy, but it has its uses. 它不是C ++的处理方式,它打破了通用的迭代器原理,但是有其用途。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM