Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C++ (http://www.velocityreviews.com/forums/f39-c.html)
-   -   Retrieving the prior to the last element of a std::vector of struct ??? (http://www.velocityreviews.com/forums/t501623-retrieving-the-prior-to-the-last-element-of-a-std-vector-of-struct.html)

Peter Olcott 04-15-2007 04:33 PM

Retrieving the prior to the last element of a std::vector of struct ???
 
What is the correct syntax for the last line???

#include <vector>
#include <stdio.h>

struct TestType {
double ONE;
double TWO;
};

void main()
{
TestType Record;
std::vector<TestType> Test;

for (double N = 111.0; N <= 122.0; N++) {
Test.push_back(Record);
Test.back().ONE = N;
Test.back().TWO = N / 3.0;
}
for (int M = 0; M < Test.size(); M++)
printf("Test[%02d].ONE--->%6.2f
Test[%02d].TWO--->%6.2f\n",
M, Test[M].ONE, M, Test[M].TWO);

printf("Test.back().ONE--->%6.2f
Test.back().TWO--->%6.2f \n",
Test.back().ONE, Test.back().TWO);

// printf("Test.back().ONE--->%6.2f\n",
(Test.back() -1).ONE);
}



Daniel T. 04-15-2007 04:57 PM

Re: Retrieving the prior to the last element of a std::vector of struct ???
 
"Peter Olcott" <NoSpam@SeeScreen.com> wrote:

> What is the correct syntax for the last line???


> // printf("Test.back().ONE--->%6.2f\n", (Test.back() -1).ONE);


printf("Test.back().ONE--->%6.2f\n", (Test.end() - 2)->ONE);

Ron Natalie 04-15-2007 06:22 PM

Re: Retrieving the prior to the last element of a std::vector ofstruct ???
 

>
> void main()

int main()


>
> // printf("Test.back().ONE--->%6.2f\n",
> (Test.back() -1).ONE);
> }
>
>


back() returns a reference to last object, you can't
do -1 to it (you're substracting from an the object
stored in the last position).

back() is equivelent to *(--end())
your second item should be
*(Test.end() -2)
This will work on any container that has random
access iterators (like vector)... alternatively
you can do
*(--(--end()))
which will work on bidirectional iterators (like list).


Of course you need to assure that there are at least
two objects exist in the container obviously.

dasjotre 04-16-2007 10:18 AM

Re: Retrieving the prior to the last element of a std::vector of struct ???
 
On 15 Apr, 19:22, Ron Natalie <r...@spamcop.net> wrote:
>
> back() is equivelent to *(--end())
> your second item should be
> *(Test.end() -2)
> This will work on any container that has random
> access iterators (like vector)... alternatively
> you can do
> *(--(--end()))
> which will work on bidirectional iterators (like list).


Also, *(rbegin()+1) where iterators are random
access, or *(++rbegin()) where they are not.

> Of course you need to assure that there are at least
> two objects exist in the container obviously.





All times are GMT. The time now is 12:43 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.