views:

44

answers:

2

I'm coding a C++ function that accepts a string, an array and the size of the array. It looks like this:

bool funcname (string skey, string sArr[], int arrSz)

I want to pass several array data types, such as double, char, long int, etc. Is it right to use string as data type for the array? Or is there a general data type that I can use?

Thanks in advance.

+4  A: 

Using a string in this way is bad imo. Amongst other things you are sending an array of strings. You'd be better off using a std::vector. You could then template the function as follows:

template< typename T >
bool 
funcname (const std::string& skey, const std::vector< T >& arr )

This way you can directly query the vector for the size and you can pass through a vector of ANY data types.

Also bear in mind that its far more efficient to send structures through as const references instead of having a "potential" copy of the structures.

Goz
Actually, I'm not just sending array of strings, I'm sending array of different data types.
Ruel
Well you ARE sending an array of strings :P None-the-less are you saying that "sArr" could contain some doubles, some floats and some chars, etc?
Goz
seems like you just need vector (or another container) then
jk
Here's an example(using my version). `double dArr[10] = { //values }; funcname("randstring", dArr, 10);` also: `int iArr[5] = { //values }; funcname("somerandstring", iArr, 5);`
Ruel
vector is what you want.
lz_prgmr
Ok, thank you very much people!
Ruel
@Ruel: Then my solution above will work perfectly for you :)
Goz
+1  A: 

if you want arrays per se

template <typename T>
bool funcname (T key, T Arr[], int arrSz)
{
//T is the type of array you'll pass
}

also google for function templates. HTH

Armen Tsirunyan