I have an array of edges, which is defined as a C-style array of doubles, where every 4 doubles define an edge, like this:
double *p = ...;
printf("edge1: %lf %lf %lf %lf\n", p[0], p[1], p[2], p[3]);
printf("edge2: %lf %lf %lf %lf\n", p[4], p[5], p[6], p[7]);
So I want to use std::sort() to sort it by edge length. If it was a struct Edge { double x1, y1, x2, y2; }; Edge *p;, I would be good to go.
But in this case, the double array has a block size that is not expressed by the pointer type. qsort() allows you to explicitly specify the block size, but std::sort() infers the block-size by the pointer type.
For performance reasons (both memory-usage and CPU), let's say that it's undesirable to create new arrays, or transform the array somehow. For performance reasons again, let's say that we do want to use std::sort() instead of qsort().
Is it possible to call std::sort() without wasting a single CPU cycle on transforming the data?
Possible approach:
An obvious approach is to try to force-cast the pointer:
double *p = ...;
struct Edge { double arr[4]; };
Edge *p2 = reinterpret_cast<Edge*>(p);
std::sort(...);
But how do I make sure the data is aligned properly? Also, how do I make sure it will always be aligned properly on all platforms and architectures?
Or can I use a typedef double[4] Edge;?
How about having a reordering vector? You initialize vector with 1..N/L, pass std::sort a comparator that compares elements i1*L..i1*L+L to i2*L..i2*L+L, and when your vector is properly sorted, reorder the C array according to new order.
In response to comment: yes things get complicated, but it may just be good complication! Take a look here.
You can use a "stride iterator" for this. A "stride iterator" wraps another iterator and an integer step size. Here's a simple sketch:
template<typename Iter>
class stride_iterator
{
...
stride_iterator(Iter it, difference_type step = difference_type(1))
: it_(it), step_(step) {}
stride_iterator& operator++() {
std::advance(it_,step_);
return *this;
}
Iter base() const { return it_; }
difference_type step() const { return step_; }
...
private:
Iter it_;
difference_type step_;
};
Also, helper functions like these
template<typename Iter>
stride_iterator<Iter> make_stride_iter(
Iter it,
typename iterator_traits<Iter>::difference_type step)
{
return stride_iterator<Iter>(it,step);
}
template<typename Iter>
stride_iterator<Iter> make_stride_iter(
stride_iterator<Iter> it,
typename iterator_traits<Iter>::difference_type step)
{
return stride_iterator<Iter>(it.base(),it.step() * step);
}
should make it fairly easy to use stride iterators:
int array[N*L];
std::sort( make_stride_iter(array,L),
make_stride_iter(array,L)+N );
Implementing the iterator adapter all by yourself (with all operators) is probably not a good idea. As Matthieu pointed out, you can safe yourself a lot of typing if you make use of Boost's iterator adapter tools, for example.
Edit:
I just realized that this doesn't do what you wanted since std::sort will only exchange the first element of each block. I don't think there's an easy and portable solution for this. The problem I see is that swapping "elements" (your blocks) cannot be (easily) customized when using std::sort. You could possibly write your iterator to return a special reference type with a special swap function but I'm not sure whether the C++ standard guarantees that std::sort will use a swap function that is looked up via ADL. Your implementation may restrict it to std::swap.
I guess the best answer is still: "Just use qsort".
For the new question, we need to pass in sort() a kind of iterator that will not only let us compare the right things (i.e. will make sure to take 4 steps through our double[] each time instead of 1) but also swap the right things (i.e. swap 4 doubles instead of one).
We can accomplish both by simply reinterpreting our double array as if it were an array of 4 doubles. Doing this:
typedef double Edge[4];
doesn't work, since you can't assign an array, and swap will need to. But doing this:
typedef std::array<double, 4> Edge;
or, if not C++11:
struct Edge {
double vals[4];
};
satisfies both requirements. Thus:
void sort(double* begin, double* end) {
typedef std::array<double, 4> Edge;
Edge* edge_begin = reinterpret_cast<Edge*>(begin);
Edge* edge_end = reinterpret_cast<Edge*>(end);
std::sort(edge_begin, edge_end, compare_edges);
}
bool compare_edges(const Edge& lhs, const Edge& rhs) {
// to be implemented
}
If you're concerned about alignment, can always just assert that there's no extra padding:
static_assert(sizeof(Edge) == 4 * sizeof(double), "uh oh");
I don't remember exactly how to do this, but if you can fake anonymous functions, then you can make a comp(L) function that returns the version of comp for arrays of length L... that way L becomes a parameter, not a global, and you can use qsort. As others mentioned, except in the case where your array is already sorted, or backwards or something, qsort is going to be pretty much just as fast as any other algorithm. (there's a reason it's called quicksort after all...)
It's not part of any ANSI, ISO, or POSIX standard, but some systems provide the qsort_r() function, which allows you to pass an extra context parameter to the comparison function. You can then do something like this:
int comp(void *thunk, const void *a, const void *b)
{
int L = (int)thunk;
// compare a and b as you would normally with a qsort comparison function
}
qsort_r(array, N, sizeof(int) * L, (void *)L, comp);
Alternatively, if you don't have qsort_r, you can use the callback(3) package from the ffcall library to create closures at runtime. Example:
#include <callback.h>
void comp_base(void *data, va_alist alist)
{
va_start_int(alist); // return type will be int
int L = (int)data;
const void *a = va_arg_ptr(alist, const void*);
const void *b = va_arg_ptr(alist, const void*);
// Now that we know L, compare
int return_value = comp(a, b, L);
va_return_int(alist, return_value); // return return_value
}
...
// In a function somewhere
typedef int (*compare_func)(const void*, const void*);
// Create some closures with different L values
compare_func comp1 = (compare_func)alloc_callback(&comp_base, (void *)L1);
compare_func comp2 = (compare_func)alloc_callback(&comp_base, (void *)L2);
...
// Use comp1 & comp2, e.g. as parameters to qsort
...
free_callback(comp1);
free_callback(comp2);
Note that the callback library is threadsafe, since all parameters are passed on the stack or in registers. The library takes care of allocating memory, making sure that memory is executable, and flushing the instruction cache if necessary to allow dynamically generated code (that is, the closure) to be executed at runtime. It supposedly works on a large variety of systems, but it's also quite possible that it won't work on yours, either due to bugs or lack of implementation.
Also note that this adds a little bit of overhead to the function call. Each call to comp_base() above has to unpack its arguments from the list passed it (which is in a highly platform-dependent format) and stuff its return value back in. Most of the time, this overhead is miniscule, but for a comparison function where the actual work performed is very small and which will get called many, many times during a call to qsort(), the overhead is very significant.
std::array< std::array<int, L>, N > array;
// or std::vector< std::vector<int> > if N*L is not a constant
std::sort( array.begin(), array.end() );
I'm not sure if you can achieve the same result without a lot more work. std::sort() is made to sort sequences of elements defined by two random access iterators. Unfortunately, it determines the type of the element from the iterator. For example:
std::sort(&array[0], &array[N + L]);
will sort all of the elements of array. The problem is that it assumes that the subscripting, increment, decrement, and other indexing operators of the iterator step over elements of the sequence. I believe that the only way that you can sort slices of the array (I think that this is what you are after), is to write an iterator that indexes based on L. This is what sellibitze has done in the stride_iterator answer.
namespace
{
struct NewCompare
{
bool operator()( const int a, const int b ) const
{
return a < b;
}
};
}
std::sort(array+start,array+start+L,NewCompare);
Do test with std::stable_sort() on realistic data-sets - for some data mixes its substantially faster!
On many compilers (GCC iirc) there's a nasty bite: the std::sort() template asserts that the comparator is correct by testing it TWICE, once reversed, to ensure the result is reversed! This will absolutely completely kill performance for moderate datasets in normal builds. The solution is something like this:
#ifdef NDEBUG
#define WAS_NDEBUG
#undef NDEBUG
#endif
#define NDEBUG
#include <algorithm>
#ifdef WAS_NDEBUG
#undef WAS_NDEBUG
#else
#undef NDEBUG
#endif
Adapted from this excellent blog entry: http://www.tilander.org/aurora/2007/12/comparing-stdsort-and-qsort.html
Arkadiy has the right idea. You can sort in place if you create an array of pointers and sort that:
#define NN 7
#define LL 4
int array[NN*LL] = {
3, 5, 5, 5,
3, 6, 6, 6,
4, 4, 4, 4,
4, 3, 3, 3,
2, 2, 2, 2,
2, 0, 0, 0,
1, 1, 1, 1
};
struct IntPtrArrayComp {
int length;
IntPtrArrayComp(int len) : length(len) {}
bool operator()(int* const & a, int* const & b) {
for (int i = 0; i < length; ++i) {
if (a[i] < b[i]) return true;
else if (a[i] > b[i]) return false;
}
return false;
}
};
void sortArrayInPlace(int* array, int number, int length)
{
int** ptrs = new int*[number];
int** span = ptrs;
for (int* a = array; a < array+number*length; a+=length) {
*span++ = a;
}
std::sort(ptrs, ptrs+number, IntPtrArrayComp(length));
int* buf = new int[number];
for (int n = 0; n < number; ++n) {
int offset = (ptrs[n] - array)/length;
if (offset == n) continue;
// swap
int* a_n = array+n*length;
std::move(a_n, a_n+length, buf);
std::move(ptrs[n], ptrs[n]+length, a_n);
std::move(buf, buf+length, ptrs[n]);
// find what is pointing to a_n and point it
// to where the data was move to
int find = 0;
for (int i = n+1; i < number; ++i) {
if (ptrs[i] == a_n) {
find = i;
break;
}
}
ptrs[find] = ptrs[n];
}
delete[] buf;
delete[] ptrs;
}
int main()
{
for (int n = 0; n< NN; ++n) {
for (int l = 0; l < LL; ++l) {
std::cout << array[n*LL+l];
}
std::cout << std::endl;
}
std::cout << "----" << std::endl;
sortArrayInPlace(array, NN, LL);
for (int n = 0; n< NN; ++n) {
for (int l = 0; l < LL; ++l) {
std::cout << array[n*LL+l];
}
std::cout << std::endl;
}
return 0;
}
Output:
3555
3666
4444
4333
2222
2000
1111
----
1111
2000
2222
3555
3666
4333
4444
A lot of these answers seem like overkill. If you really have to do it C++ style, using jmucchiello's example:
template <int Length>
struct Block
{
int n_[Length];
bool operator <(Block const &rhs) const
{
for (int i(0); i < Length; ++i)
{
if (n_[i] < rhs.n_[i])
return true;
else if (n_[i] > rhs.n_[i])
return false;
}
return false;
}
};
and then sort with:
sort((Block<4> *)&array[0], (Block<4> *)&array[NN]);
It doesn't have to be any more complicated.
Related
Mainly as an exercise I am implementing a conversion from base B to base 10:
unsigned fromBaseB(std::vector<unsigned> x,unsigned b){
unsigned out = 0;
unsigned pow = 1;
for (size_t i=0;i<x.size();i++){
out += pow * x[i];
pow *= b;
}
return out;
}
int main() {
auto z = std::vector<unsigned>(9,0);
z[3] = 1;
std::cout << fromBaseB(z,3) << std::endl;
}
Now I would like to write this using algorithms. E.g. using accumulate I could write
unsigned fromBaseB2(std::vector<unsigned> x,unsigned b){
unsigned pow = 1;
return std::accumulate(x.begin(),
x.end(),0u,
[pow,b](unsigned sum,unsigned v) mutable {
unsigned out = pow*v;
pow *= b;
return out+sum;
});
}
However, imho thats not nicer code at all. Actually it would be more natural to write it as an inner product, because thats just what we have to calculate to make the basis transformation. But to use inner_product I need an iterator:
template <typename T> struct pow_iterator{
typedef T value_type;
pow_iterator(T base) : base(base),value(1) {}
T base,value;
pow_iterator& operator++(){ value *= base;return *this; }
T operator*() {return value; }
bool operator==(const pow_iterator& other) const { return value == other.value;}
};
unsigned fromBaseB3(std::vector<unsigned> x,unsigned b){
return std::inner_product(x.begin(),x.end(),pow_iterator<unsigned>(b),0u);
}
Using that iterator, now calling the algorithm is nice an clean, but I had to write a lot of boilerplate code for the iterator. Maybe it is just my misunderstanding of how algorithms and iterators are supposed to be used... Actually this is just an example of a general problem I am facing sometimes: I have a sequence of numbers that is calculated based on a simple pattern and I would like to have a iterator that when dereferenced returns the corresponding number from that sequence. When the sequence is stored in a container I simply use the iterators provided by the container, but I would like to do the same, also when there is no container where the values are stored. I could of course try to write my own generic iterator that does the job, but isnt there something existing in the standard library that can help here?
To me it feels a bit strange, that I can use a lambda to cheat accumulate into calculating an inner product, but to use inner_product directly I have to do something extra (either precalculate the powers and store them in a container, or write an iterator ie. a seperate class).
tl;dr: Is there a easy way to reduce the boilerplate for the pow_iterator above?
the more general (but maybe too broad) question: Is it "ok" to use an iterator for a sequence of values that is not stored in a container, but that is calculated only if the iterator is dereferenced? Is there a "C++ way" of implementing it?
As Richard Hodges wrote in the comments, you can look at boost::iterator. Alternatively, there is range-v3. If you go with boost, there are a few possible ways to go. The following shows how to do so with boost::iterator::counting_iterator and boost::iterator::transform_iterator (C++ 11):
#include <iostream>
#include <cmath>
#include <boost/iterator/counting_iterator.hpp>
#include <boost/iterator/transform_iterator.hpp>
int main() {
const std::size_t base = 2;
auto make_it = [](std::size_t i) {
return boost::make_transform_iterator(
boost::make_counting_iterator(i),
[](std::size_t j){return std::pow(base, j);});};
for(auto b = make_it(0); b != make_it(10); ++b)
std::cout << *b << std::endl;
}
Here's the output:
$ ./a.out
1
2
4
8
16
32
64
128
256
512
I have an array int arr[5] that is passed to a function fillarr(int arr[]):
int fillarr(int arr[])
{
for(...);
return arr;
}
How can I return that array?
How will I use it, say I returned a pointer how am I going to access it?
In this case, your array variable arr can actually also be treated as a pointer to the beginning of your array's block in memory, by an implicit conversion. This syntax that you're using:
int fillarr(int arr[])
Is kind of just syntactic sugar. You could really replace it with this and it would still work:
int fillarr(int* arr)
So in the same sense, what you want to return from your function is actually a pointer to the first element in the array:
int* fillarr(int arr[])
And you'll still be able to use it just like you would a normal array:
int main()
{
int y[10];
int *a = fillarr(y);
cout << a[0] << endl;
}
C++ functions can't return C-style arrays by value. The closest thing is to return a pointer. Furthermore, an array type in the argument list is simply converted to a pointer.
int *fillarr( int arr[] ) { // arr "decays" to type int *
return arr;
}
You can improve it by using an array references for the argument and return, which prevents the decay:
int ( &fillarr( int (&arr)[5] ) )[5] { // no decay; argument must be size 5
return arr;
}
With Boost or C++11, pass-by-reference is only optional and the syntax is less mind-bending:
array< int, 5 > &fillarr( array< int, 5 > &arr ) {
return arr; // "array" being boost::array or std::array
}
The array template simply generates a struct containing a C-style array, so you can apply object-oriented semantics yet retain the array's original simplicity.
In C++11, you can return std::array.
#include <array>
using namespace std;
array<int, 5> fillarr(int arr[])
{
array<int, 5> arr2;
for(int i=0; i<5; ++i) {
arr2[i]=arr[i]*2;
}
return arr2;
}
$8.3.5/8 states-
"Functions shall not have a return type of type array or function, although they may have a return type of type pointer or reference to such things. There shall be no arrays of functions, although there can be arrays of pointers to functions."
int (&fn1(int (&arr)[5]))[5]{ // declare fn1 as returning refernce to array
return arr;
}
int *fn2(int arr[]){ // declare fn2 as returning pointer to array
return arr;
}
int main(){
int buf[5];
fn1(buf);
fn2(buf);
}
the answer may depend a bit on how you plan to use that function. For the simplest answer, lets decide that instead of an array, what you really want is a vector. Vectors are nice because the look for all the world like boring, ordinary values you can store in regular pointers. We'll look at other options and why you want them afterwards:
std::vector<int> fillarr( std::vector<int> arr ) {
// do something
return arr;
}
This will do exactly what you expect it to do. The upside is that std::vector takes care of making sure everything is handled cleanly. the downside is that this copies a very large amount of data, if your array is large. In fact it copies every element of the array twice. first it copies the vector so that the function can use it as a parameter. then it copies it again to return it to the caller. If you can handle managing the vector yourself, you can do things quite a bit more easily. (it may copy it a third time if the caller needs to store it in a variable of some sort to do more calculation)
It looks like what you're really trying to do is just populate a collection. if you don't have a specific reason to return a new instance of a collection, then don't. we can do it like this
void fillarr(std::vector<int> & arr) {
// modify arr
// don't return anything
}
this way you get a reference to the array passed to the function, not a private copy of it. any changes you make to the parameter are seen by the caller. You could return a reference to it if you want, but that's not really a great idea, since it sort of implies that you're getting something different from what you passed.
If you really do need a new instance of the collection, but want to avoid having it on the stack (and all the copying that entails), you need to create some kind of contract for how that instance is handled. the easiest way to do that is to use a smart pointer, which keeps the referenced instance around as long as anyone is holding onto it. It goes away cleanly if it goes out of scope. That would look like this.
std::auto_ptr<std::vector<int> > fillarr( const std::vector<int> & arr) {
std::auto_ptr<std::vector<int> > myArr(new std::vector<int>);
// do stuff with arr and *myArr
return myArr;
}
For the most part, using *myArr works identically to using a plain vanilla vector. This example also modifies the parameter list by adding the const keyword. Now you get a reference without copying it, but you can't modify it, so the caller knows it'll be the same as before the function got to it.
All of this is swell, but idiomatic c++ rarely works with collections as a whole. More normally, you will be using iterators over those collections. that would look something more like this
template <class Iterator>
Iterator fillarr(Iterator arrStart, Iterator arrEnd) {
Iterator arrIter = arrStart;
for(;arrIter <= arrEnd; arrIter++)
;// do something
return arrStart;
}
Using it looks a bit odd if you're not used to seeing this style.
vector<int> arr;
vector<int>::iterator foo = fillarr(arr.begin(), arr.end());
foo now 'points to' the beginning of the modified arr.
What's really nice about this is that it works equally well on vector as on plain C arrays and many other types of collection, for example
int arr[100];
int *foo = fillarr(arr, arr+100);
Which now looks an awful lot like the plain pointer examples given elsewhere in this question.
This:
int fillarr(int arr[])
is actually treated the same as:
int fillarr(int *arr)
Now if you really want to return an array you can change that line to
int * fillarr(int arr[]){
// do something to arr
return arr;
}
It's not really returning an array. you're returning a pointer to the start of the
array address.
But remember when you pass in the array, you're only passing in a pointer.
So when you modify the array data, you're actually modifying the data that the
pointer is pointing at. Therefore before you passed in the array, you must realise
that you already have on the outside the modified result.
e.g.
int fillarr(int arr[]){
array[0] = 10;
array[1] = 5;
}
int main(int argc, char* argv[]){
int arr[] = { 1,2,3,4,5 };
// arr[0] == 1
// arr[1] == 2 etc
int result = fillarr(arr);
// arr[0] == 10
// arr[1] == 5
return 0;
}
I suggest you might want to consider putting a length into your fillarr function like
this.
int * fillarr(int arr[], int length)
That way you can use length to fill the array to it's length no matter what it is.
To actually use it properly. Do something like this:
int * fillarr(int arr[], int length){
for (int i = 0; i < length; ++i){
// arr[i] = ? // do what you want to do here
}
return arr;
}
// then where you want to use it.
int arr[5];
int *arr2;
arr2 = fillarr(arr, 5);
// at this point, arr & arr2 are basically the same, just slightly
// different types. You can cast arr to a (char*) and it'll be the same.
If all you're wanting to do is set the array to some default values, consider using
the built in memset function.
something like:
memset((int*)&arr, 5, sizeof(int));
While I'm on the topic though. You say you're using C++. Have a look at using stl vectors. Your code is likely to be more robust.
There are lots of tutorials. Here is one that gives you an idea of how to use them.
http://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html
This is a fairly old question, but I'm going to put in my 2 cents as there are a lot of answers, but none showing all possible methods in a clear and concise manner (not sure about the concise bit, as this got a bit out of hand. TL;DR đŸ˜‰).
I'm assuming that the OP wanted to return the array that was passed in without copying as some means of directly passing this to the caller to be passed to another function to make the code look prettier.
However, to use an array like this is to let it decay into a pointer and have the compiler treat it like an array. This can result in subtle bugs if you pass in an array like, with the function expecting that it will have 5 elements, but your caller actually passes in some other number.
There a few ways you can handle this better. Pass in a std::vector or std::array (not sure if std::array was around in 2010 when the question was asked). You can then pass the object as a reference without any copying/moving of the object.
std::array<int, 5>& fillarr(std::array<int, 5>& arr)
{
// (before c++11)
for(auto it = arr.begin(); it != arr.end(); ++it)
{ /* do stuff */ }
// Note the following are for c++11 and higher. They will work for all
// the other examples below except for the stuff after the Edit.
// (c++11 and up)
for(auto it = std::begin(arr); it != std::end(arr); ++it)
{ /* do stuff */ }
// range for loop (c++11 and up)
for(auto& element : arr)
{ /* do stuff */ }
return arr;
}
std::vector<int>& fillarr(std::vector<int>& arr)
{
for(auto it = arr.begin(); it != arr.end(); ++it)
{ /* do stuff */ }
return arr;
}
However, if you insist on playing with C arrays, then use a template which will keep the information of how many items in the array.
template <size_t N>
int(&fillarr(int(&arr)[N]))[N]
{
// N is easier and cleaner than specifying sizeof(arr)/sizeof(arr[0])
for(int* it = arr; it != arr + N; ++it)
{ /* do stuff */ }
return arr;
}
Except, that looks butt ugly, and super hard to read. I now use something to help with that which wasn't around in 2010, which I also use for function pointers:
template <typename T>
using type_t = T;
template <size_t N>
type_t<int(&)[N]> fillarr(type_t<int(&)[N]> arr)
{
// N is easier and cleaner than specifying sizeof(arr)/sizeof(arr[0])
for(int* it = arr; it != arr + N; ++it)
{ /* do stuff */ }
return arr;
}
This moves the type where one would expect it to be, making this far more readable. Of course, using a template is superfluous if you are not going to use anything but 5 elements, so you can of course hard code it:
type_t<int(&)[5]> fillarr(type_t<int(&)[5]> arr)
{
// Prefer using the compiler to figure out how many elements there are
// as it reduces the number of locations where you have to change if needed.
for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
{ /* do stuff */ }
return arr;
}
As I said, my type_t<> trick wouldn't have worked at the time this question was asked. The best you could have hoped for back then was to use a type in a struct:
template<typename T>
struct type
{
typedef T type;
};
typename type<int(&)[5]>::type fillarr(typename type<int(&)[5]>::type arr)
{
// Prefer using the compiler to figure out how many elements there are
// as it reduces the number of locations where you have to change if needed.
for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
{ /* do stuff */ }
return arr;
}
Which starts to look pretty ugly again, but at least is still more readable, though the typename may have been optional back then depending on the compiler, resulting in:
type<int(&)[5]>::type fillarr(type<int(&)[5]>::type arr)
{
// Prefer using the compiler to figure out how many elements there are
// as it reduces the number of locations where you have to change if needed.
for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
{ /* do stuff */ }
return arr;
}
And then of course you could have specified a specific type, rather than using my helper.
typedef int(&array5)[5];
array5 fillarr(array5 arr)
{
// Prefer using the compiler to figure out how many elements there are
// as it reduces the number of locations where you have to change if needed.
for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
{ /* do stuff */ }
return arr;
}
Back then, the free functions std::begin() and std::end() didn't exist, though could have been easily implemented. This would have allowed iterating over the array in a safer manner as they make sense on a C array, but not a pointer.
As for accessing the array, you could either pass it to another function that takes the same parameter type, or make an alias to it (which wouldn't make much sense as you already have the original in that scope). Accessing a array reference is just like accessing the original array.
void other_function(type_t<int(&)[5]> x) { /* do something else */ }
void fn()
{
int array[5];
other_function(fillarr(array));
}
or
void fn()
{
int array[5];
auto& array2 = fillarr(array); // alias. But why bother.
int forth_entry = array[4];
int forth_entry2 = array2[4]; // same value as forth_entry
}
To summarize, it is best to not allow an array decay into a pointer if you intend to iterate over it. It is just a bad idea as it keeps the compiler from protecting you from shooting yourself in the foot and makes your code harder to read. Always try and help the compiler help you by keeping the types as long as possible unless you have a very good reason not to do so.
Edit
Oh, and for completeness, you can allow it to degrade to a pointer, but this decouples the array from the number of elements it holds. This is done a lot in C/C++ and is usually mitigated by passing the number of elements in the array. However, the compiler can't help you if you make a mistake and pass in the wrong value to the number of elements.
// separate size value
int* fillarr(int* arr, size_t size)
{
for(int* it = arr; it != arr + size; ++it)
{ /* do stuff */ }
return arr;
}
Instead of passing the size, you can pass the end pointer, which will point to one past the end of your array. This is useful as it makes for something that is closer to the std algorithms, which take a begin and and end pointer, but what you return is now only something that you must remember.
// separate end pointer
int* fillarr(int* arr, int* end)
{
for(int* it = arr; it != end; ++it)
{ /* do stuff */ }
return arr;
}
Alternatively, you can document that this function will only take 5 elements and hope that the user of your function doesn't do anything stupid.
// I document that this function will ONLY take 5 elements and
// return the same array of 5 elements. If you pass in anything
// else, may nazal demons exit thine nose!
int* fillarr(int* arr)
{
for(int* it = arr; it != arr + 5; ++it)
{ /* do stuff */ }
return arr;
}
Note that the return value has lost it's original type and is degraded to a pointer. Because of this, you are now on your own to ensure that you are not going to overrun the array.
You could pass a std::pair<int*, int*>, which you can use for begin and end and pass that around, but then it really stops looking like an array.
std::pair<int*, int*> fillarr(std::pair<int*, int*> arr)
{
for(int* it = arr.first; it != arr.second; ++it)
{ /* do stuff */ }
return arr; // if you change arr, then return the original arr value.
}
void fn()
{
int array[5];
auto array2 = fillarr(std::make_pair(&array[0], &array[5]));
// Can be done, but you have the original array in scope, so why bother.
int fourth_element = array2.first[4];
}
or
void other_function(std::pair<int*, int*> array)
{
// Can be done, but you have the original array in scope, so why bother.
int fourth_element = array2.first[4];
}
void fn()
{
int array[5];
other_function(fillarr(std::make_pair(&array[0], &array[5])));
}
Funny enough, this is very similar to how std::initializer_list work (c++11), but they don't work in this context.
to return an array from a function , let us define that array in a structure;
So it looks something like this
struct Marks{
int list[5];
}
Now let us create variables of the type structure.
typedef struct Marks marks;
marks marks_list;
We can pass array to a function in the following way and assign value to it:
void setMarks(int marks_array[]){
for(int i=0;i<sizeof(marks_array)/sizeof(int);i++)
marks_list.list[i]=marks_array[i];
}
We can also return the array. To return the array , the return type of the function should be of structure type ie marks. This is because in reality we are passing the structure that contains the array. So the final code may look like this.
marks getMarks(){
return marks_list;
}
the Simplest way to do this ,is to return it by reference , even if you don't write
the '&' symbol , it is automatically returned by reference
void fillarr(int arr[5])
{
for(...);
}
int *fillarr(int arr[])
You can still use the result like
int *returned_array = fillarr(some_other_array);
if(returned_array[0] == 3)
do_important_cool_stuff();
As above mentioned paths are correct. But i think if we just return a local array variable of a function sometimes it returns garbage values as its elements.
in-order to avoid that i had to create the array dynamically and proceed. Which is something like this.
int* func()
{
int* Arr = new int[100];
return Arr;
}
int main()
{
int* ArrResult = func();
cout << ArrResult[0] << " " << ArrResult[1] << endl;
return 0;
}
Source: https://www.tutorialspoint.com/cplusplus/cpp_return_arrays_from_functions.htm
C++ does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.
If you want to return a single-dimension array from a function, you would have to declare a function returning a pointer as in the following example:
int * myFunction() {
.
.
.
}
C++ does not advocate to return the address of a local variable to outside of the function so you would have to define the local variable as static variable.
Applying these rules on the current question, we can write the program as follows:
# include <iostream>
using namespace std;
int * fillarr( );
int main ()
{
int *p;
p = fillarr();
for ( int i = 0; i < 5; i++ )
cout << "p[" << i << "] : "<< *(p + i) << endl;
return 0;
}
int * fillarr( )
{
static int arr[5];
for (int i = 0; i < 5; ++i)
arr[i] = i;
return arr;
}
The Output will be:
p[0]=0
p[1]=1
p[2]=2
p[3]=3
p[4]=4
template<typename T, size_t N>
using ARR_REF = T (&)[N];
template <typename T, size_t N>
ARR_REF<T,N> ArraySizeHelper(ARR_REF<T,N> arr);
#define arraysize(arr) sizeof(ArraySizeHelper(arr))
and what about:
int (*func())
{
int *f = new int[10] {1,2,3};
return f;
}
int fa[10] = { 0 };
auto func2() -> int (*) [10]
{
return &fa;
}
Actually when you pass an array inside a function, the pointer to the original array is passed in the function parameter and thus the changes made to the array inside that function is actually made on the original array.
#include <iostream>
using namespace std;
int* func(int ar[])
{
for(int i=0;i<100;i++)
ar[i]=i;
int *ptr=ar;
return ptr;
}
int main() {
int *p;
int y[100]={0};
p=func(y);
for(int i=0;i<100;i++)
cout<<i<<" : "<<y[i]<<'\n';
}
Run it and you will see the changes
And why don't "return" the array as a parameter?
fillarr(int source[], size_t dimSource, int dest[], size_t dimDest)
{
if (dimSource <= dimDest)
{
for (size_t i = 0; i < dimSource; i++)
{
//some stuff...
}
}
else
{
//some stuff..
}
}
or..in a simpler way (but you have to know the dimensions...):
fillarr(int source[], int dest[])
{
//...
}
A simple and elaborate example, so that I can refer here if I forget the concept and need help.
#include <iostream>
using namespace std;
int *ReturnArray(int arr[], int size)
{
static int MinMax[2] = {0, 0}; // must use static, else address would be deleted after the return is reached
MinMax[0] = arr[0];
MinMax[1] = arr[size - 1];
return MinMax;
}
int main()
{
int arr[] = {1, 2, 3};
int size = sizeof(arr) / sizeof(*arr);
int *ans; // pointer to hold returned array
ans = ReturnArray(arr, size); // only pointer can receive the return, not an array
cout << "Min: " << ans[0] << " Max: " << ans[1];
return 0;
}
Here's a full example of this kind of problem to solve
#include <bits/stdc++.h>
using namespace std;
int* solve(int brr[],int n)
{
sort(brr,brr+n);
return brr;
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int *a=solve(arr,n);
for(int i=0;i<n;i++)
{
cout<<a[i]<<endl;
}
return 0;
}
i used static array so that while returning array it should not throw error as you are returning address of local variable...
so now you can send any locally created variable from function by making it as static...as it works as global variable....
#include<iostream>
using namespace std;
char *func(int n)
{
// char a[26]; /*if we use this then an error will occur because you are
// returning address of a local variable*/
static char a[26];
char temp='A';
for(int i=0;i<n;i++)
{
a[i]=temp;temp++;
}
return a;
}
int main()
{
int n=26;
char *p=func(n);
for(int i=0;i<n;i++)
cout<<*(p+i)<<" ";
//or you can also print like this
for(int i=0;i<n;i++)
cout<<p[i]<<" ";
}
Just define a type[ ] as return value, like:
private string[] functionReturnValueArray(string one, string two)
{
string[] x = {one, two};
x[0] = "a";
x[1] = "b";
return x;
}
.
.
.
function call:
string[] y;
y = functionReturnValueArray(stringOne, stringTwo)
I want to add two arrays by simply writing:
int a[4] = {1,2,3,4};
int b[4] = {2,1,3,1};
int sum[4] = a + b;
I wrote this function but I got an error
int* operator+(const uint32& other) const{
uint32 sum[n];
for(int i=0; i<n; i++){
sum[i] = (*this[i]) + other[i];
}
return sum;
}
Could you help me on this? Thanks in advance.
Let's go through your code, piece by piece, and look at the problems:
int* operator+(const uint32& other) const{
You can't overload operators for built-in types, so this is doomed from the beginning
Even if you could do this (which you can't), it needs to take two parameters since it's non-member binary function.
uint32 sum[n];
You can't make variable-length arrays in C++ (assuming n isn't a compile-time constant) (note: G++ has some extensions that allow this, but it's non-standard C++)
for(int i=0; i<n; i++){
sum[i] = (*this[i]) + other[i];
There's no this pointer to begin with in this code (it's not a member function)...
const uint32& other is not an array/pointer to an array. It's a single reference to a single uint32. That means that other in this code is not an array/pointer to an array, and so you cannot do other[i] (it's like trying to do int x = 3; x[4] = 13;, which makes no sense).
}
return sum;
You're returning a pointer to a locally allocated array, which means this will result in undefined behavior, as the memory associated with sum is going to get annihilated when this function returns.
}
This is probably wrong, but it appears to work (C++11):
#include <iostream>
#include <array>
using namespace std;
template <class T>
T operator+(const T& a1, const T& a2)
{
T a;
for (typename T::size_type i = 0; i < a1.size(); i++)
a[i] = a1[i] + a2[i];
return a;
}
int main()
{
array<int,5> a1 = { 1, 2, 3, 4, 5 };
array<int,5> a2 = { 2, 3, 4, 5, 6 };
array<int,5> a3 = a1 + a2;
for (int i = 0; i < 5; i++)
cout << a1[i] << '+' << a2[i] << '=' << a3[i] << ' ';
cout << endl;
return 0;
}
Output (ideone):
1+2=3 2+3=5 3+4=7 4+5=9 5+6=11
I think the issue is that you're missing a way to pass in the length of the array. You might need to do something a bit more sophisticated. Something like:
class AddingVector : public std::vector<int>
{
public:
typedef AddingVector type;
type operator+(const AddingVector& rhs, const AddingVector& lhs)
{
/* validate that they're the same size, decide how you want to handle that*/
AddingVector retVal;
AddingVector::const_iterator rIter = rhs.begin();
AddingVector::const_iterator lIter = lhs.begin();
while (rIter != rhs.end() && lIter != lhs.end()) {
retVal.push_back(*rIter + *lIter);
++rIter;
++lIter;
}
return retVal;
}
}
You cannot do that. Non-member binary operators must take two arguments (you only provided one), so you could try this:
int* operator+(const uint32& a, const uint32& b)
But that can't possibly work either, since you want to add arrays, not single uint32 variables. So you would think that this would do it:
int* operator+(const uint32[] a, const uint32[] b)
or:
int* operator+(const uint32[4] a, const uint32[4] b)
But no go. It's illegal because you cannot have pointer types as both arguments in an operator overload. Additionally, at least one of the arguments must be a class type or an enum. So what you're trying to do is already impossible on at least two different levels.
It's impossible to do what you want. One correct way to go about it is to write your own class for an array that can be added to another one.
You cannot overload operators for types other than your own defined types. That is, if you create a class X, you can overload operators for X, but you cannot overload operators for arrays or pointers to fundamental types.
first is your code getting compiled properly, you have used 'n' directly in declaring array, is 'n' declared as constant..
And moreover you have taken a local variable in the function and returning it, well, this return a garbage form the stack, wat i can suggest is you malloc some memory and use it,, but again freeing it would be needed...
Hey, what you could do is,
Take a wrapper class "array"
class array
{
int *ipArr;
DWORD size;
};
then in constructor you can pass the size you want to have an array of
array(DWORD dwSize);
{
// then malloc memory of size dwSize;
}
Have an overloaded operator'+' for this class, that will have the above implementation of adding two int arrays,
Note here you will also need to overlaod the '=' assignment operator, so that our array class can you is directly..
now you can free the associated memory in the destructor
You have a few problems. The first is that you aren't passing in both arrays, and then you don't specify what n is, and the last is that you are trying to pass out a pointer to a local variable. It looks like you are trying to make a member operator of a class.
So basically you are trying to add the contents of an unspecified length array to an uninitialised array of the same length and return the stack memory.
So if you pass in pointers to the arrays and the length of the array and an output array then it would work, but you wouldn't have the syntax
sum = a + b;
it would be something like
addArray(&a, &b, &sum, 4);
To get the syntax you want you could make a class that wraps an array. But that is a much more complicated task.
as in the title is it possible to join a number of arrays together without copying and only using pointers? I'm spending a significant amount of computation time copying smaller arrays into larger ones.
note I can't used vectors since umfpack (some matrix solving library) does not allow me to or i don't know how.
As an example:
int n = 5;
// dynamically allocate array with use of pointer
int *a = new int[n];
// define array pointed by *a as [1 2 3 4 5]
for(int i=0;i<n;i++) {
a[i]=i+1;
}
// pointer to array of pointers ??? --> this does not work
int *large_a = new int[4];
for(int i=0;i<4;i++) {
large_a[i] = a;
}
Note: There is already a simple solution I know and that is just to iteratively copy them to a new large array, but would be nice to know if there is no need to copy repeated blocks that are stored throughout the duration of the program. I'm in a learning curve atm.
thanks for reading everyone
as in the title is it possible to join a number of arrays together without copying and only using pointers?
In short, no.
A pointer is simply an address into memory - like a street address. You can't move two houses next to each other, just by copying their addresses around. Nor can you move two houses together by changing their addresses. Changing the address doesn't move the house, it points to a new house.
note I can't used vectors since umfpack (some matrix solving library) does not allow me to or i don't know how.
In most cases, you can pass the address of the first element of a std::vector when an array is expected.
std::vector a = {0, 1, 2}; // C++0x initialization
void c_fn_call(int*);
c_fn_call(&a[0]);
This works because vector guarantees that the storage for its contents is always contiguous.
However, when you insert or erase an element from a vector, it invalidates pointers and iterators that came from it. Any pointers you might have gotten from taking an element's address no longer point to the vector, if the storage that it has allocated must change size.
No. The memory of two arrays are not necessarily contiguous so there is no way to join them without copying. And array elements must be in contiguous memory...or pointer access would not be possible.
I'd probably use memcpy/memmove, which is still going to be copying the memory around, but at least it's been optimized and tested by your compiler vendor.
Of course, the "real" C++ way of doing it would be to use standard containers and iterators. If you've got memory scattered all over the place like this, it sounds like a better idea to me to use a linked list, unless you are going to do a lot of random access operations.
Also, keep in mind that if you use pointers and dynamically allocated arrays instead of standard containers, it's a lot easier to cause memory leaks and other problems. I know sometimes you don't have a choice, but just saying.
If you want to join arrays without copying the elements and at the same time you want to access the elements using subscript operator i.e [], then that isn't possible without writing a class which encapsulates all such functionalities.
I wrote the following class with minimal consideration, but it demonstrates the basic idea, which you can further edit if you want it to have functionalities which it's not currently having. There should be few error also, which I didn't write, just to make it look shorter, but I believe you will understand the code, and handle error cases accordingly.
template<typename T>
class joinable_array
{
std::vector<T*> m_data;
std::vector<size_t> m_size;
size_t m_allsize;
public:
joinable_array() : m_allsize() { }
joinable_array(T *a, size_t len) : m_allsize() { join(a,len);}
void join(T *a, size_t len)
{
m_data.push_back(a);
m_size.push_back(len);
m_allsize += len;
}
T & operator[](size_t i)
{
index ix = get_index(i);
return m_data[ix.v][ix.i];
}
const T & operator[](size_t i) const
{
index ix = get_index(i);
return m_data[ix.v][ix.i];
}
size_t size() const { return m_allsize; }
private:
struct index
{
size_t v;
size_t i;
};
index get_index(size_t i) const
{
index ix = { 0, i};
for(auto it = m_size.begin(); it != m_size.end(); it++)
{
if ( ix.i >= *it ) { ix.i -= *it; ix.v++; }
else break;
}
return ix;
}
};
And here is one test code:
#define alen(a) sizeof(a)/sizeof(*a)
int main() {
int a[] = {1,2,3,4,5,6};
int b[] = {11,12,13,14,15,16,17,18};
joinable_array<int> arr(a,alen(a));
arr.join(b, alen(b));
arr.join(a, alen(a)); //join it again!
for(size_t i = 0 ; i < arr.size() ; i++ )
std::cout << arr[i] << " ";
}
Output:
1 2 3 4 5 6 11 12 13 14 15 16 17 18 1 2 3 4 5 6
Online demo : http://ideone.com/VRSJI
Here's how to do it properly:
template<class T, class K1, class K2>
class JoinArray {
JoinArray(K1 &k1, K2 &k2) : k1(k1), k2(k2) { }
T operator[](int i) const { int s = k1.size(); if (i < s) return k1.operator[](i); else return k2.operator[](i-s); }
int size() const { return k1.size() + k2.size(); }
private:
K1 &k1;
K2 &k2;
};
template<class T, class K1, class K2>
JoinArray<T,K1,K2> join(K1 &k1, K2 &k2) {Â return JoinArray<T,K1,K2>(k1,k2); }
template<class T>
class NativeArray
{
NativeArray(T *ptr, int size) : ptr(ptr), size(size) { }
T operator[](int i) const { return ptr[i]; }
int size() const {Â return size; }
private:
T *ptr;
int size;
};
int main() {
int array[2] = {Â 0,1 };
int array2[2] = { 2,3 };
NativeArray<int> na(array, 2);
NativeArray<int> na2(array2, 2);
auto joinarray = join(na,na2);
}
A variable that is a pointer to a pointer must be declared as such.
This is done by placing an additional asterik in front of its name.
Hence, int **large_a = new int*[4]; Your large_a goes and find a pointer, while you've defined it as a pointer to an int. It should be defined (declared) as a pointer to a pointer variable. Just as int **large_a; could be enough.
I have an array int arr[5] that is passed to a function fillarr(int arr[]):
int fillarr(int arr[])
{
for(...);
return arr;
}
How can I return that array?
How will I use it, say I returned a pointer how am I going to access it?
In this case, your array variable arr can actually also be treated as a pointer to the beginning of your array's block in memory, by an implicit conversion. This syntax that you're using:
int fillarr(int arr[])
Is kind of just syntactic sugar. You could really replace it with this and it would still work:
int fillarr(int* arr)
So in the same sense, what you want to return from your function is actually a pointer to the first element in the array:
int* fillarr(int arr[])
And you'll still be able to use it just like you would a normal array:
int main()
{
int y[10];
int *a = fillarr(y);
cout << a[0] << endl;
}
C++ functions can't return C-style arrays by value. The closest thing is to return a pointer. Furthermore, an array type in the argument list is simply converted to a pointer.
int *fillarr( int arr[] ) { // arr "decays" to type int *
return arr;
}
You can improve it by using an array references for the argument and return, which prevents the decay:
int ( &fillarr( int (&arr)[5] ) )[5] { // no decay; argument must be size 5
return arr;
}
With Boost or C++11, pass-by-reference is only optional and the syntax is less mind-bending:
array< int, 5 > &fillarr( array< int, 5 > &arr ) {
return arr; // "array" being boost::array or std::array
}
The array template simply generates a struct containing a C-style array, so you can apply object-oriented semantics yet retain the array's original simplicity.
In C++11, you can return std::array.
#include <array>
using namespace std;
array<int, 5> fillarr(int arr[])
{
array<int, 5> arr2;
for(int i=0; i<5; ++i) {
arr2[i]=arr[i]*2;
}
return arr2;
}
$8.3.5/8 states-
"Functions shall not have a return type of type array or function, although they may have a return type of type pointer or reference to such things. There shall be no arrays of functions, although there can be arrays of pointers to functions."
int (&fn1(int (&arr)[5]))[5]{ // declare fn1 as returning refernce to array
return arr;
}
int *fn2(int arr[]){ // declare fn2 as returning pointer to array
return arr;
}
int main(){
int buf[5];
fn1(buf);
fn2(buf);
}
the answer may depend a bit on how you plan to use that function. For the simplest answer, lets decide that instead of an array, what you really want is a vector. Vectors are nice because the look for all the world like boring, ordinary values you can store in regular pointers. We'll look at other options and why you want them afterwards:
std::vector<int> fillarr( std::vector<int> arr ) {
// do something
return arr;
}
This will do exactly what you expect it to do. The upside is that std::vector takes care of making sure everything is handled cleanly. the downside is that this copies a very large amount of data, if your array is large. In fact it copies every element of the array twice. first it copies the vector so that the function can use it as a parameter. then it copies it again to return it to the caller. If you can handle managing the vector yourself, you can do things quite a bit more easily. (it may copy it a third time if the caller needs to store it in a variable of some sort to do more calculation)
It looks like what you're really trying to do is just populate a collection. if you don't have a specific reason to return a new instance of a collection, then don't. we can do it like this
void fillarr(std::vector<int> & arr) {
// modify arr
// don't return anything
}
this way you get a reference to the array passed to the function, not a private copy of it. any changes you make to the parameter are seen by the caller. You could return a reference to it if you want, but that's not really a great idea, since it sort of implies that you're getting something different from what you passed.
If you really do need a new instance of the collection, but want to avoid having it on the stack (and all the copying that entails), you need to create some kind of contract for how that instance is handled. the easiest way to do that is to use a smart pointer, which keeps the referenced instance around as long as anyone is holding onto it. It goes away cleanly if it goes out of scope. That would look like this.
std::auto_ptr<std::vector<int> > fillarr( const std::vector<int> & arr) {
std::auto_ptr<std::vector<int> > myArr(new std::vector<int>);
// do stuff with arr and *myArr
return myArr;
}
For the most part, using *myArr works identically to using a plain vanilla vector. This example also modifies the parameter list by adding the const keyword. Now you get a reference without copying it, but you can't modify it, so the caller knows it'll be the same as before the function got to it.
All of this is swell, but idiomatic c++ rarely works with collections as a whole. More normally, you will be using iterators over those collections. that would look something more like this
template <class Iterator>
Iterator fillarr(Iterator arrStart, Iterator arrEnd) {
Iterator arrIter = arrStart;
for(;arrIter <= arrEnd; arrIter++)
;// do something
return arrStart;
}
Using it looks a bit odd if you're not used to seeing this style.
vector<int> arr;
vector<int>::iterator foo = fillarr(arr.begin(), arr.end());
foo now 'points to' the beginning of the modified arr.
What's really nice about this is that it works equally well on vector as on plain C arrays and many other types of collection, for example
int arr[100];
int *foo = fillarr(arr, arr+100);
Which now looks an awful lot like the plain pointer examples given elsewhere in this question.
This:
int fillarr(int arr[])
is actually treated the same as:
int fillarr(int *arr)
Now if you really want to return an array you can change that line to
int * fillarr(int arr[]){
// do something to arr
return arr;
}
It's not really returning an array. you're returning a pointer to the start of the
array address.
But remember when you pass in the array, you're only passing in a pointer.
So when you modify the array data, you're actually modifying the data that the
pointer is pointing at. Therefore before you passed in the array, you must realise
that you already have on the outside the modified result.
e.g.
int fillarr(int arr[]){
array[0] = 10;
array[1] = 5;
}
int main(int argc, char* argv[]){
int arr[] = { 1,2,3,4,5 };
// arr[0] == 1
// arr[1] == 2 etc
int result = fillarr(arr);
// arr[0] == 10
// arr[1] == 5
return 0;
}
I suggest you might want to consider putting a length into your fillarr function like
this.
int * fillarr(int arr[], int length)
That way you can use length to fill the array to it's length no matter what it is.
To actually use it properly. Do something like this:
int * fillarr(int arr[], int length){
for (int i = 0; i < length; ++i){
// arr[i] = ? // do what you want to do here
}
return arr;
}
// then where you want to use it.
int arr[5];
int *arr2;
arr2 = fillarr(arr, 5);
// at this point, arr & arr2 are basically the same, just slightly
// different types. You can cast arr to a (char*) and it'll be the same.
If all you're wanting to do is set the array to some default values, consider using
the built in memset function.
something like:
memset((int*)&arr, 5, sizeof(int));
While I'm on the topic though. You say you're using C++. Have a look at using stl vectors. Your code is likely to be more robust.
There are lots of tutorials. Here is one that gives you an idea of how to use them.
http://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html
This is a fairly old question, but I'm going to put in my 2 cents as there are a lot of answers, but none showing all possible methods in a clear and concise manner (not sure about the concise bit, as this got a bit out of hand. TL;DR đŸ˜‰).
I'm assuming that the OP wanted to return the array that was passed in without copying as some means of directly passing this to the caller to be passed to another function to make the code look prettier.
However, to use an array like this is to let it decay into a pointer and have the compiler treat it like an array. This can result in subtle bugs if you pass in an array like, with the function expecting that it will have 5 elements, but your caller actually passes in some other number.
There a few ways you can handle this better. Pass in a std::vector or std::array (not sure if std::array was around in 2010 when the question was asked). You can then pass the object as a reference without any copying/moving of the object.
std::array<int, 5>& fillarr(std::array<int, 5>& arr)
{
// (before c++11)
for(auto it = arr.begin(); it != arr.end(); ++it)
{ /* do stuff */ }
// Note the following are for c++11 and higher. They will work for all
// the other examples below except for the stuff after the Edit.
// (c++11 and up)
for(auto it = std::begin(arr); it != std::end(arr); ++it)
{ /* do stuff */ }
// range for loop (c++11 and up)
for(auto& element : arr)
{ /* do stuff */ }
return arr;
}
std::vector<int>& fillarr(std::vector<int>& arr)
{
for(auto it = arr.begin(); it != arr.end(); ++it)
{ /* do stuff */ }
return arr;
}
However, if you insist on playing with C arrays, then use a template which will keep the information of how many items in the array.
template <size_t N>
int(&fillarr(int(&arr)[N]))[N]
{
// N is easier and cleaner than specifying sizeof(arr)/sizeof(arr[0])
for(int* it = arr; it != arr + N; ++it)
{ /* do stuff */ }
return arr;
}
Except, that looks butt ugly, and super hard to read. I now use something to help with that which wasn't around in 2010, which I also use for function pointers:
template <typename T>
using type_t = T;
template <size_t N>
type_t<int(&)[N]> fillarr(type_t<int(&)[N]> arr)
{
// N is easier and cleaner than specifying sizeof(arr)/sizeof(arr[0])
for(int* it = arr; it != arr + N; ++it)
{ /* do stuff */ }
return arr;
}
This moves the type where one would expect it to be, making this far more readable. Of course, using a template is superfluous if you are not going to use anything but 5 elements, so you can of course hard code it:
type_t<int(&)[5]> fillarr(type_t<int(&)[5]> arr)
{
// Prefer using the compiler to figure out how many elements there are
// as it reduces the number of locations where you have to change if needed.
for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
{ /* do stuff */ }
return arr;
}
As I said, my type_t<> trick wouldn't have worked at the time this question was asked. The best you could have hoped for back then was to use a type in a struct:
template<typename T>
struct type
{
typedef T type;
};
typename type<int(&)[5]>::type fillarr(typename type<int(&)[5]>::type arr)
{
// Prefer using the compiler to figure out how many elements there are
// as it reduces the number of locations where you have to change if needed.
for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
{ /* do stuff */ }
return arr;
}
Which starts to look pretty ugly again, but at least is still more readable, though the typename may have been optional back then depending on the compiler, resulting in:
type<int(&)[5]>::type fillarr(type<int(&)[5]>::type arr)
{
// Prefer using the compiler to figure out how many elements there are
// as it reduces the number of locations where you have to change if needed.
for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
{ /* do stuff */ }
return arr;
}
And then of course you could have specified a specific type, rather than using my helper.
typedef int(&array5)[5];
array5 fillarr(array5 arr)
{
// Prefer using the compiler to figure out how many elements there are
// as it reduces the number of locations where you have to change if needed.
for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
{ /* do stuff */ }
return arr;
}
Back then, the free functions std::begin() and std::end() didn't exist, though could have been easily implemented. This would have allowed iterating over the array in a safer manner as they make sense on a C array, but not a pointer.
As for accessing the array, you could either pass it to another function that takes the same parameter type, or make an alias to it (which wouldn't make much sense as you already have the original in that scope). Accessing a array reference is just like accessing the original array.
void other_function(type_t<int(&)[5]> x) { /* do something else */ }
void fn()
{
int array[5];
other_function(fillarr(array));
}
or
void fn()
{
int array[5];
auto& array2 = fillarr(array); // alias. But why bother.
int forth_entry = array[4];
int forth_entry2 = array2[4]; // same value as forth_entry
}
To summarize, it is best to not allow an array decay into a pointer if you intend to iterate over it. It is just a bad idea as it keeps the compiler from protecting you from shooting yourself in the foot and makes your code harder to read. Always try and help the compiler help you by keeping the types as long as possible unless you have a very good reason not to do so.
Edit
Oh, and for completeness, you can allow it to degrade to a pointer, but this decouples the array from the number of elements it holds. This is done a lot in C/C++ and is usually mitigated by passing the number of elements in the array. However, the compiler can't help you if you make a mistake and pass in the wrong value to the number of elements.
// separate size value
int* fillarr(int* arr, size_t size)
{
for(int* it = arr; it != arr + size; ++it)
{ /* do stuff */ }
return arr;
}
Instead of passing the size, you can pass the end pointer, which will point to one past the end of your array. This is useful as it makes for something that is closer to the std algorithms, which take a begin and and end pointer, but what you return is now only something that you must remember.
// separate end pointer
int* fillarr(int* arr, int* end)
{
for(int* it = arr; it != end; ++it)
{ /* do stuff */ }
return arr;
}
Alternatively, you can document that this function will only take 5 elements and hope that the user of your function doesn't do anything stupid.
// I document that this function will ONLY take 5 elements and
// return the same array of 5 elements. If you pass in anything
// else, may nazal demons exit thine nose!
int* fillarr(int* arr)
{
for(int* it = arr; it != arr + 5; ++it)
{ /* do stuff */ }
return arr;
}
Note that the return value has lost it's original type and is degraded to a pointer. Because of this, you are now on your own to ensure that you are not going to overrun the array.
You could pass a std::pair<int*, int*>, which you can use for begin and end and pass that around, but then it really stops looking like an array.
std::pair<int*, int*> fillarr(std::pair<int*, int*> arr)
{
for(int* it = arr.first; it != arr.second; ++it)
{ /* do stuff */ }
return arr; // if you change arr, then return the original arr value.
}
void fn()
{
int array[5];
auto array2 = fillarr(std::make_pair(&array[0], &array[5]));
// Can be done, but you have the original array in scope, so why bother.
int fourth_element = array2.first[4];
}
or
void other_function(std::pair<int*, int*> array)
{
// Can be done, but you have the original array in scope, so why bother.
int fourth_element = array2.first[4];
}
void fn()
{
int array[5];
other_function(fillarr(std::make_pair(&array[0], &array[5])));
}
Funny enough, this is very similar to how std::initializer_list work (c++11), but they don't work in this context.
to return an array from a function , let us define that array in a structure;
So it looks something like this
struct Marks{
int list[5];
}
Now let us create variables of the type structure.
typedef struct Marks marks;
marks marks_list;
We can pass array to a function in the following way and assign value to it:
void setMarks(int marks_array[]){
for(int i=0;i<sizeof(marks_array)/sizeof(int);i++)
marks_list.list[i]=marks_array[i];
}
We can also return the array. To return the array , the return type of the function should be of structure type ie marks. This is because in reality we are passing the structure that contains the array. So the final code may look like this.
marks getMarks(){
return marks_list;
}
the Simplest way to do this ,is to return it by reference , even if you don't write
the '&' symbol , it is automatically returned by reference
void fillarr(int arr[5])
{
for(...);
}
int *fillarr(int arr[])
You can still use the result like
int *returned_array = fillarr(some_other_array);
if(returned_array[0] == 3)
do_important_cool_stuff();
As above mentioned paths are correct. But i think if we just return a local array variable of a function sometimes it returns garbage values as its elements.
in-order to avoid that i had to create the array dynamically and proceed. Which is something like this.
int* func()
{
int* Arr = new int[100];
return Arr;
}
int main()
{
int* ArrResult = func();
cout << ArrResult[0] << " " << ArrResult[1] << endl;
return 0;
}
Source: https://www.tutorialspoint.com/cplusplus/cpp_return_arrays_from_functions.htm
C++ does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.
If you want to return a single-dimension array from a function, you would have to declare a function returning a pointer as in the following example:
int * myFunction() {
.
.
.
}
C++ does not advocate to return the address of a local variable to outside of the function so you would have to define the local variable as static variable.
Applying these rules on the current question, we can write the program as follows:
# include <iostream>
using namespace std;
int * fillarr( );
int main ()
{
int *p;
p = fillarr();
for ( int i = 0; i < 5; i++ )
cout << "p[" << i << "] : "<< *(p + i) << endl;
return 0;
}
int * fillarr( )
{
static int arr[5];
for (int i = 0; i < 5; ++i)
arr[i] = i;
return arr;
}
The Output will be:
p[0]=0
p[1]=1
p[2]=2
p[3]=3
p[4]=4
template<typename T, size_t N>
using ARR_REF = T (&)[N];
template <typename T, size_t N>
ARR_REF<T,N> ArraySizeHelper(ARR_REF<T,N> arr);
#define arraysize(arr) sizeof(ArraySizeHelper(arr))
and what about:
int (*func())
{
int *f = new int[10] {1,2,3};
return f;
}
int fa[10] = { 0 };
auto func2() -> int (*) [10]
{
return &fa;
}
Actually when you pass an array inside a function, the pointer to the original array is passed in the function parameter and thus the changes made to the array inside that function is actually made on the original array.
#include <iostream>
using namespace std;
int* func(int ar[])
{
for(int i=0;i<100;i++)
ar[i]=i;
int *ptr=ar;
return ptr;
}
int main() {
int *p;
int y[100]={0};
p=func(y);
for(int i=0;i<100;i++)
cout<<i<<" : "<<y[i]<<'\n';
}
Run it and you will see the changes
And why don't "return" the array as a parameter?
fillarr(int source[], size_t dimSource, int dest[], size_t dimDest)
{
if (dimSource <= dimDest)
{
for (size_t i = 0; i < dimSource; i++)
{
//some stuff...
}
}
else
{
//some stuff..
}
}
or..in a simpler way (but you have to know the dimensions...):
fillarr(int source[], int dest[])
{
//...
}
A simple and elaborate example, so that I can refer here if I forget the concept and need help.
#include <iostream>
using namespace std;
int *ReturnArray(int arr[], int size)
{
static int MinMax[2] = {0, 0}; // must use static, else address would be deleted after the return is reached
MinMax[0] = arr[0];
MinMax[1] = arr[size - 1];
return MinMax;
}
int main()
{
int arr[] = {1, 2, 3};
int size = sizeof(arr) / sizeof(*arr);
int *ans; // pointer to hold returned array
ans = ReturnArray(arr, size); // only pointer can receive the return, not an array
cout << "Min: " << ans[0] << " Max: " << ans[1];
return 0;
}
Here's a full example of this kind of problem to solve
#include <bits/stdc++.h>
using namespace std;
int* solve(int brr[],int n)
{
sort(brr,brr+n);
return brr;
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int *a=solve(arr,n);
for(int i=0;i<n;i++)
{
cout<<a[i]<<endl;
}
return 0;
}
i used static array so that while returning array it should not throw error as you are returning address of local variable...
so now you can send any locally created variable from function by making it as static...as it works as global variable....
#include<iostream>
using namespace std;
char *func(int n)
{
// char a[26]; /*if we use this then an error will occur because you are
// returning address of a local variable*/
static char a[26];
char temp='A';
for(int i=0;i<n;i++)
{
a[i]=temp;temp++;
}
return a;
}
int main()
{
int n=26;
char *p=func(n);
for(int i=0;i<n;i++)
cout<<*(p+i)<<" ";
//or you can also print like this
for(int i=0;i<n;i++)
cout<<p[i]<<" ";
}
Just define a type[ ] as return value, like:
private string[] functionReturnValueArray(string one, string two)
{
string[] x = {one, two};
x[0] = "a";
x[1] = "b";
return x;
}
.
.
.
function call:
string[] y;
y = functionReturnValueArray(stringOne, stringTwo)