473,799 Members | 3,832 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Pointer to container in STL

I would like to know how to get the address of a container of the STL
without using iterators. I have a class with three STL lists and a
index which points to an element of any ot the other lists, but i don't
know how to access these elements addresses.
Just as an example:
class C {
public:
int a;
}

int main() {
C obj;
obj.a=2;
list<C> letter;
letter.push_bac k(obj);
list<C>::iterat or it = letter.begin();
// How do i know where 'it' is pointing
}

Thanks in advance, Daniel Marques

Jun 28 '06 #1
4 4037

Daniel Marques wrote:
I would like to know how to get the address of a container of the STL
without using iterators. I have a class with three STL lists and a
index which points to an element of any ot the other lists, but i don't
know how to access these elements addresses.
Just as an example:
class C {
public:
int a;
}

int main() {
C obj;
obj.a=2;
list<C> letter;
letter.push_bac k(obj);
list<C>::iterat or it = letter.begin();
// How do i know where 'it' is pointing
}


C* ptr = &(*it);

Best regards,

Tom

Jun 28 '06 #2
Daniel Marques wrote:
I would like to know how to get the address of a container of the STL
without using iterators. I have a class with three STL lists and a
index which points to an element of any ot the other lists, but i don't
know how to access these elements addresses.
Just as an example:
class C {
public:
int a;
}

int main() {
C obj;
obj.a=2;
list<C> letter;
letter.push_bac k(obj);
list<C>::iterat or it = letter.begin();
// How do i know where 'it' is pointing
}


Im not sure if this is a preferable way but I whould use here:

C* c_ptr = &(*it);

Yes this looks very strange, but it should give what you want: The
physical* address of the element.

HTH,
Henning

*) Well I know in fact it is not the real physical adress but the linear
or logical one or whatever.
"Physical" here just should denote that what you get is not an
STL-iterator but a primitive pointer.
Jun 28 '06 #3

"Daniel Marques" <da***********@ gmail.com> wrote:
I would like to know how to get the address of a container of the STL
without using iterators.
This "question" contains a false two false pre-assumptions:
1. That iterators are pointers (they're not; they're classes)
2. That iterators point to containers (they don't; they point
to elements IN containers)
I have a class with three STL lists and a index which points
to an element of any ot the other lists, but i don't
know how to access these elements addresses.
Don't do that!

STL containers do their own memory management. A pointer to
an element in such a container tends to get "stale" real fast.
You can get a pointer to an element of a container easy:

std::vector<int > Bark;
Bark.push_back( 42);
Bark.push_back( 18);
Bark.push_back( 87);
int* Fred = &(Bark[1]);

But will it still point to the same element when you get around
to using it, later? Maybe, or maybe not. The element may
have been erased! Or the container may have re-allocated
itself and moved! You may be now dereferencing a pointer
to God knows what. That often causes hard-to-debug sporadic
runtime errors. The kind of bugs that can stay with a
software project throughout its lifetime because no one
could figure out what was going wrong.

Instead, use iterators and algorithms. That's what they're
for: accessing elements in STL containers.
Just as an example:
class C {
public:
int a;
}

int main() {
C obj;
obj.a=2;
list<C> letter;
letter.push_bac k(obj);
list<C>::iterat or it = letter.begin();
// How do i know where 'it' is pointing
}


You don't need to know where "it" is pointing. Don't try to store
the location of the beginning of an STL container. Instead, wait
until you need to USE that location, then call begin() at that time.
That way, you'll NEVER have to worry about whether your pointer is
valid or stale.

Just because C++ ALLOWS you to take addresses of things doesn't mean
you necessarily should. That's very dangerous. So much so that many
languages (eg, Perl, Java, etc.) have outlawed that. Pointers are evil.
Don't use them except in those cases where they're a _necessary_ evil.
(Eg, when doing polymorphism; or when passing a function pointer as
an argument to a function.)

Some day you may end up like me, maintaining a bunch of legacy code
(perhaps your own). If that code contains pointers used with wild
abandon, you'll hate yourself for having written it. I guarantee it.
So don't do that.

Instead, use iterators. The usual way to riffle through a std::list
is like this:

std::list<MyTyp e> Blat;
// ... load stuff into Blat here ...
std::list<MyTyp e>::iterator Iter;
for (Iter = Blat.begin(); Iter != Blat.end(); ++Iter)
{
// do stuff with (*Iter)
}

Another way is by using std::for_each, like so:

std::for_each(B lat.begin(), Blat.end(), MyFunction);

where MyFunction is a function or functor with one argument, of the
same type as the content-type of Blat; it will be applied for each
element of Blat.

Or use other algorithms, such as sort, find, replace, merge, etc.

Consult a book on STL for more info:

The whole nine yards: Josuttis: "The C++ Standard Library"
Short 'n' Sweet: O'Reilly's STL pocket reference.
--
Cheers,
Robbie Hatley
Tustin, CA, USA
lone wolf intj at pac bell dot net
home dot pac bell dot net slant earnur slant
Jun 28 '06 #4
Henning Hasemann wrote:
Daniel Marques wrote:
I would like to know how to get the address of a container of the STL
without using iterators. I have a class with three STL lists and a
index which points to an element of any ot the other lists, but i don't
know how to access these elements addresses.
Just as an example:
class C {
public:
int a;
}

int main() {
C obj;
obj.a=2;
list<C> letter;
letter.push_bac k(obj);
list<C>::iterat or it = letter.begin();
// How do i know where 'it' is pointing
}


Im not sure if this is a preferable way but I whould use here:

C* c_ptr = &(*it);

Yes this looks very strange, but it should give what you want: The
physical* address of the element.

HTH,
Henning

*) Well I know in fact it is not the real physical adress but the linear
or logical one or whatever.
"Physical" here just should denote that what you get is not an
STL-iterator but a primitive pointer.


Assuming C hasn't overridden operator&, of course.
Jun 28 '06 #5

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

Similar topics

11
3045
by: Vivi Orunitia | last post by:
Hi all, I tried looking this up in the sgi docs but it didn't provide any concrete answer to what I'm looking for. Basically, is there any difference between using ::iterator for a container vs using ::pointer? I did a quick experiment and replaced all the ::iterator in my code with ::pointer and it seems to work the same. What I'm think is on the surface they're the same but perhaps there're some subtle differences beneath the...
3
1369
by: jjleto | last post by:
I have just learn about "pointer to member". Does someone have an actual example where "pointers to member" are usefull or necessary ? Can't always &(myClass.member) be used ? Thank you.
16
2711
by: forester | last post by:
lets say its common situation when object have subobjects in container and receives callbacks from contained items. and object want to move objects in containers on signal(callback). iterator is needed for container modifications, item cannot know its iterator, at least its not easy to do so and i think cannot be done type-safe avoiding virtual functions and stuff. 'this' pointer from items is a freeby :>. the problem is, std...
18
2570
by: silversurfer | last post by:
Ok, this should be fairly easy for most of you (at least I hope so), but not for me: Let us say we have got the following elements: std::vector<Entry> models; //Entry is a struct std::vector<Entry>::iterator modelIterator; In a method, I am currently writing, I need to get a pointer to an entry in the vector.. I thought of the following:
19
1652
by: Michael | last post by:
Hi, typedef std::vector<Vehicle* VehicleList; Vehicle is a UDT, or a class. Why is Vehicle* not just Vehicle in < >. Which one is better and why? If you could explain it by laying out some codes, it would be highly appreciated! Thanks in advance, Michael
2
35631
weaknessforcats
by: weaknessforcats | last post by:
Handle Classes Handle classes, also called Envelope or Cheshire Cat classes, are part of the Bridge design pattern. The objective of the Bridge pattern is to separate the abstraction from the implementation so the two can vary independently. Handle classes usually contain a pointer to the object implementation. The Handle object is used rather than the implemented object. This leaves the implemented object free to change without affecting...
18
1822
by: Goran | last post by:
Hi @ all! Again one small question due to my shakiness of what to use... What is better / smarter? private: vector<MyClass_t* itsVector; OR...
2
2939
by: domehead100 | last post by:
I have a templated class, CDerived: template <typename TValue, typename TDraw, typename TEdit ...> class CDerived : public CBase { TValue m_Value public: TValue& GetValue() const {
8
1863
by: mathieu | last post by:
Hi there I have implemented a very simple smartpointer class (invasive design). And I was wondering what should be the natural API when using those in a Container. I choose to define the following operator in my smartpointer class: .... operator ObjectType * () const
0
9687
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10257
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10237
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9077
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6808
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5467
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4144
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3761
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2941
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.