473,325 Members | 2,872 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,325 software developers and data experts.

A question about vectors and pointers

Hi ..

A basic template and pointer question for you.

I have a set of classes that look like (simplified):

class Foo {
public:
Foo *next;
Foo *other;
int n;

friend class FooList;
};

class FooList {
vector<Foo> foos;
void add(); // add a foo to the list
};

void FooList::add() {
Foo f = new Foo();
f->n = foos.size();

Foo *fp = foos.end(); // get the last added foo to link the pointers
if (fp != (Foo*)NULL)
fp->next = &f;
foos.push_back(f);
}

My problem is that the 'Foo *fp = foos.end();' is illegal.
How go I get the last item as it is stored?

Regards,

--
-mark. (probertm at acm dot org)
Jul 23 '05 #1
8 1238
Mark Probert wrote:
class Foo {
public:
Foo *next;
Foo *other;
int n;

friend class FooList;
};
All members of class Foo are public. Why do you need to make FooList a
friend ?
class FooList {
vector<Foo> foos;
void add(); // add a foo to the list
};
All members of class FooList are private. Is this really what you want ?
void FooList::add() {
Foo f = new Foo();
f->n = foos.size();

Foo *fp = foos.end(); // get the last added foo to link the pointers
if (fp != (Foo*)NULL)
fp->next = &f;
foos.push_back(f);
}

What are you trying to do here (please describe in words) ? If you really
want an iterator to the last member of foos, you can use "--foos.end()". Of
course, you have to make sure that foos.size() is non-zero.

Thanks,
--
CrayzeeWulf
Jul 23 '05 #2
Val
| If you really
| want an iterator to the last member of foos, you can use "--foos.end()". Of
| course, you have to make sure that foos.size() is non-zero.

Checking for non-zero is required indeed but not good enough. In general, I wouldn't use "--obj.end()" at all!
What if "vector<Foo>::iterator" is a Foo*? C++ won't allow you to modify temporary objects of built in types.

Check this out:
Foo* return_a_Foo() { //the code to do it }
myPointer = --return_a_Foo(); //Error?

However, if you are sure that "vector<Foo>::iterator" is a random access iterator then rewrite it like this:
"foos.end() -1 "
According to "Exceptional C++::Herb Sutter" you won't lose performance either.
Jul 23 '05 #3
On 2005-04-13, Val <va*****************@hotmail.com> wrote:

Check this out:
Foo* return_a_Foo() { //the code to do it }
myPointer = --return_a_Foo(); //Error?

However, if you are sure that "vector<Foo>::iterator" is a random access iterator then rewrite it like this:
"foos.end() -1 "
According to "Exceptional C++::Herb Sutter" you won't lose performance either.

Thanks, Val.

--
-mark. (probertm at acm dot org)
Jul 23 '05 #4
On 2005-04-13, CrayzeeWulf <cr*********@gnudom.org> wrote:
All members of class Foo are public. Why do you need to make FooList a
friend ?


My apologies. The classes are a very simplified version of the real classes.
The members are private and there are other members and member functions.
What are you trying to do here (please describe in words) ? If you really
want an iterator to the last member of foos, you can use "--foos.end()". Of
course, you have to make sure that foos.size() is non-zero.


Thanks for that.

Regards,

--
-mark. (probertm at acm dot org)
Jul 23 '05 #5
> void FooList::add() {
Foo f = new Foo();
f->n = foos.size();

Foo *fp = foos.end(); // get the last added foo to link the pointers
Undefined here.
You are assuming that an iterator can be converted to a pointer to Foo (or
is a pointer) and on some implementions that is not true. foos.end() returns
_just_ an iterator.
if (fp != (Foo*)NULL)
fp->next = &f;
And suppose that vector iterators are pointers in this implementation.
This is more undefined behaviour in that foos.end() is never supposed to be
dereferenced, yet you are setting fp->next, a big no-no.
foos.push_back(f);
}
My problem is that the 'Foo *fp = foos.end();' is illegal.
How go I get the last item as it is stored?
Foo *fp = &foos.back();

will do it. back() returns a reference to the last item stored in the vector
(assuming it is not empty). end() is always invalid and should never be
dereferenced for any container. begin() is always valid if the container is
not empty.

Stephen Howe

Regards,

--
-mark. (probertm at acm dot org)

Jul 23 '05 #6

"Mark Probert" <pr******@gmail.com> wrote in message
news:QZZ6e.986608$8l.977913@pd7tw1no...
Hi ..

A basic template and pointer question for you.

I have a set of classes that look like (simplified):

class Foo {
public:
Foo *next;
Foo *other;
int n;

friend class FooList;
};

class FooList {
vector<Foo> foos;
Your later usage implies that you meant:

std::vecotr<Foo*> foos.
void add(); // add a foo to the list
};

void FooList::add() {
Foo f = new Foo();
f->n = foos.size();

Foo *fp = foos.end(); // get the last added foo to link the pointers
You get a reference to the last item using

Foo* fp = foos.back();
if (fp != (Foo*)NULL)
fp->next = &f;
foos.push_back(f);
}

My problem is that the 'Foo *fp = foos.end();' is illegal.
How go I get the last item as it is stored?


While my intuition says that there may be better approaches to accomplishing
your final goal, the following will do what you were explicitly asking for.

class Foo
{
Foo* next;
Foo* other;
int n;
public:

Foo():next(0),other(0),n(0){}

Foo( std::vector<Foo*>& foos );

void AttachNext( Foo* aNext ){ next = aNext; }

...
};

class FooList
{
std::vector<Foo*> foos;

public:
void add(){ foos.push_back( new Foo( foos ) ); }
};

Foo::Foo( std::vector<Foo*>& foos ):next(0),other(0),n(foos.size())
{
if( !foos.empty() ) foos.back().AttachNext( this );
}

Jeff Flinn
Jul 23 '05 #7
"Mark Probert" <pr******@gmail.com> wrote in message
news:QZZ6e.986608$8l.977913@pd7tw1no...
My problem is that the 'Foo *fp = foos.end();' is illegal.
How go I get the last item as it is stored?


That's not your only problem if you think it's meaningful to store the
address of a Foo that's an element of a vector.

Each time you execute push_back on the vector, the call might cause the
vector to reallocate. If it does, then every element of the vector will be
moved to another location in memory, and all pointers to elements of the
vector will become meaningless.

So if what you're trying to do is have a vector of objects that refer to
each other somehow, I can see three plausible choices:

1) Store vector indices rather than pointers.
2) Preallocate enough memory for the vector (using the "reserve" member
function) that it never reallocates.
3) Use a different container such as deque, which doesn't move its
elements around in memory.
Jul 23 '05 #8
On 2005-04-13, Andrew Koenig <ar*@acm.org> wrote:
"Mark Probert" <pr******@gmail.com> wrote in message
news:QZZ6e.986608$8l.977913@pd7tw1no...
My problem is that the 'Foo *fp = foos.end();' is illegal.
How go I get the last item as it is stored?


That's not your only problem if you think it's meaningful to store the
address of a Foo that's an element of a vector.

Many thanks, Andrew. I was not aware of that.
Deque it is ...

--
-mark. (probertm at acm dot org)
Jul 23 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: J. Campbell | last post by:
I have a class that contains an array of integers that hold the state of my 'system'. The system must be updated periodically. I need to update the whole system at once, at which point the system...
5
by: Simon Elliott | last post by:
I'd like to do something along these lines: struct foo { int i1_; int i2_; }; struct bar {
3
by: Amit | last post by:
Hello. I am having some problem organizing a set of vectors. The vectors itself, could contain a pointer( say integer pointer) or could contain another object MyClass. 1>So, first of all, is...
4
by: Dr. J.K. Becker | last post by:
Hi all, I have vectors that holds pointers to other vectors, like so: vector<whatever> x; vector<whatever*> z; z=&x; Now I add something to x
6
by: Adam Hartshorne | last post by:
Hi All, I have the following setup. Two 'std::vector's which i iterate through in a for (iterate through vector1 of types X) { for (iterate through vector2 of types Y) { f(x) }
4
by: mp | last post by:
I am doing pairwise comparisons between 2 vectors of chars and permuting one vector and storing the resulting calculations in a vector<float> then I find a p-value among other stats. I have to do...
9
by: kathy | last post by:
I am using std::vector in my program: func() { std::vector <CMyClass *> vpMyClass; vpMyClass.push_back(new CMyClass()); vpMyClass.push_back(new CMyClass()); vpMyClass.push_back(new...
1
nabh4u
by: nabh4u | last post by:
Hi, I have a problem referencing to Vectors using pointers i.e. I am not able to use "call by reference" on vector variables. I have a "read()" function in "x.cpp" and "main()" in "y.cpp". I...
5
by: Jim | last post by:
Hi, Just wondering which is better vector<record *r; r.push_back(new record(x,y)); or vector<recordr; r.push_back(record(x,y));
160
by: raphfrk | last post by:
Is this valid? int a; void *b; b = (void *)a; // b points to a b += 5*sizeof(*a); // b points to a a = 100;
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.