473,785 Members | 2,129 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to return an array of own datatype

Hello (and a happy new year)

I'm quite new to C++ and have to programm something for school and can't
get my head around
a couple of things, but at the moment this one is the most important for me:

I have defined a class String and before I go on I should mention that
I'm not allowed to use any pre-defined templates (no STL) and not the
standard C++ String class, kind of mean :)

Nevertheless I want to tokenize a String with a predefined delimiter,
which will be used later to
cut words out of a sentence.

String.cpp

String[] String::tokeniz e(const String s, char* delimiter)
{
String stringArray[];
// tokenize the String and put each word into the String array
...

return stringArray;
}
String.h

String[] tokenize(const String s, char* delimiters);
My first problem is that I get a bunch of errors for the header line
(the first is C3409, I'm using VC++ .NET),
I assume this is not the way how one should define an array return type?
I know I have a second problem too, because I have to define the size
of the array I want to return, but honestly I want to avoid that, I
would love to do that dynamicly
as in a Vector.

Jul 22 '05 #1
9 2375
On Sun, 02 Jan 2005 11:12:07 +0100 in comp.lang.c++, Steve
<s.*******@fh tw-berlin.de> wrote,
String[] tokenize(const String s, char* delimiters);


An array return type is not allowed.

You can return a struct that contains an array. Or you can let the
caller provide a pointer to an array argument that you fill with
your results. You can return a pointer to an array that you got
somewhere, but that means you have to pay more attention to where
the array is allocated.

Jul 22 '05 #2
David Harmon wrote:
On Sun, 02 Jan 2005 11:12:07 +0100 in comp.lang.c++, Steve
<s.*******@fh tw-berlin.de> wrote,
String[] tokenize(const String s, char* delimiters);

An array return type is not allowed.

Ohhh, ok didn't know that!
You can return a struct that contains an array. Or you can let the
caller provide a pointer to an array argument that you fill with
your results. You can return a pointer to an array that you got
somewhere, but that means you have to pay more attention to where
the array is allocated.


Thanks, I will give the struct idea a try.

cheers
Steve

Jul 22 '05 #3
"Steve" <s.*******@fh tw-berlin.de> wrote in message news:33******** *****@news.dfnc is.de...
David Harmon wrote:
On Sun, 02 Jan 2005 11:12:07 +0100 in comp.lang.c++, Steve
<s.*******@fh tw-berlin.de> wrote,
String[] tokenize(const String s, char* delimiters);

An array return type is not allowed.

Ohhh, ok didn't know that!

You can return a struct that contains an array. Or you can let the
caller provide a pointer to an array argument that you fill with
your results. You can return a pointer to an array that you got
somewhere, but that means you have to pay more attention to where
the array is allocated.


Thanks, I will give the struct idea a try.

Most time, return a struct is not a good idea. This cause a copy operation of
the members in the struct.
cheers
Steve

Jul 22 '05 #4


String.cpp

std::vector<Str ing> String[] String::tokeniz e(const String s, char* delimiter)
{
std::vector<Str ing> stringArray;
// tokenize the String and put each word into the String array
...

return stringArray;
}
OK?
But a little slow.

--

---http://snnn.blogone.ne t-----
Jul 22 '05 #5
"Mole Wang" <mo****@yahoo.c om.cn> writes:

Most time, return a struct is not a good idea. This cause a copy operation of
the members in the struct.

Or return a std::SmartPtr allocated by the function ?

Who should own it?
Who should allocate it?
Who should free it?

Pointers bring too trouble to it.

--
---------------snnn-------------
---http://snnn.blogone.ne t-----
Jul 22 '05 #6
"cyper" <cy***@163.com. haha.removeme> a écrit dans le message de news:
u1***********@1 63.com.haha.rem oveme...
"Mole Wang" <mo****@yahoo.c om.cn> writes:

Most time, return a struct is not a good idea. This cause a copy operation
of
the members in the struct.

Or return a std::SmartPtr allocated by the function ?

Who should own it?
Who should allocate it?
Who should free it?


Depending on the design, receiving a reference to an object for modification
can be more "efficient" than returning it. The thing is, modifying
parameters received by reference is usually dangerous, since it is not
always clear that the function will modify it. I prefer passing by address
when my functions modify their arguments.

void f(A &a);
void g(A *a);

int main()
{
A a;

f(a); // watch out, f() modifies a
g(&a); // that's clearer (imho)
}

Except for specific cases, I prefer returning by value since it is the
clearest way and users can safely ignore the modifications.
Jonathan
Jul 22 '05 #7

"cyper" <cy***@163.com. haha.removeme> wrote in message
news:u6******** ***@163.com.hah a.removeme...


String.cpp

std::vector<Str ing> String[] String::tokeniz e(const String s, char* delimiter) {
std::vector<Str ing> stringArray;
// tokenize the String and put each word into the String array
...

return stringArray;
}
OK?
But a little slow.


Did you try to compile that?

-Mike
Jul 22 '05 #8
Steve wrote:
Hello (and a happy new year)

I'm quite new to C++ and have to programm something for school and can't
get my head around
a couple of things, but at the moment this one is the most important for
me:

I have defined a class String and before I go on I should mention that
I'm not allowed to use any pre-defined templates (no STL) and not the
standard C++ String class, kind of mean :)

Nevertheless I want to tokenize a String with a predefined delimiter,
which will be used later to
cut words out of a sentence.

String.cpp

String[] String::tokeniz e(const String s, char* delimiter)

From a design perspective , the String argument to the function,
seems a little bit unconventional and confusing, since it is not
clear why this ought to be a member function since you are
passing a String and a delimiter as argument to the function.
(well, then you can as well have this method as static, which
may not be the best design though ).

Some suggestions:

1. You can have a method as follows.

vector<String> String::tokeniz e(const char * delimiter)
//Tokenize the String object's contents' here.
2. A better way would be to have a StringTokenizer class.
vector<String> StringTokenizer ::tokenize(cons t char * delimiter);
--
Karthik.
Jul 22 '05 #9
Steve wrote:
String[] String::tokeniz e(const String s, char* delimiter)
{
String stringArray[];
// tokenize the String and put each word into the String array
...

return stringArray;
}
The typical C++ approach to this is to have the function take an output
iterator which is written to in the function, i.e. something like this:

| template <typename OutIt>
| OutIt String::tokeniz e(char const* delimiters, OutIt to)
| {
| // ...
| *to++ = token;
| // ...
| return to;
| }

You could then use your 'tokenize()' function something like this:

| std::vector<Str ing> vec;
| String str(/*...*/);
| str.tokenize(", ", std::back_inser ter(vec));

.... or use whatever appropriate container type you wish instead of
'std::vector' as long as it supports a 'push_back()' operation. This
also
allows output e.g. to standard output using an appropriate iteartor:

| str.tokenize(', ', std::ostream_it erator<String>( std::cout, "\n"));

The trouble is somewhat that your teacher apparently does not
understand
how C++ works and deprived you from reasonable use of the standard
library
thereby either forcing you to reimplement fairly large portions thereof
or
using inferior programming techniques. If he wanted you to provide an
implementation of some particular algorithms without using the
corresponding
algorithms from the standard library he should have specified it that
way
rather.
String[] tokenize(const String s, char* delimiters);
This is illegal syntax. If it were possible to return an array from a
function, the syntax would rather be something like this:

| String (tokenize(Strin g const&s, char const* delimiters))[10];

A declaration like this should give an error message similar to the one
issued e.g. by SUN's compiler:

| Error: Functions cannot return arrays or functions.

However, please note two other important changes I applied to the
function
signature:
- The string is taken as reference argument: there is probably no need
to
copy the String, especially if you want it to be 'const' anyway.
- To allow passing of string literals to the functions, the second
parameter uses a pointer to 'char const' (i.e. an array of constant
'char's; 'char const' and 'const char' is equivalent but I consider
it
to be easier to read to place the 'const' as far to the right as
possible).
My first problem is that I get a bunch of errors for the header line
(the first is C3409, I'm using VC++ .NET),
I assume this is not the way how one should define an array return type?

Right. See above.
I know I have a second problem too, because I have to define the size
of the array I want to return, but honestly I want to avoid that, I
would love to do that dynamicly
as in a Vector.


To do so, you need to handle dynamic memory allocation - or,
preferably,
use one of the standard containers. Proper implementation of a
container
is actually non-trivial and involves loads of intrinsic little nits
which
are, IMO, far beyond a typical school assignment level. For example,
reasonable implementation of a 'std::vector' replacement involves
allocation
of uninitialized memory and placement construction/destruction of
elements.
No real rocket science but hardly what students need to be exposed to
learn
dealing with data structures either. Of course, some issues can be side
stepped by default constructing a bigger array and only considering a
subset
of the actual elements to be present in the vector...
--
<mailto:di***** ******@yahoo.co m> <http://www.dietmar-kuehl.de/>
<http://www.contendix.c om> - Software Development & Consulting

Jul 22 '05 #10

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

Similar topics

3
10693
by: Phil Powell | last post by:
if (is_array($_POST)) { foreach ($this->getAssocSectionsObjArray($key, $dbAP) as $obj) { print_r($obj); print_r(" in array? "); print_r(in_array($obj, $result)); print_r("<P>"); if (!in_array($obj, $result)) array_push($result, $obj); } }
1
2104
by: OlgaM | last post by:
Hello, i'm trying to initialize an array. The class List contains this in its private data members: ListNode<DATATYPE> *dataItems; In the constructor, i'm trying to allocate space for this array.
1
8374
by: Raptor | last post by:
Hi, I'm quite new to MySQL and quite impressed by its feature set. I've also been looking at Interbase and it has a feature that allows a multidimensional array to be stored in a single field. Does MySQL also have this feature? I was thinking about using MySQLs GIS data types but it only supports a two dimensional point, where as I need a three dimensional point to be stored. Each point represents a radar point. If anybody can...
11
2486
by: Magix | last post by:
Hi, what is wrong with following code ? typedef struct { word payLen; datatype data; } msg_type;
7
1808
by: nafri | last post by:
hello all, I want to create a function that returns the first element of the Array that is input to it. However, the Input Array can be an Array of points, double, or anyother type, which means the return type of the function depends on the type of the objects the Input array holds. I can have the return type as Object, but it has problems like late binding and more importantly the client has to always Cast it. For example. class...
6
51508
by: Andrew | last post by:
Hi all, I have a method that wants to return an array. What datatype should I use ? I tried using an "Array" but there was a compilation error. Why ? public Array setReviewAll2 (int intNumQn) int rows = intNumQn; int cols = 3; string arrRv = new string ; for ( int i = arrRv.GetLowerBound(0); i <= arrRv.GetUpperBound(0); i++ ){
0
1887
by: DWalker | last post by:
VBA, as used in Excel 2000 and Excel 2003, has a function called Array. It's commonly seen in statements like the following: Workbooks.OpenText Filename:=ACFileName, _ StartRow:=1, DataType:=xlFixedWidth, FieldInfo:=Array(Array(0, 2), _ Array(9, 1), Array(18, 1), Array(33, 1), Array(49, 1), Array(71, 1), _ Array(75, 1), Array(89, 1), Array(113, 1), Array(117, 1), Array(135, 1)) The FieldInfo parameter is an array of arrays, and the...
0
6277
by: rascal_mon | last post by:
I'm new with XML. Please give me some advice. I wonder there are any difference between XML that is automatically generated from ADO and XML file that shows in many textbooks. I found that the formats are a bit difference. At the begining of the one that is automatically generated from ADO is usually like this <xml xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882" xmlns:dt="uuid: C2F41010-65B3-11d1-A29F-00AA00C14882"...
8
1710
by: Tom | last post by:
Is there a function to get a variable to return its name w/datatype of string? i.e.: $var would return "var"
0
10350
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
10157
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
10097
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
8983
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
7505
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
6742
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();...
1
4055
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
3658
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2887
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.