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

P

Peter Olcott

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);
}
 
R

Ron Natalie

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.
 
D

dasjotre

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.
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top