co********@gmail.com wrote:
Environemtnt: Visual C++ on Windows Xp
I am new somewhat new to C++ and would like to some advise and
correction to my code below. I am simply trying to write function that
generates an array and returns it to the caller for output and further
use. I have read bits sugessting that thios can be done using pointers,
structs and or vectors but no workin solution yet. Thanks in
advance...
int generateIntegers(int searchList[])
This defines a function that returns a SINGLE "int" by value. You're
passing in a pointer to an array of int (no size given).
Why are you returning an int ? The code below does initialize the array
except you're trying to return a pointer where you otherwise declared to
return an int by value.
/*This function generates a thousand integers held in an array*/
{
//searchList[1000];
for(int i=0; i<1000;++i)
{
searchList[i]=(i+1)*3;
}
return searchList;
}
This code would do what you're looking for.
void generateIntegers(int * searchList, unsigned length)
{
for(int i=0; i<length;++i)
{
searchList[i]=(i+1)*3;
}
}
The function above is more appropriate - it simply sets the values into
the array passed in.
// simply for determining the number of elements in an array....
template <typename w_Type, int w_N>
inline int CountElements( w_Type (&i_array)[ w_N ] )
{
return w_N;
}
int main()
{
int searchList[1000];
generateIntegers(searchList, CountElements( searchList ) );
for(int i=0; i<CountElements( searchList );++i) {
cout << searchList[i] << endl;
}
}
However, if you REALLY want to return a value (lots of memory copies
that degrade performance and not a good thing to do), you can do this:
#include <vector>
std::vector<int> generateIntegers(int count)
{
std::vector<int> searchList(count);
for(int i=0; i<count;++i)
{
searchList[i]=(i+1)*3;
}
return searchList;
}
int main()
{
int count = 1000;
std::vector<int> searchList = generateIntegers(count);
for(int i=0; i<searchList.size(); ++i)
{
std::cout << searchList[i] << std::endl;
}
}
The example above does more like what you described. It returns a vector
and probably makes 2 copies before you're done with the process. You
really want to avoid that if you can.
Finally, you can use a vector passed in by reference to eliminate the
copies (similar to what you did in your original example).
#include <vector>
void generateIntegers(std::vector<int> & searchList)
{
for(int i=0; i<searchList.size();++i)
{
searchList[i]=(i+1)*3;
}
}
int main()
{
std::vector<int> searchList(1000);
generateIntegers(searchList);
for(int i=0; i<searchList.size(); ++i)
{
std::cout << searchList[i] << std::endl;
}
}