vector: Foo[5] == ((foo*)Foo) + 5 ?

R

.rhavin grobert

assume the following:
______________________
std::vector<foo> m_vFoo; // we assume foo has more than four
elements!

foo* FifthElement(foo* pFooZero)
// we call +0 the zeroth element!
{
return pFooZero + 5;
};
______________________

is &m_vFoo[5] the same as FifthElement(m_vFoo) ? Allways?
 
R

.rhavin grobert

Don't you mean either SixthElement, or an index of 4? Remember, in C++, 0
is the FIRST element.

little typo.

1 is the FIRST element!
0 is the ZEROTH element!

but that's esotheric....
 
E

Erik Wikström

assume the following:
______________________
std::vector<foo> m_vFoo; // we assume foo has more than four
elements!

foo* FifthElement(foo* pFooZero)
// we call +0 the zeroth element!
{
return pFooZero + 5;
};
______________________

is &m_vFoo[5] the same as FifthElement(m_vFoo) ? Allways?

If I understand you correctly what you are asking is if the address of
the vector is also the address of its first element, and since the
vectors elements are stored in contiguous memory if the address of the
vector + sizeof(foo) * 5 is also the address of the sixth (element with
index 5) element.

The answer is with hight probability no, the vector contains a pointer
to the first element which will be located elsewhere.
 
A

Andrey Tarasevich

..rhavin grobert said:
assume the following:
______________________
std::vector<foo> m_vFoo; // we assume foo has more than four
elements!

foo* FifthElement(foo* pFooZero)
// we call +0 the zeroth element!
{
return pFooZero + 5;
};
______________________

is &m_vFoo[5] the same as FifthElement(m_vFoo) ? Allways?

Never. You question makes no sense since neither

FifthElement(m_vFoo)

nor

(foo*)Foo

is a valid expression in C++ for 'm_vFoo'/'Foo' of type 'std::vector<foo>'.

Clarify your question.
 
J

JaredGrubb

assume the following:
______________________
std::vector<foo> m_vFoo;  // we assume foo has more than four
elements!

foo* FifthElement(foo* pFooZero)
// we call +0 the zeroth element!
{
  return pFooZero + 5;};

______________________

is &m_vFoo[5] the same as FifthElement(m_vFoo) ? Allways?

Not exactly. m_vFoo is not convertible to foo*, so your code wont
compile. However, the following does work and is true:

&m_vFoo[5] == FifthElement(&*m_vFoo.begin())

This is actually used in a container benchmark written by Alexander
Stepanov to test whether a compiler adds any overhead to iterators,
when in theory a vector iterator should be a thin wrapper for a foo*.
(http://www.stepanovpapers.com/container_benchmark.cpp)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,830
Latest member
ZADIva7383

Latest Threads

Top