Printing the elements in multidemensional array - C++ - c++

Help me to get correct result with this cplusplus program.
With this code I'm trying to print all the elements in array 'arr' with each inner array on it's own line.
Code:
using namespace std;
int main()
{
int arr[3][4] = {
{1,2,3,4},{5,6,7,8},{9,10,11,12}
};
for (auto p = begin(arr); arr != end(arr); ++p) {
for (auto q = begin(*p); q != end(*p); ++q) {
cout << *q << " ";
}
}
cout << endl;
keep_window_open();
return 0;
}
But when I execute this code the compiler shows me a bunch of memory addresses instead elements in array 'arr'. Did I do anything wrong with that code? And I'm using Visual Studio 2015 for programming, In case if you want to know.

try this:
int ia[3][4] = {
{ 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }
};
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
cout << ia[i][j] << endl;
}
}

Just for Fun
#include <iostream>
#include <array>
int main(void)
{
std::array<std::array<int, 4>, 3> const array = {{{1,2,3,4},{5,6,7,8},{9,10,11,12}}};
if (array.begin() != array.end()) {
auto itarray = array.begin();
if (itarray->begin() != itarray->end()) { {
auto itsubarray = itarray->begin();
std::cout << *itsubarray;
for (itsubarray = itsubarray + 1; itsubarray != itarray->end(); itsubarray++) {
std::cout << " " << *itsubarray;
} }
for (itarray = itarray + 1; itarray != array.end(); itarray++) {
for (int elem : *itarray) {
std::cout << " " << elem;
}
}
}
}
std::cout << std::endl;
return 0;
}

Or if you wish to use iterators:
#include <iterator>
using std::endl;
using std::begin;
using std::end;
using std::cout;
int main() {
int arr[3][4] = { { 1,2,3,4 },{ 5,6,7,8 },{ 9,10,11,12 } };
for (auto p = begin(arr); p != end(arr); ++p) {
for (auto q = begin(*p); q != end(*p); ++q) {
cout << *q << " ";
}
}
cout << endl;
return 0;
}
The change is in the first for loop where you had arr != end(arr), but you wanted p != end(arr). And if you ever change the length of your array this loop will still work.

Related

How does this loop work (Check Duplicate in array loop)

Beginner programmer here can someone please explain to me how this loop works.
How can the loop detect the duplicate element in the array?
sorry for the simple question.
#include <iostream>
using namespace std;
int main()
{
int num[5];
int numSize = sizeof(num) / sizeof(num[0]);
for(int i = 0; i < numSize; i++)
{
cout << "Enter number : ";
cin >> num[i];
if(i >= 0)
{
for(int j = 0 ; j < numSize; j++)
{
if(num[i] == num[j] && (i != j))
{
i--;
j++;
}
}
}
}
for(int p = 0; p < numSize; p++)
cout << num[p] << " ";
}
Avoid indexing when it is possible. It is not final solution but it may show you right direction.
#include <iostream>
#include <algorithm>
int main()
{
int num[] = { 0, 5, 6, 8, 0, 2, 5, 8 };
std::sort(std::begin(num), std::end(num));
auto it = std::begin(num);
while(1) {
it = std::adjacent_find(it, std::end(num));
if(it != std::end(num)) {
std::cout << "Double pairs " << *it << " and " << *(it+1) << std::endl;
++it;
}
else {
break;
}
}
return 0;
}
Output:
Double pairs 0 and 0
Double pairs 5 and 5
Double pairs 8 and 8

bin_search return an array with 15 elements in C++

I would like to create an array i_array with 15 elements and rate every element with formula
a = sin((Pi * (i - 7)) / 15)
and return it.
#include <cmath>
#include <cstddef>
#include <iostream>
void sinuss(double (&arr)[15]) {
for (int i = 0; i < 15; ++i) {
arr[i] = std::sin((M_PI * (i - 7)) / 15);
std::cout << arr[i] << ' ';
}
std::cout << '\n';
}
void modBinSearch(double arr[], double start, double end){
if (start > end){
return -1;
}
const int mitte = start +((end-start)/2);
if(arr[mitte] == 0.0){
return mitte;
}
else if(arr[mitte] > 0.0){
return modBinSearch(arr[], start, mitte-1);
}
return modBinSearch(arr, mitte+1,end);
}
int main() {
double i_array[15];
sinuss(i_array);
for (int i = 0; i < 15; ++i) {
std::cout << i_array[i] << ' ';
}
std::cout << '\n';
int arr[] = sinuss(i_array);
int n = sizeof(arr)/sizeof(arr[0]);
int result = modBinSearch(arr, 0, n-1);
return 0;
}
I have no idea. I don't know what my error is.
I am new in C++, because it I have a lot of problem with it:(
In my function sinuss() I should return rated elements as array and in function modBinSearch() I should return the least element who not smaller as 0.0 is. But my programm is wrong :(
There are usually better ways to write loops that use a sequence of floating-point values, such as using an integer for loop control and calculating the floating-point value from the integer in each iteration. (Alternatively, you can use a floating-point object for loop control but take care to use only integer values for the loop expressions.)
Define a type of what you desire. Suggesting a std::array<double,15>. It makes coding what you want more natural.
#include <array>
#include <iostream>
#include <cmath>
using namespace std;
using ArrOf15Dbl = array<double, 15>;
ArrOf15Dbl sinuss() {
ArrOf15Dbl i_array;
for (int i = 0; i < 15; ++i) {
i_array[i] = sin((M_PI * (i - 7)) / 15);
cout << i_array[i] << ' ';
}
cout << '\n';
return i_array;
}
int main() {
ArrOf15Dbl x = sinuss();
for (auto i : x) {
cout << i << ' ';
}
cout << '\n';
}
But returning arrays from a function is not possible with C++98/03. So one solution is to allocate the needed memory dynamically, but don't forget to release it later!
#include <cmath>
#include <cstddef>
#include <iostream>
int const kArrSiz = 15;
// OBS: caller assumes ownership of array pointer!
// Must be deleted with "delete [] foobar;"
double* sinuss() {
double* i_array = new double[kArrSiz];
for (int i = 0; i < kArrSiz; ++i) {
i_array[i] = std::sin((M_PI * (i - 7)) / kArrSiz);
std::cout << i_array[i] << ' ';
}
std::cout << '\n';
return i_array;
}
int main() {
double* x = sinuss();
for (int i = 0; i < kArrSiz; ++i) {
std::cout << x[i] << ' ';
}
std::cout << '\n';
delete [] x;
return EXIT_SUCCESS;
}
But with a change of interface to your function, it can be made safer by requiring the caller to allocate the array and your function instead fills it with your required values.
void sinuss(double (&arr)[15]) {
for (int i = 0; i < 15; ++i) {
arr[i] = std::sin((M_PI * (i - 7)) / 15);
std::cout << arr[i] << ' ';
}
std::cout << '\n';
}
int main() {
double i_array[15];
sinuss(i_array);
for (int i = 0; i < 15; ++i) {
std::cout << i_array[i] << ' ';
}
std::cout << '\n';
return EXIT_SUCCESS;
}

How to use the C++ std to count leading and trailing zeros of a collection of integers

Could we replace a loop by calls to the standard library to count the leading zeros in a collection of integers?
I am learning std but can't figure a way to use something like count or count_if for this situation since I need to know the previous element.
int collection[] = { 0,0,0,0,6,3,1,3,5,0,0 };
auto collectionSize = sizeof(collection) / sizeof(collection[0]);
auto countLeadingZeros = 0;
for (auto idx = 0; idx < collectionSize; idx++)
{
if (collection[idx] == 0)
countLeadingZeros++;
else
break;
}
// leading zeros: 4*0
cout << "leading zeros: " << countLeadingZeros << "*0" << endl;
I have a similar case to count the trailing zeros in the same collection.
auto countTrailingZeros = 0;
for (auto idx = collectionSize - 1; idx >= 0; idx--)
{
if (collection[idx] == 0)
countTrailingZeros++;
else
break;
}
// trailing zeros: 2*0
cout << "trailing zeros: " << countTrailingZeros << "*0" << endl;
Below a complete example that builds.
#include <iostream>
using namespace std;
int main()
{
int collection[] = { 0,0,0,0,6,3,1,3,5,0,0 };
auto collectionSize = sizeof(collection) / sizeof(collection[0]);
auto countLeadingZeros = 0;
for (auto idx = 0; idx < collectionSize; idx++)
{
if (collection[idx] == 0)
countLeadingZeros++;
else
break;
}
cout << "leading zeros: " << countLeadingZeros << "*0" << endl;
auto countTrailingZeros = 0;
for (auto idx = collectionSize - 1; idx >= 0; idx--)
{
if (collection[idx] == 0)
countTrailingZeros++;
else
break;
}
cout << "trailing zeros: " << countTrailingZeros << "*0" << endl;
return 0;
}
One way would be to use std::find_if.
auto countLeadingZeros = std::find_if(
std::begin(collection), std::end(collection),
[](int x) { return x != 0; }) - std::begin(collection);
auto countTrailingZeros = std::find_if(
std::rbegin(collection), std::rend(collection),
[](int x) { return x != 0; }) - std::rbegin(collection);
You can use std::find_if and reverse iterators
#include <iostream>
#include <algorithm>
#include <vector>
using std::cout;
using std::endl;
int main() {
auto vec = std::vector<int>{0, 0, 1, 0};
auto first_non_zero = std::find_if(vec.cbegin(), vec.cend(),
[](auto integer) {
return integer != 0;
});
auto first_non_zero_end = std::find_if(vec.crbegin(), vec.crend(),
[](auto integer) {
return integer != 0;
});
auto leading_zeros = std::distance(vec.cbegin(), first_non_zero);
auto trailing_zeros = std::distance(vec.crbegin(), first_non_zero_end);
cout << "leading zeros " << leading_zeros << endl;
cout << "trailing zeros " << trailing_zeros << endl;
}
You can use either the standard algorithm std::find_if or the standard algorithm std::find_if_not.
Here is a demonstrative program that uses the standard algorithm std::find_if_not.
#include <iostream>
#include <functional>
#include <iterator>
#include <algorithm>
int main()
{
int collection[] = { 0, 0, 0, 0, 6, 3, 1, 3, 5, 0, 0 };
std::size_t n = 0;
auto first = std::find_if_not(std::begin(collection),
std::end(collection),
std::bind2nd(std::equal_to<int>(), 0));
n += std::distance(std::begin(collection), first);
auto last = std::find_if_not(std::rbegin(collection),
std::reverse_iterator<int *>( first ),
std::bind2nd(std::equal_to<int>(), 0));
n += std::distance(std::rbegin(collection), last );
std::cout << n << std::endl;
return 0;
}
The program output is
6

C++ multiple returns from single function

still pretty new to C++.
Had to write a function in class to count the number of each digit in a multi-dimensional array.
Now I didn't think you could return multiple int values from a single called function and then use all of these returns in a text based answer, so I attempted to return a different value depending on the value requested as parameter for each digit.
The code below is unnecessarily long and I'm still receiving the following errors.
main-1-3.cpp: In function 'int main()':
main-1-3.cpp:12:21: error: too few arguments to function 'int
count_numbers(int(*)[4], int)'
count_numbers(array);
^
main-1-3.cpp:7:12: note: declared here
extern int count_numbers(int array[4][4], int);
With a bit of debugging I could likely fix up these compile errors, but I feel like my method is extremely convoluted and was wondering if it were possible to call the function as:
count_number(array[4][4])
(Removing the need for the Q parameter) and then have count_numbersreturn all ten of the number values and the just output them as text like << ",3:" << three << instead of << ",8:" << count_numbers(array, 8) <<
Anyway, the function.cpp and main.cpp are below.
If anyone could point me in the right direction it would greatly appreciated. Just need to know the correct method so I can condense this code.
function.cpp
#include <iomanip>
#include <locale>
#include <sstream>
#include <string>
#include <iostream>
int count_numbers(int array[4][4], int Q)
{
int X=0;
int Y=0;
int zero=0;
int one=0;
int two=0;
int three=0;
int four=0;
int five=0;
int six=0;
int seven=0;
int eight=0;
int nine=0;
while(X<4)
{
if(array[X][Y]==0)
{
zero=zero+1;
}
if(array[X][Y]==1)
{
one=one+1;
}
if(array[X][Y]==2)
{
two=two+1;
}
if(array[X][Y]==3)
{
three=three+1;
}
if(array[X][Y]==4)
{
four=four+1;
}
if(array[X][Y]==5)
{
five=five+1;
}
if(array[X][Y]==6)
{
six=six+1;
}
if(array[X][Y]==7)
{
seven=seven+1;
}
if(array[X][Y]==8)
{
eight=eight+1;
}
if(array[X][Y]==9)
{
nine=nine+1;
}
Y++;
if(Y==4)
{
Y=0;
X++;
}
}
if(Q==0)
{
return zero;
}
if(Q==1)
{
return one;
}
if(Q==2)
{
return two;
}
if(Q==3)
{
return three;
}
if(Q==4)
{
return four;
}
if(Q==5)
{
return five;
}
if(Q==6)
{
return six;
}
if(Q==7)
{
return seven;
}
if(Q==8)
{
return eight;
}
if(Q==9)
{
return nine;
}
}
main.cpp
#include <iomanip>
#include <locale>
#include <sstream>
#include <string>
#include <iostream>
extern int count_numbers(int array[4][4], int);
int array[4][4] = { {1,2,3,4} , {1,2,3,4} , {1,2,3,4} , {1,2,3,4}};
int main()
{
count_numbers(array);
std::cout << ",0:" << count_numbers(array, 0) << ",1:" << count_numbers(array, 1) << ",2:" << count_numbers(array, 2) << ",3:" << count_numbers(array, 3) << ",4:" << count_numbers(array, 4) << ",5:" << count_numbers(array, 5) << ",6:" << count_numbers(array, 6) <<",7:" << count_numbers(array, 7) << ",8:" << count_numbers(array, 8) << ",9:" << count_numbers(array, 9) << std::endl;
}
PS. Ignore incorrect indentation its just from pasting to this site
PPS. Thanks for any assistance.
EDIT
Thank you "Vlad From Moscow" for the assistance.
My initial (terrible) code would have worked if I'd simply removed the (unintentional) count_number(array); call from main.cpp
However the for loop system proposed by Vlad allowed me to shrink the code by 80%. It now looks like this:
int count_numbers(int array[4][4], int Q)
{
int ans=0;
for(int i=0; i<4; i++)
{
for(int j=0; j<4; j++)
{
ans += array[i][j] ==Q;
}
}
return ans;
}
Thank you for the assistance which was great, I began coding on Python so it was my lack of understanding of loops in C++ which was the real problem here.
Anyway, problem solved..
This call
count_numbers(array);
does not make sense and moreover is invalid because the function requires two arguments instead of one.
The function itself can be written the following way
const size_t N = 4;
size_t count_number( const int ( &a )[N][N], int value )
{
size_t n = 0;
for ( size_t i = 0; i < N; i++ )
{
for ( size_t j = 0; j < N; j++ )
{
n += a[i][j] == value;
}
}
return n;
}
and called like
std::cout << "0: " << count_number( array, 0 )
<< ", 1: " << count_number( array, 1 )
<< ", 2: " << count_number( array, 2 )
<< ", 3: " << count_number( array, 3 )
<< ", 4: " << count_number( array, 4 )
<< ", 5: " << count_number( array, 5 )
<< ", 6: " << count_number( array, 6 )
<< ", 7: " << count_number( array, 7 )
<< ", 8: " << count_number( array, 8 )
<< ", 9: " << count_number( array, 9 )
<< std::endl;
Here is a demonstrative program
#include <iostream>
const size_t N = 4;
size_t count_number( const int ( &a )[N][N], int value )
{
size_t n = 0;
for ( size_t i = 0; i < N; i++ )
{
for ( size_t j = 0; j < N; j++ )
{
n += a[i][j] == value;
}
}
return n;
}
int main()
{
int array[N][N] =
{
{ 1, 2, 3, 4 } ,
{ 1, 2, 3, 4 } ,
{ 1, 2, 3, 4 } ,
{ 1, 2, 3, 4 }
};
bool first = true;
for ( int value = 0; value < 10; ++value )
{
size_t n = count_number( array, value );
if ( n )
{
std::cout << ( first ? first = false, "" : ", " )
<< value << ": " << n;
}
}
std::cout << std::endl;
}
Its output is
1: 4, 2: 4, 3: 4, 4: 4
A more general approach can look the following way
#include <iostream>
#include <iterator>
#include <algorithm>
template <typename InputIterator, typename T>
size_t count_number( InputIterator first,
InputIterator last,
const T &value )
{
size_t n = 0;
for ( ; first != last; ++first )
{
n += std::count( std::begin( *first ), std::end( *first ), value );
}
return n;
}
int main()
{
const size_t N = 4;
int array[N][N] =
{
{ 1, 2, 3, 4 } ,
{ 1, 2, 3, 4 } ,
{ 1, 2, 3, 4 } ,
{ 1, 2, 3, 4 }
};
bool first = true;
for ( int value = 0; value < 10; ++value )
{
size_t n = count_number( std::begin( array ), std::end( array ), value );
if ( n )
{
std::cout << ( first ? first = false, "" : ", " )
<< value << ": " << n;
}
}
std::cout << std::endl;
}
The program output will be the same as it is shown above.
If the array contains only digits that you need to count then the function can look like
const size_t N = 4;
void count_digits( const int ( &a )[N][N], size_t ( &digits)[10] )
{
for ( size_t &x : digits ) x = 0;
for ( size_t i = 0; i < N; i++ )
{
for ( size_t j = 0; j < N; j++ )
{
++digits[a[i][j]];
}
}
}
To call the function you need to declare in main an array like for example
size_t digits[10];
you can return int[] or event better since you are using c++ return vector<int>.
In your function you can replace one, two, .. with something like
vector<int> result(10);
This will create a vector with 10 entries, all of them 0.
Then replace thing like three = three + 1 with result[3] = result[3] + 1 or even more condensed result[3]++
Then at the end you can write ... << ",0:" << result[0] << ... or even do a for loop like:
for (int i = 0; i < 10; ++i) count << "," << i << ":" << result[i];
You can do all this with int[] as well if that's required but you need to take care of allocating and deallocating the memory. vector will simplify your code a lot.

Split array into sub blocks

What I am trying to achieve is this:
I have an image and I need to split it into sub blocks of 16x16 and I am working on the algorithm for this. For testing purposes though, I am using a small matrix:
A = {1, 2, 3, 4}
Now what I want to end up is this: 2 blocks containing:
A[1] = {1 2};
A[2] = {3, 4};
I have tried to use the following:
double matrix[4] = {1, 2, 3, 4};
for(int i = 0; (i < 4); i++)
{
for(unsigned j=i; (j < 2); j +=2)
{
std::cout << j << ' ';
}
std::cout << std::endl;
}
My thought process was to loop through the entire array (4) and then increment by 2 each time to create the 1x2 block. This did not work however.
Where am I going wrong here?
Something like that? (Does both output and assignment)
int LEN = 4;
int INNER = 2;
int OUTER_LEN = LEN/INNER_LEN;
double matrix[LEN] = {1, 2, 3, 4};
double* matrix2[OUTER_LEN];
for(int i = 0; i < OUTER_LEN; i++)
{
matrix2[i] = &matrix[i*INNER_LEN];
for(unsigned j=0; j < INNER_LEN; j++)
{
std::cout << matrix[i*INNER_LEN+j] << ' ';
}
std::cout << std::endl;
}
Just for output you could do something like that:
#include <iostream>
int main(){
const size_t SIZE = 4;
const size_t PART_SIZE = 2;
double matrix[4] = {1, 2, 3, 4};
for(int i = 0; (i < SIZE); i += PART_SIZE)
{
for(size_t j = i; (j < i + PART_SIZE) && j < SIZE; j += 1)
{
std::cout << matrix[j] << ' ';
}
std::cout << std::endl;
}
}
To add another matrix:
#include <iostream>
int main(){
const size_t SIZE = 4;
const size_t PART_SIZE = 2;
size_t partsNumber = SIZE / PART_SIZE; // Beware of SIZE that is not divisible by PART_SIZE - partsNumber will be too small
double matrix[4] = { 1, 2, 3, 4 };
// To do it properly I should make it dynamic array with size of partsNumber instead of the 2 literals
double parts_matrix[2][PART_SIZE];
for (int i = 0; (i < SIZE); i += PART_SIZE) {
for (size_t j = i; (j < i + PART_SIZE) && j < SIZE; j += 1) {
std::cout << matrix[j] << ' ';
parts_matrix[j / partsNumber][j % PART_SIZE] = matrix[j];
}
std::cout << std::endl;
}
std::cout << parts_matrix[0][0] << " " << parts_matrix[0][1] << std::endl << parts_matrix[1][0] << " " << parts_matrix[1][1]; // Check if it works
}
The following is a demo of how to do the splitting for custom block size (rough cut though, corner cases and input verification are ommited) using boost range and the boost::slice functionality (here "output creation" is presented)
#include <iterator>
#include <iostream>
#include <boost/range/adaptor/sliced.hpp>
#include <boost/range/algorithm/copy.hpp>
using namespace std;
using namespace boost::adaptors;
template<typename T, size_t N>
void split(T (&input)[N], size_t block_size)
{
for (size_t i(0); i <= N-block_size; i += block_size)
{
cout << "{ ";
boost::copy(input | sliced(i, i+block_size),
std::ostream_iterator<int>(std::cout, " "));
cout << "}\n";
}
}
int main()
{
int A[] = {1, 2, 3, 4};
split(A, 2);
}
Demo
Output
{ 1 2 }
{ 3 4 }
What if I don't want to do output
To some the following may look more readable
template<typename T, size_t N>
void split(T (&input)[N], size_t block_size)
{
for (size_t i(0); i <= N-block_size; i += block_size)
{
cout << "{ ";
// do whatever with the i slice (again I'm showing output)
for (auto k : (input | sliced(i, i+block_size))) cout << k << " ";
cout << "}\n";
}
}