473,385 Members | 1,536 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,385 software developers and data experts.

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(sizeof(struct test));
struct test *t = (struct test *)varray_get(tests, 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 8667
"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 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(sizeof(struct test));
struct test *t = (struct test *)varray_get(tests, 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.begin(),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>list
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(sizeof(struct test));
> struct test *t = (struct test *)varray_get(tests, 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.begin(),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>list
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.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?

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.CIS.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*********@xmission.dot.com> wrote in message
news:86************@Zorthluthik.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*********@xmission.dot.com> wrote in message
news:86************@Zorthluthik.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.CIS.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(tests, 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.CIS.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(tests, 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
On Mon, 8 Sep 2003 16:22:48 -0700, "Michael B. Allen"
<mb*****@ioplex.com> wrote:

"Alf P. Steinbach" <al***@start.no> wrote in message
news:3f****************@News.CIS.DFN.DE...
>The benifit of the C version was that one memory allocation mightaccomodate >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;


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


operator[] is overloaded to return a reference (like a pointer) to a
member of the vector. No copying occurs - f above is just an alias for
the index'th member of foos.
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(tests, 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?


In this case you'd make str a std::string or vector<char> (to avoid
the memory management), but you'd stick with args being char*'s.
std::string (and CString) controls its own memory - there is no way to
get a CString to reference part of another string (although such a
class might be useful).

If this code isn't called in an inner loop, then having a separate
std::string for each arg would be the way to go. This will be fast
enough unless dealing with very large CSV files.

This may be of interest:
http://www.sgi.com/tech/stl/string_discussion.html

Tom
Jul 19 '05 #11
Stroustrup (section 20.3.13) presents template Basic_substring which
does roughly that.

tom_usenet wrote:
std::string (and CString) controls its own memory - there is no way to
get a CString to reference part of another string (although such a
class might be useful).


Jul 19 '05 #12

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

Similar topics

6
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...
1
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...
1
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...
8
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...
19
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...
1
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
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: ...
2
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...
35
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...
4
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...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.