473,910 Members | 4,221 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Array List?

Coming from C and Java on *nix I'm a little out of my element messing around
with CList and MSVC++ but I think my issues are largely syntactic.

I have an ADT that I use called a 'varray' that can return a pointer to an
arbirary sized element in an array given an index and it will allocate the
memory to back it if necessary:

struct varray *tests = varray_new(size of(struct test));
struct test *t = (struct test *)varray_get(te sts, 50));

The point being I don't have to allocate the memory for *t. Each element in
the backing array is sizeof(struct test).

Is there an equivalent ADT in C++ that I should use?

Thanks,
Mike

ref: http://www.ioplex.com/~miallen/libmba/dl/src/varray.c
Jul 19 '05 #1
11 8711
"Alf P. Steinbach" <al***@start.no > wrote in message
news:3f******** ********@News.C IS.DFN.DE...
I have an ADT that I use called a 'varray' that can return a pointer to anarbirary sized element in an array given an index and it will allocate thememory to back it if necessary:

struct varray *tests = varray_new(size of(struct test));
struct test *t = (struct test *)varray_get(te sts, 50));

The point being I don't have to allocate the memory for *t. Each element inthe backing array is sizeof(struct test).

Is there an equivalent ADT in C++ that I should use?


Check out the standard containers, std::vector, std::list and so on.


You mean like this? Is this legit?

#include <iostream>
#include <list>
using namespace std;

struct foo {
int i;
short s;
};

main()
{
list<struct foo> L;
struct foo f;

f.i = 10;
f.s = 5;
L.push_back(f);
f.i = 30;
f.s = 15;
L.push_front(f) ;
f.i = 100;
f.s = 50;
L.insert(++L.be gin(),f);
f.i = 101;
f.s = 51;
L.push_back(f);
f.i = 102;
f.s = 52;
L.push_back(f);

list<struct foo>::iterator i;

for(i=L.begin() ; i != L.end(); ++i) cout << "i=" << i->i << ",s=" << i->s
<< " ";
cout << endl;
return 0;
}

c:\miallen\p>li st
i=30,s=15 i=100,s=50 i=10,s=5 i=101,s=51 i=102,s=52
Jul 19 '05 #2
On Mon, 8 Sep 2003 14:10:16 -0700, "Michael B. Allen" <mb*****@ioplex .com> wrote:
"Alf P. Steinbach" <al***@start.no > wrote in message
news:3f******* *********@News. CIS.DFN.DE...
>I have an ADT that I use called a 'varray' that can return a pointer toan >arbirary sized element in an array given an index and it will allocatethe >memory to back it if necessary:
>
> struct varray *tests = varray_new(size of(struct test));
> struct test *t = (struct test *)varray_get(te sts, 50));
>
>The point being I don't have to allocate the memory for *t. Each elementin >the backing array is sizeof(struct test).
>
>Is there an equivalent ADT in C++ that I should use?
Check out the standard containers, std::vector, std::list and so on.


You mean like this?


Good. I'll comment only on opportunities for improvement.

Is this legit?
Yep.
#include <iostream>
#include <list>
using namespace std;
Prevents you from using names like 'list' for your own purposes.
struct foo {
int i;
short s;
};
A constructor can ease things considerably, avoiding e.g. dummy
variables like 'f' below, as well as the assignments.

main()
'main' must have return type 'int'.

See [http://www.research.att.com/~bs/bs_faq2.html#void-main].
{
list<struct foo> L;
No need to repeat the word 'struct' (in contrast to C, in C++ a
'struct' is a type like any others).

Avoiding all uppercase names can help avoid name conflicts with
macros.

struct foo f;

f.i = 10;
f.s = 5;
L.push_back(f);
f.i = 30;
f.s = 15;
L.push_front(f) ;
f.i = 100;
f.s = 50;
L.insert(++L.be gin(),f);
f.i = 101;
f.s = 51;
L.push_back(f);
f.i = 102;
f.s = 52;
L.push_back(f);

list<struct foo>::iterator i;

for(i=L.begin() ; i != L.end(); ++i) cout << "i=" << i->i << ",s=" << i->s
<< " ";
cout << endl;
return 0;
}

Consider
#include <iostream>
#include <list>

struct Foo
{
int i;
short s;

Foo( int iValue, short sValue ): i( iValue ), s( sValue ) {}
};

int main()
{
std::list<Foo> list;

list.push_back( Foo( 10, 5 ) );
list.push_front ( Foo( 30, 15 ) );
list.insert( ++list.begin(), Foo( 100, 50 ) );
list.push_back( Foo( 101, 51 ) );
list.push_back( Foo( 102, 52 ) );

std::list<Foo>: :iterator i;

for( i = list.begin(); i != list.end(); ++i )
{
std::cout << "i=" << i->i << ",s=" << i->s << " " << std::endl;
}
}

c:\miallen\p>l ist
i=30,s=15 i=100,s=50 i=10,s=5 i=101,s=51 i=102,s=52


Jul 19 '05 #3

"Alf P. Steinbach" <al***@start.no > wrote in message
news:3f******** ********@News.C IS.DFN.DE...
#include <iostream>
#include <list>

struct Foo
{
int i;
short s;

Foo( int iValue, short sValue ): i( iValue ), s( sValue ) {}
};

int main()
{
std::list<Foo> list;

list.push_back( Foo( 10, 5 ) );

"
Interesting. Is that a constructor? Is there a relationship between this and
the constructor of a class? Does this degenerate into a class or is this
just some extra notation specific to structures?

In practice do folks just end up using classes over structs entirely? Or is
there an advantage to using a struct like this? One of the things that
bothered me about C++ that you cannot not be certain what was in memory
(e.g. you cannot serialize, inspect, or partially copy the memory occupied
by a class for fear of breaking it). Explicit memory manipluation is what
makes C great (yes, and dangerous).

Thanks,
Mike
Jul 19 '05 #4
"Michael B. Allen" <mb*****@ioplex .com> writes:
"Alf P. Steinbach" <al***@start.no > wrote in message
news:3f******** ********@News.C IS.DFN.DE...
#include <iostream>
#include <list>

struct Foo
A struct is a class whose members and bases are public by default (as
opposed to private). There is no other difference between struct and
class. structs may have constructors, destructors, copy-assignment
operators, virtual functions, base classes, virtual base classes,
etc, all with the same semantics as classes do.
{
int i;
short s;

Foo( int iValue, short sValue ): i( iValue ), s( sValue )
{}
This is a constructor.
};

int main()
{
std::list<Foo> list;

list.push_back( Foo( 10, 5 ) ); "
Interesting. Is that a constructor?


Yes.
Is there a relationship between this and
the constructor of a class?
It fills the same role. The standard refers to both structs and
classes as 'class types'

[snip] In practice do folks just end up using classes over structs entirely? Or is
there an advantage to using a struct like this?
Yes. It is common to place public interface before private
members. Since struct access is public default, it suits this
style naturally.
One of the things that
bothered me about C++ that you cannot not be certain what was in memory
(e.g. you cannot serialize, inspect, or partially copy the memory occupied
by a class for fear of breaking it). Explicit memory manipluation is what
makes C great (yes, and dangerous).

[snip]

This is not true. C and C++ offer essentially the same guarantees in
this area.
Jul 19 '05 #5
On Mon, 8 Sep 2003 14:58:01 -0700, "Michael B. Allen" <mb*****@ioplex .com> wrote:

"Alf P. Steinbach" <al***@start.no > wrote in message
news:3f******* *********@News. CIS.DFN.DE...
#include <iostream>
#include <list>

struct Foo
{
int i;
short s;

Foo( int iValue, short sValue ): i( iValue ), s( sValue ) {}
};

int main()
{
std::list<Foo> list;

list.push_back( Foo( 10, 5 ) );"
Interesting. Is that a constructor? Is there a relationship between this and
the constructor of a class? Does this degenerate into a class or is this
just some extra notation specific to structures?


Here I'll just redirect you to the FAQ, your textbook, etc., but yes, yes, yes,
and no, and
In practice do folks just end up using classes over structs entirely? Or is
there an advantage to using a struct like this?
yes, and depends.

One of the things that
bothered me about C++ that you cannot not be certain what was in memory
(e.g. you cannot serialize, inspect, or partially copy the memory occupied
by a class for fear of breaking it).


You can do whatever you do in C, but C++ provides additional features where
you can't do whatever you do in C. Scribble on yellow note: intelligent
constraints yield power. Put note on computer monitor.

Jul 19 '05 #6

"llewelly" <ll*********@xm ission.dot.com> wrote in message
news:86******** ****@Zorthluthi k.local.bar...
One of the things that
bothered me about C++ that you cannot not be certain what was in memory
(e.g. you cannot serialize, inspect, or partially copy the memory occupied by a class for fear of breaking it). Explicit memory manipluation is what makes C great (yes, and dangerous).

[snip]

This is not true. C and C++ offer essentially the same guarantees in
this area.


Actually I just realized something that might illustrate my point. In my
original C example I basically had:

struct Foo *f = varray_get(foos , index);
f->i = 10;
f->s = 5;

The C++ alternative is:

list.push_back( Foo( 10, 5 ) );

The benifit of the C version was that one memory allocation might accomodate
many structs and nothing is copied. You are given a pointer to _the_ memory.
In the C++ version I don't think this is the case. Is push_back copying an
entire Foo? Also, is Foo( 10, 5 ) makeing another function call?

I don't mean to nit-pik (yet). I'm just trying to understand what's
happening under the hood.

Mike
Jul 19 '05 #7
On Mon, 8 Sep 2003 15:27:01 -0700, "Michael B. Allen" <mb*****@ioplex .com> wrote:

"llewelly" <ll*********@xm ission.dot.com> wrote in message
news:86******* *****@Zorthluth ik.local.bar...
> One of the things that
> bothered me about C++ that you cannot not be certain what was in memory
> (e.g. you cannot serialize, inspect, or partially copy the memoryoccupied > by a class for fear of breaking it). Explicit memory manipluation iswhat > makes C great (yes, and dangerous). [snip]

This is not true. C and C++ offer essentially the same guarantees in
this area.


Actually I just realized something that might illustrate my point. In my
original C example I basically had:

struct Foo *f = varray_get(foos , index);
f->i = 10;
f->s = 5;

The C++ alternative is:

Two errors in that sentence. (1) You can do the same in C++, and at
different levels of abstraction, including the raw C level. (2) There
are more than one way to obtain the high-level functionality, including
but not limited to per-structure allocation.
list.push_back( Foo( 10, 5 ) );

The benifit of the C version was that one memory allocation might accomodate
many structs and nothing is copied. You are given a pointer to _the_ memory.
Consider
std::vector<Foo > foos( cacheSize );
Foo& f = foos[index];

f.i = 10;
f.s = 5;
In the C++ version I don't think this is the case. Is push_back copying an
entire Foo? Also, is Foo( 10, 5 ) makeing another function call?


It can be, yes in this example, quality of implementation.

Jul 19 '05 #8

"Alf P. Steinbach" <al***@start.no > wrote in message
news:3f******** ********@News.C IS.DFN.DE...
The benifit of the C version was that one memory allocation might accomodatemany structs and nothing is copied. You are given a pointer to _the_
memory.
Consider
std::vector<Foo > foos( cacheSize );
Foo& f = foos[index];

f.i = 10;
f.s = 5;


So the [] operator is overloaded to allocate memory backing the memory at
that index? Or is the entire Foo still being copied?

Here's a similar problem I'm having (not really a problem but coming from
pure C I'd like to know how to do this sort of thing); I have a
csv_row_parse function that parses a Comma Separated Values (CSV) file and
populates a char *row[] array with pointers to each element in a CSV record.
Now I know that the pointers in this array all point to one continuous chunk
of memory and that the order of elements in that memory is preserved in the
array.

Here's the problem; I need a class with a CString *args[10] member that
corresponds to row elements 4 to 13 in the row. Because I know the pointers
of interest all appear together in memory I can just copy them by finding
the last valid element, finding the end of it, and then substracting a
pointer to the first element to get the chunk of memory that needs to be
copied:

struct test *t = varray_get(test s, index);

memset(t->args, 0, 10 * sizeof *str);
for(i = 4; i < 14 && row[i]; i++) { /* find the last args element */
str = row[i];
}
if (i > 4) {
/* calc the very end of the last args element */
size_t siz = ((str + str_length(str, rlim) + 1) - row[4]) * sizeof *str;
if ((str = (char *)malloc(siz)) == NULL) {
return -1;
}
/* allocate and copy */
memcpy(str, row[4], siz);
for(i = 4; i < 14 && row[i]; i++) {
/* recalculate pointers relative to the
* beginning of the new mem chunk */
t->args[i - 4] = str + (row[i] - row[4]);
}
}

Now all the args are in one string. Can I do this with CString?

Thanks,
Mike

ref: http://www.ioplex.com/~miallen/libmba/dl/src/csv.c
Jul 19 '05 #9


"Michael B. Allen" wrote:

"Alf P. Steinbach" <al***@start.no > wrote in message
news:3f******** ********@News.C IS.DFN.DE...
The benifit of the C version was that one memory allocation might accomodatemany structs and nothing is copied. You are given a pointer to _the_
memory.

Consider
std::vector<Foo > foos( cacheSize );
Foo& f = foos[index];

f.i = 10;
f.s = 5;


So the [] operator is overloaded to allocate memory backing the memory at
that index? Or is the entire Foo still being copied?


No. The element at that index has to exist already. Since the
vector is initialized with cacheSize elements, that many elements
are created by the constructor of the vector:

In the above, nothing gets copied in
Foo& f = foos[index];

f is a *reference* to the element in the vector. A reference
is another name for an already existing object.

Alf could have written as well:

std::vector<Foo > foos( cacheSize );
foos[index] = Foo( 10, 5 );

Why don't you do yourself a favour and buy a book about C++?
You will need it. You can't learn a language like C++ by studying
some examples out of context. C++ is much to powerfull for this,
even if you have C-knowledge.

Here's a similar problem I'm having (not really a problem but coming from
pure C I'd like to know how to do this sort of thing); I have a
csv_row_parse function that parses a Comma Separated Values (CSV) file and
populates a char *row[] array with pointers to each element in a CSV record.
Now I know that the pointers in this array all point to one continuous chunk
of memory and that the order of elements in that memory is preserved in the
array.

Here's the problem; I need a class with a CString *args[10] member that
corresponds to row elements 4 to 13 in the row. Because I know the pointers
of interest all appear together in memory I can just copy them by finding
the last valid element, finding the end of it, and then substracting a
pointer to the first element to get the chunk of memory that needs to be
copied:

struct test *t = varray_get(test s, index);

memset(t->args, 0, 10 * sizeof *str);
for(i = 4; i < 14 && row[i]; i++) { /* find the last args element */
str = row[i];
}
if (i > 4) {
/* calc the very end of the last args element */
size_t siz = ((str + str_length(str, rlim) + 1) - row[4]) * sizeof *str;
if ((str = (char *)malloc(siz)) == NULL) {
return -1;
}
/* allocate and copy */
memcpy(str, row[4], siz);
for(i = 4; i < 14 && row[i]; i++) {
/* recalculate pointers relative to the
* beginning of the new mem chunk */
t->args[i - 4] = str + (row[i] - row[4]);
}
}

Now all the args are in one string. Can I do this with CString?


The first thing you need to get rid of:
Drop your use of pointers. In C++ you do much less with them then you did in C.
Drop your way of thinking in memory locations and how you can use clever tricks
with pointer arithmetic to get at the information you want.

In C++ one would create

std::vector< std::string > Args

and fill in entire objects, instead of fidelling around with pointers and memory
allocation stuff. Stop your thinking of raw memory and how to squeeze out every
last nanosecond from the code. Work with objects: objects are resonsible for themselfs.
Objects *know* how to deal with the low level stuff. If you need a string, then
you have one: std::string or CString (if you are working with MFC). And that
std::string deals with the low level things, you just say:

mystring = "abcdef";

and the string class does the memory allocation under the hood.

You need an array of strings. Easy ...

std::vector< std::string > MyStrings;

.... is one. It does everything for you:

MyStrings.push_ back( "hello world" );
MyStrings.push_ back( "this is a" );
MyStrings.push_ back( "example" );

MyStrings[1] = "this is not an";

The string class handles all the details need for handling
one string and the vector class handles all the details needed
to have an array of strings which can grow dynamically.

I know it's hard. But the change from C to C++ is not just
only different syntax. If you want to go OO, then you also
need a different way of thinking.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 19 '05 #10

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

Similar topics

6
6335
by: Harry Overs | last post by:
My program needs to take a pointer to BYTE array (unsigned char*) and convert it into a STL list so that each BYTE in the array has its own element in the list, i.e. if the array has hundred bytes then the list needs to have a hundred entries, at present when I try to do this each element in my list points to the entire BYTE array, when what I really need is copies of each single BYTE in its own part of the list. I have used code similar...
1
2377
by: aemazing | last post by:
hello, im new to the forum and i wanted to help with my c++ program. the teacher wants us to design a progrm that would keep track of airplanes awaitin landing at an airport. the program will maintain a queue of flights numbers. the program will be abel to do the following: Add a new flight number to the end of the queue (got it done) LAnd the plane at the front of the queue - problems wit it- display the queue - got it done
1
2207
by: aemazing | last post by:
i've been tryin to do the following - -Add a new flight number to the end of the queue (got it done) -LAnd the plane at the front of the queue - problems wit it- -display the queue - got it done -seach for a specific flight number in queue ( didn't get there yet) -move a flight number one one position in the queue to another ( didn't get there yet) this is what i have so far. it runs but something is wrong and i don't know what it is.
8
3701
by: Peter B. Steiger | last post by:
The latest project in my ongoing quest to evolve my brain from Pascal to C is a simple word game that involves stringing together random lists of words. In the Pascal version the whole array was static; if the input file contained more than entries, tough. This time I want to do it right - use a dynamic array that increases in size with each word read from the file. A few test programs that make use of **List and realloc( List, blah...
19
3162
by: Tom Jastrzebski | last post by:
Hello, I was just testing VB.Net on Framework.Net 2.0 performance when I run into the this problem. This trivial code attached below executed hundreds, if not thousand times faster in VB 6.0 than in .Net environment, under VS 2005 Beta 2. Does anyone have any idea whether this will be addressed in the final release? Thanks, Tomasz
1
7131
by: cyrvb | last post by:
Hello, I'm a very very newbie in C# I did start 2 days ago, I get Visual Stuido 2005 C# I try to understand how to manage the arrays I did write this
10
3026
by: javuchi | last post by:
I just want to share some code with you, and have some comments and improvements if you want. This header file allocates and add and delete items of any kind of data from a very fast array: #include <stdlib.h> #ifndef __LIST_H__ #define __LIST_H__
2
2991
by: StevenChiasson | last post by:
For the record, not a student, just someone attempting to learn C++. Anyway, the problem I'm having right now is the member function detAddress, of object controller. This is more or less, your standard dynamic address book program. Adding, and listing work just fine. However, deleting, editing and viewing relies on member function retAddress. This function returns an array of pointers that are pointing to created objects. In action, all it...
35
5919
by: Lee Crabtree | last post by:
This seems inconsistent and more than a little bizarre. Array.Clear sets all elements of the array to their default values (0, null, whatever), whereas List<>.Clear removes all items from the list. That part makes a reasonable amount of sense, as you can't actually take items away from an Array. However, there doesn't seem to be a way to perform the same operation in one fell swoop on a List<>. For example:
4
2895
by: Bob Bedford | last post by:
Hello, I've an array of array(1,2,3,4). I'd like to retrieve the values in 3 and 4 giving the values 1 and 2. How can I do that, how to search in an array of array ? in short, how to write the findvalue function ? $list = array(); array_push($list,array(1,1,'x','x'); array_push($list,array(1,2,'x','y'); array_push($list,array(2,1,'y','x');
0
10037
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
11349
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10921
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...
0
9727
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...
1
8099
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7250
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
5939
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...
0
6142
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4776
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

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.