How to create a 2D array in C++ using this specific container - c++

I'm trying to port a
int a[][]
from Java to C++. I'm using this class as a container ArrayRef for ints because it handles references, and the project uses it extensively. In the AbstractReader class I declared
const ArrayRef<int> START_END_PATTERN_;
const ArrayRef<int> MIDDLE_PATTERN_;
const ArrayRef<ArrayRef<int> > L_PATTERNS_;
const ArrayRef<ArrayRef<int> > L_AND_G_PATTERNS_;
and
static int START_END_PATTERN[];
static int MIDDLE_PATTERN[];
static int L_PATTERNS[10][4];
static int L_AND_G_PATTERNS[20][4];
Note the trailing underscore to differentiate the two variables.
I'm not sure what to do in order to initialize the two-dimensional ArrayRef. What I'm posting here will segfault because those ArrayRefs are being allocated on the stack. Anybody have a clever way to do this?
The only way I've actually managed to get it to work is using a ArrayRef< Ref<ArrayRef<int> > > by making ArrayRef inherit from Counted, which is basically a class that allows for Reference Counting in C++. But in order to access the elements I hen have to do something like *(foo[i])[j], which is slightly nastier than foo[i][j].
int AbstractReader::L\_AND\_G_PATTERNS[20][4] = {
{3, 2, 1, 1}, // 0
{2, 2, 2, 1}, // 1
{2, 1, 2, 2}, // 2
{1, 4, 1, 1}, // 3
{1, 1, 3, 2}, // 4
{1, 2, 3, 1}, // 5
{1, 1, 1, 4}, // 6
{1, 3, 1, 2}, // 7
{1, 2, 1, 3}, // 8
{3, 1, 1, 2}, // 9
// G patterns
{1, 1, 2, 3}, // 0
{1, 2, 2, 2}, // 1
{2, 2, 1, 2}, // 2
{1, 1, 4, 1}, // 3
{2, 3, 1, 1}, // 4
{1, 3, 2, 1}, // 5
{4, 1, 1, 1}, // 6
{2, 1, 3, 1}, // 7
{3, 1, 2, 1}, // 8
{2, 1, 1, 3} // 9
};
AbstractReader::AbstractReader()
: decodeRowStringBuffer_(ostringstream::app),
START_END_PATTERN_(START_END_PATTERN, 3),
MIDDLE_PATTERN_(MIDDLE_PATTERN, 5),
L_PATTERNS_(10),
L_AND_G_PATTERNS_(20) {
for (int i = 0; i < 20; i++) {
if (i < 10) {
L_PATTERNS_[i] = ArrayRef<int> ((L_PATTERNS[i]), 4);
}
ArrayRef<int> lgpattern((L_AND_G_PATTERNS[i]), 4);
L_AND_G_PATTERNS_[i] = lgpattern;
}
}

What you have should be safe. The (stack allocated) ArrayRefs create heap allocated Arrays to back them, and then share those Arrays.
Edit: Thanks for posting Counted. Took a bit of work, but I think I see what's going on.
Solution: Don't declare L_PATTERNS_ or L_AND_G_PATTERNS_ as const. Alternately, const_cast to get the desired operator[]. E.g.
const_cast<ArrayRef<ArrayRef<int> > &>(L_PATTERNS_)[i] = ArrayRef<int> ((L_PATTERNS[i]), 4);
Rationale:
In AbstractReader, you declare:
const ArrayRef<ArrayRef<int> > L_PATTERNS_;
Then in its constructor, you attempt an assignment:
AbstractReader::AbstractReader() :
{
...
L_PATTERNS_[i] = ArrayRef<int> ((L_PATTERNS[i]), 4);
...
}
Since L_PATTERNS_ is const, L_PATTERNS_[i] invokes a method from ArrayRef<ArrayRef<int> >:
T operator[](size_t i) const { return (*array_)[i]; }
This returns a brand new copy of what was at L_PATTERNS_[i]. The assignment then occurs (into a temporary), leaving the original unchanged. When you later go back to access L_PATTERNS_[xxx], you're looking at the original, uninitialized value (which is a NULL reference/pointer). Thus the segfault.
Somewhat surprising is that ArrayRef even allows this assignment. Certainly it breaks the "Principle of Least Surprise". One would expect the compiler to issue an error. To make sure that the compiler is more helpful in the future, we need to give a slightly different definition of ArrayRef's operator[] const (Array.h:121), such as:
const T operator[](size_t i) const { return (*array_)[i]; }
or perhaps (with caveats):
const T& operator[](size_t i) const { return (*array_)[i]; }
After making either change, the compiler disallows allow the assignment. GCC, for example, reports:
error: passing 'const common::ArrayRef<int>' as 'this' argument of 'common::ArrayRef<T>& common::ArrayRef<T>::operator=(const common::ArrayRef<T>&) [with T = int]' discards qualifiers

Causes may be several. For instance, you don't include in your paste the "Counted" class, and at some point, a->retain() is called (line 130). This method is not shown.

Related

Call a function with a part of a larger array

I'm refactoring some code and have decided that I would like to merge a two-dimensional array into a one-dimensional, larger array. The problem is now that I have some functions which take those smaller arrays as parameter and I would prefer to keep their signatures. Is it possible to call a function with only a part of a larger array?
f1 is what I currently have and f2 is what it should look like after refactoring:
#include <array>
void func(std::array<int const, 5> const& arr, int i);
void f1() {
static std::array<std::array<int const, 5>, 2> const arr{{{1, 2, 3, 4, 5}, {6, 7, 8, 9, 0}}};
func(arr[0], 0);
func(arr[1], 1);
}
void f2() {
static std::array<int const, 10> const arr{1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
//TODO: call func with first and last 5 elements.
}
If you change your function to to take a range of elements as Peter commented, this becomes trivial. You would pass arr.begin() and arr.begin() + 5 for the first array and arr.begin() + 5, arr.end() for the second.
void func(int* b, int* e, int i);
You can also take a span just to make things cleaner. Here gsl::span is used but you can write your own if you want:
#include <gsl/span>
void func(gsl::span<int> s, int i);
static std::array<int const, 10> const arr{1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
func( {arr.begin(), arr.begin() + 5}, 0 );
func( {arr.begin() + 5, arr.end()}, 1 );

Iteratively calculate the power set of a set or vector

While there are plenty of examples on how to generate the actual power set of a set, I can't find anything about iteratively (as in std::iterator) generating the power set. The reason why I would appreciate such an algorithm is the size of my base set. As the power set of a n-element set has 2^n elements, I would quickly run out of memory when actually computing the set. So, is there any way to create an iterator for the power set of a given set? Is it even possible?
If it would be easier, an iterator that creates sets of ints would be fine - I could use them as indices for the actual set/vector.
As I actually work on a std::vector, random access would be possible if neccessary
Using for_each_combination from Combinations and Permutations one can easily iterate through all members of the power set of a std::vector<AnyType>. For example:
#include <vector>
#include <iostream>
#include "../combinations/combinations"
int
main()
{
std::vector<int> v{1, 2, 3, 4, 5};
std::size_t num_visits = 0;
for (std::size_t k = 0; k <= v.size(); ++k)
for_each_combination(v.begin(), v.begin()+k, v.end(),
[&](auto first, auto last)
{
std::cout << '{';
if (first != last)
{
std::cout << *first;
for (++first; first != last; ++first)
std::cout << ", " << *first;
}
std::cout << "}\n";
++num_visits;
return false;
});
std::cout << "num_visits = " << num_visits << '\n';
}
This visits each power set member of this vector, and executes the functor, which simply counts the number of visits and prints out the current power set:
{}
{1}
{2}
{3}
{4}
{5}
{1, 2}
{1, 3}
{1, 4}
{1, 5}
{2, 3}
{2, 4}
{2, 5}
{3, 4}
{3, 5}
{4, 5}
{1, 2, 3}
{1, 2, 4}
{1, 2, 5}
{1, 3, 4}
{1, 3, 5}
{1, 4, 5}
{2, 3, 4}
{2, 3, 5}
{2, 4, 5}
{3, 4, 5}
{1, 2, 3, 4}
{1, 2, 3, 5}
{1, 2, 4, 5}
{1, 3, 4, 5}
{2, 3, 4, 5}
{1, 2, 3, 4, 5}
num_visits = 32
The syntax I've used above is C++14. If you have C++11, you will need to change:
[&](auto first, auto last)
to:
[&](std::vector<int>::const_iterator first, std::vector<int>::const_iterator last)
And if you are in C++98/03, you will have to write a functor or function to replace the lambda.
The for_each_combination function allocates no extra storage. This is all done by swapping members of the vector into the range [v.begin(), v.begin()+k). At the end of each call to for_each_combination the vector is left in its original state.
If for some reason you want to "exit" the for_each_combination early, simply return true instead of false.

How to filter vector elements relative to other ones?

I a vector of vectors, each representing a a set (in the mathematical sense). For example:
{{1, 3}, {4, 9, 14}, {1, 3}, {1, 4, 8, 9, 10, 14, 16}, {1, 3, 9}, {4, 9, 17, 22}}
I want to make the most efficient C++ possible function capable of filtering (in place, if possible) the vector in order to remove every item that contains another.
For example, here:
{1, 3} is contained by {1, 3} and {1, 3, 9}
{4, 9, 14} is contained by {1, 4, 8, 9, 10, 14, 16}
The resulting vector would then be:
{{1, 3}, {4, 9, 14}, {4, 9, 17, 22}}
As I'm beginning with C++ don't really have any clue of how to do this efficiently. I found, on other answers here, the erase / remove idiom, which doesn't seem to be very appropriate here, except by passing erase a closure as predicate. Which doesn't seem really idiomatic in C++.
Please note that keeping the original ordering doesn't matter, nor does the ordering of values inside each set.
Given what I learnt so far, thanks to your very helpful comments, the solution I came up with is:
struct std::vector<size_t> colset;
bool less_colsets(const colset& a, const colset& b) {
return a.size() < b.size();
}
void sort_colsets(std::list<colset>& l) {
l.sort(less_colsets);
}
void strip_subsets(std::list<colset>& l) {
sort_colsets(l);
for (std::list<colset>::iterator i = l.begin(); i != l.end(); ++i) {
std::list<colset>::iterator j = next(i, 1);
while (j != l.end()) {
if (includes((*j).begin(), (*j).end(), (*i).begin(), (*i).end())) {
j = l.erase(j);
}
else {
++j;
}
}
}
}
Note that I replaced the outermost std::vector by std::list which is much more optimised for element removal anywhere.
This seems to work as expected, though I'd need some more tests to prove this. The next step will be to use a more efficient comparison function than includes, which would take into account the fact that each vector is lexically ordered (which the program guarantees). I'll try this tomorrow.
Edit: Looks like std::includes already takes care of this fact. YAY!
Thanks everybody.

2D int array in C++

So I want to initialize an int 2d array very quickly, but I can't figure out how to do it. I've done a few searches and none of them say how to initialize a 2D array, except to do:
int [SOME_CONSTANT][ANOTHER_CONSTANT] = {{0}};
Basically, I've got 8 vertices, and I'm listing the 4 vertices of each face of a cube in an array. I've tried this:
int[6][4] sides = {{0, 1, 2, 3}, {4, 5, 6, 7}, {0, 4, 7, 3}, {7, 6, 2, 3}, {5, 1, 2, 6}, {0, 1, 5, 4}};
But that tells me that there's an error with 'sides', and that it expected a semi-colon. Is there any way to initialize an array quickly like this?
Thanks!
You have the [][] on the wrong side. Try this:
int sides[6][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {0, 4, 7, 3}, {7, 6, 2, 3}, {5, 1, 2, 6}, {0, 1, 5, 4}};
Keep in mind that what you really have is:
int **sides
(A pointer to a pointer of ints). It's sides that has the dimensions, not the int. Therefore, you could also do:
int x, y[2], z[3][4], ...;
I think You meant to say
int sides[6][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {0, 4, 7, 3}, {7, 6, 2, 3}, {5, 1, 2, 6}, {0, 1, 5, 4}};
int array[n][m] behaves just like int array[n * m].
In fact, array[i][j] = array[m * i + j] for all i, j.
So int array[2][3] = {1, 2, 3, 4, 5, 6}; is a valid declaration and, for example,
array[1][1] = array[3 * 1 + 1] = array[4] = 5.
int sides[6][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {0, 4, 7, 3}, {7, 6, 2, 3}, {5, 1, 2, 6}, {0, 1, 5, 4}};
I'm not a regular c++ programmer but I looks like int sides[6][4] seems to compile while int[6][4] sides fails. Languages like C# lets you have the [][] on either sides but apparently c++ doesn't.
int sides[6][4] = ... should do the trick. This sounds like you may be coming from a Java (or other language) background so I do recommend a C++ book The Definitive C++ Book Guide and List for more details.
Yes, the intended type of sides is int[6][4], but C++ has confusing syntax sometimes. The way to declare said array is:
int sides[6][4] = {/*stuff*/};
You run into this with function pointers too, but even worse:
int (*myfuncptr)(int); //creates a function pointer called myfuncptr
With function pointers though, you can do this:
typedef int (*func_ptr_type)(int);
func_ptr_type myfuncptr;
Unfortunately, there's no corresponding magic trick for arrays.
i would make a array outside of function and just assign it it to your local. this will very likely invoke memcpy or just inline memory copying loop
this is the fastest you can get

swapping 2 numbers in 2 dimensional array

My question is as follows:
Refer to the following array declaration in the main():
const int size = 4;
int x[size][size] = {{1, 2, 3, 4}, {5, 6, 7, 8},
{9, 8, 7, 3}, {2, 1, 7, 1}};
Write a function SwapRows() to swap two rows of the above 2D array. For
example, if the function has been called to swap the first and the second rows of the
above 2D array then the result would be that the first row now becomes {5, 6, 7, 8}
and the second row now becomes {1, 2, 3, 4}. The function receives as parameter the
2D array, the size of the array, and two integers to indicate the rows to swap.
Help,,how can i go about this?????
Note: Using C++ Language
Pseudo code:
SwapRows(x[size][size], row0, row1, size)
for col = 0 to size - 1 do
temp = x[row0][col]
x[row0][col] = x[row1][col]
x[row1][col] = temp
Now all you need to do is convert the pseudo code into C++, then test, debug and document it.
#include <algorithm>
void SwapRows(int arr[][4], int r1, int r2)
{
std::swap(arr[r1],arr[r2]);
}