1

I have a 2D Array C[100][10],I want to split it column by column and insert in 1D Array like below :

C[100][10] split to C[0:100][0] , C[0:100][1] , ... , C[0:100][10] and the insert splited arrays to 1D array like : A[100] =C[0:100][0]

I can do all of that with for-loops but take long time and time is critical for my project. is there any way to solve this problem excluding for-loop

10
  • 2
    Is this C++ or C? The solution may be very different in C and C++. Commented Dec 4, 2018 at 8:53
  • You only need to do for in for. Does this really spend lots of time? Commented Dec 4, 2018 at 8:53
  • 2
    You should store the array as C[10][100]. Then you can access each subarray with C[i]. This kind of memory access should be a bit faster. Commented Dec 4, 2018 at 8:53
  • 1
    Quote: "I can do all of that with for-loops ..." Then post that code so that we can see what you are doing. That will also make the question more clear. Currently we don't even know the type of data. Commented Dec 4, 2018 at 8:56
  • 1
    @Alexanov ok, C++ then ... (C tag removed). You still need to post your current "slow" solution Commented Dec 4, 2018 at 9:17

1 Answer 1

2

You should use an array of sub arrays like:

std::array<std::array<TYPE, 100>, 10> C;

Then the elements of each sub array are consecutively stored in memory and operations are faster. std::array provides copy operator

std::array<TYPE, 100> A = C[i];
Sign up to request clarification or add additional context in comments.

10 Comments

Thank you,your solution is very useful but if i want to access to one column how can i do that?
@Alexanov If you can prepare the above array of array, you can also prepare vector of vector. Then you can split the matrix within ~1 msec by std::move like this. Why not do that ?
@Hiroki I saw your solution, can you say me how can I access to one row or column with vector? give me an example if it is possible for you , to show vector like c[0:100][1] or c[1][0:10]
@Alexanov _1th_column, ..., _10th_column in my answer are all std::vector<Foo>. Thus we can access each element of each column like this. Could you please point it out if I misunderstand your problem :).
@Alexanov How about this? I defined a simple matrix class withstd::vector and column-major instead of std::valarray. This matrix class has member functions to get accessors to rows and columns without object-copy. This is my quick implementation and please be careful with dangling :). Simple wrapping by lambdas also works.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.