c++ how to get data out of a hardcoded struct? - c++

I have a struct that has hardcoded data in it, however I can't figure out how to get c++ to display the data. What I am trying is:
#include <iostream>
using namespace std;
const int MAX = 8;
struct test {
int x[MAX] = { 16, 21, 308, 45, 51, 63, 17, 38 };
float y[MAX] = { 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5 };
int z[MAX] = { 8, 7, 6, 5, 4, 3, 2, 1 };
} id[MAX] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int main() {
for (int counter = 0; counter < MAX; counter++) {
cout << id[counter].x << ", " << id[counter].y << ", "<< id[counter].z << endl;
}
}

I suggest you change your data layout:
struct Triplet
{
int x;
float y;
int z;
};
Next, make a container of the values:
std::vector<Triplet> test;
Or
Triple test[MAXIMUM_CAPACITY];
This should make your initializations easier.
It may also speed up your program by keeping relevant data closer together in the data cache.

I can't figure out how to get c++ to display the data.
You've been shooting over regarding usage of hardcoded arrays.
You don't need to double up your dimensions for struct. Any struct initialization will preserve the necessary memory for it's members.
You probably meant to write something like
#include <iostream>
using namespace std;
const int MAX = 8;
struct test
{
int x; // A simple int
float y; // A simple float
int z; // A simple int
} const id[MAX] = // Preserve the dimension. Note the const, to prevent changing the
// hardcoded values.
// Initialize the triples as needed
{ { 16, 1.5, 8 } ,
{ 308, 2.5, 7 } ,
// Place more triples here ...
{ 38, 8.5, 1 }
};
int main()
{
for (int counter = 0; counter < MAX; counter++)
{
cout << id[counter].x << ", " << id[counter].y << ", "<< id[counter].z << endl;
}
return 0;
}
See the Live Demo
The idiomatic c++ way to write this would be
struct test {
int x; // A simple int
float y; // A simple float
int z; // A simple int
};
std::array<test,MAX> id {{
{ 16, 1.5, 8 } ,
{ 308, 2.5, 7 } ,
// Place more triples here ...
{ 38, 8.5, 1 }
}};
See Live Demo

Related

Is there a way to ensure two arguments passed to a function are treated as the first and third argument in C++?

Suppose there is a function with the following prototype:
void fun (int = 10, int = 20, int = 30, int = 40);
If this function is called by passing 2 arguments to it, how can we make sure that these arguments are treated as first and third, whereas, the second and the fourth are taken as defaults.
// three and four argument version
void fun (int a, int b, int c, int d = 40)
{
...
}
// two argument version
void fun (int a, int c)
{
fun(a, 20, c, 40);
}
// one and zero argument version
void fun(int a = 10)
{
fun(a, 20, 30, 40);
}
But really my advice would be don't.
You can define the Args structure like:
struct Args {
int a = 10;
int b = 20;
int c = 30;
int d = 40;
};
and then you would have the following:
void fun(Args);
fun({.a=60, .c=70}); // a=60, b=20, c=70, d=40
Besides this approach, you can use NamedType library that implements named arguments in C++. For more usage info, check here.
UPDATE
Designated initializers feature is available by GCC and CLANG extensions and, from C++20, it is available by C++ standard.
This one works, it uses function overloading.
#include <iostream>
using namespace std;
void fun(int a = 10, int b = 20, int c = 30, int d = 40){
cout << "a = " << a << "\nb = " << b << "\nc = " << c << "\nd = " << d;
}
void fun(float a, float c, int b = 20, int d = 40){
cout << "a = " << a << "\nb = " << b << "\nc = " << c << "\nd = " << d;
}
int main(){
cout << "Enter two numbers : ";
float a, b;
cin >> a >> b;
fun(a, b);
return 0;
}
Maybe a more elegant way would be using std::bind and std::placeholders like this:
#include <functional>
void fun (int = 10, int = 20, int = 30, int = 40) {}
using namespace std::placeholders;
auto bindedFun = std::bind(fun, _1, 20, _2, 40);
int main()
{
bindedFun(1234, 5678);
}
I find it more clearer and easier to understand. Also it is less prown to errors imo! And if you don't wanna have a global variable to hold your bind, you could either declare it locally or stuff your binds in a struct.

Garbage value getting displayed on printing 2d array using row order

I am using gcc compiler on ubuntu 16 , when I am printing value garbage value is getting displayed
#include <bits/stdc++.h>
int Arrayprint(int r, int l, unsigned int* q)
{
r = 3;
l = 4;
for (int i = 0; i < r; i++) {
for (int j = 0; j < l; j++) {
cout << *(q + sizeof(unsigned int) * (i * l + j)); //Garbage getting diplay
cout << *(q + i + j); //this working
cout << "\t";
}
}
cout << "size of unsigned int : " << sizeof(unsigned int); //4
cout << "size of int : " << sizeof(int); //4
}
int main()
{
unsigned int image[R][L] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 } };
unsigned int* q = (unsigned int*)image;
Arrayprint(R, L, q);
}
From what I can tell, you understand at a low level that the address of the ith element of an array of T is base + sizeof(T) * i. That's correct, and it's good that you know that.
However, C and C++ handle this for you already. When you say q + i or q[i], it's actually compiling that into q + sizeof(T)*i anyway (with the latter also dereferencing the result).
So when you say q[sizeof(int)*i], that's actually compiling into *(q + sizeof(int)*sizeof(int)*i), which is clearly not what you wanted.
Thus, the index in the array you actually access is off by a factor of sizeof(int) and results in an out of bounds error, which is where your strange numbers are coming from.
I am using gcc compiler on ubuntu 16 , when I am printing value
garbage value is getting displayed
Instead of trying to fix what's broken in your raw array arimethics, consider using the standard containers:
#include <iostream>
#include <array>
constexpr size_t R = 3;
constexpr size_t L = 4;
using image_t = std::array<std::array<unsigned int, L>, R>;
void Arrayprint(const image_t& q) {
// range based for loops for convenience
for(auto& row : q) { // get references to each row
for(unsigned int colval : row) { // get the column values
std::cout << colval << "\t"; // print the values
}
std::cout << "\n";
}
}
int main() {
image_t image = {{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}};
Arrayprint(image);
}
Output:
1 2 3 4
5 6 7 8
9 10 11 12

How to return multiple values from a function in c++?

I know this has been asked before but I still don't know how to do it. I Have to write a function which returns the number of times 2, 5 and 9 appear in an array.
include <iostream>
int twofivenine(int array[], int n)
{
int i = 0;
int num_2 = 0;
int num_5 = 0;
int num_9 = 0;
for ( i = 0; i < n; i++ ){
switch(){
case (array[i] == 2):
num_2++;
case (array[i] == 5):
num_5++;
case (array[i] == 9):
num_9++;
}
}
return ;
}
int main()
{
int array[6] = {2,2,3,5,9,9};
std::cout << "2: 5: 9:" << twofivenine(array, 6) << std::endl;
}
I'm just not sure how to return (num_2, num_5, and num_9)
Can use std::tuple
std::tuple<int, int, int > twofivenine( int array[], int n)
{
//
return make_tuple( num_2, num_5, num_9 );
}
auto x = twofivenine( array, 6 );
std::cout << std::get<0>( x ) << '\n'
<< std::get<1>( x ) << '\n'
<< std::get<2>( x ) << '\n' ;
There are a number of ways to approach this problem.
Pass the values by reference. You can call a function such as the following:
Example:
void foo(int &a, int &b, int &c)
{
// modify a, b, and c here
a = 3
b = 38
c = 18
}
int first = 12;
int second = 3;
int third = 27;
foo(first, second, third);
// after calling the function above, first = 3, second = 38, third = 18
Store the values to return in a data type. Use a data type from the standard library such as std::vector, std::set, std::tuple, etc. to hold your values then return that entire data member.
Example:
std::vector<int> foo()
{
std::vector<int> myData;
myData.pushBack(3);
myData.pushBack(14);
myData.pushBack(6);
return myData;
}
// this function returns a vector that contains 3, 14, and 6
Create an object to hold your values. Create an object such as a struct or a class to hold your values and return the object in your function.
Example:
struct myStruct
{
int a;
int b;
int c;
};
myStruct foo()
{
// code here that modifies elements of myStruct
myStruct.a = 13;
myStruct.b = 2;
myStruct.c = 29;
return myStruct;
}
// this function returns a struct with data members a = 13, b = 2, and c = 29
The method you choose will ultimately depend on the situation.
Pass objects in by reference, ie
void twofivenine(int array[], int n, int &num_2, int &num_5, int &num_9)
{
//Don't redeclare num_2...
}
Call like so:
int num_2, num_5, num_9;
twofivenine(array, 6, num_2, num_5, num_9);
Return a struct by value which has the counts as the data members:
struct Result {
int num_3;
int num_5;
int num_9;
};
Result twofivenine(int array[], int n)
{
.
.
.
return Result{num_2, num_5, num_9};
}
and in main:
Result result(twofivenine(array, 6));
std::cout << "2: " << result.num_2 << "5: " << result.num_5 << "9: " << result.num_9 << std::endl;
Most compilers will do RVO (return-value-optimization) where the twofivenine function will directly write to the result struct avoiding a struct copy.

Memory Dump error on runtime

What is the problem in this code ? It shows memory dump error in runtime
#include<iostream>
using namespace std ;
int main()
{
int A[3][4] = {{3, 1, 8, 11}, {4, 12, 9, 10}, {7, 5, 2, 6}};
int **p = A;
P[1][2] = 99;
cout<<A[1][2] ;
}
Change your int **p = A[0][0] to int *p = &A[0][0]. In the next line, write the following *p = *((int*)p + 1 * NUM_OF_COLUMNS + 2) = 99;, where NUM_OF_COLUMNS is the number 4, instead of the P[1][2] = 99;. Correct the spelling of main as well as uppercase/lowercase of variables. Also add a return 0; at the end since you have an int main() and not a void.
you seem new to c++ or programming with a question like this one don't feel bad because pointers can be tricky and if you don't know you don't know. I am pretty sure this will help you. Remember to pick the best answer :).
#include <iostream>
using namespace std;
int main() {
int A[3][4] = { { 3, 1, 8, 11 }, { 4, 12, 9, 10 }, { 7, 5, 2, 6 } };
cout << "Before pointer change A[1][2] = " << A[1][2] << endl;
int *p; //Set pointer
p = &A[1][2]; //Set memory address to pointer don't forget '&'
*p = 99; //Change integer
cout << "After pointer change A[1][2] = " << A[1][2] << endl;
return 0; // you need a 'return 0;' because your main is int
}

Difference between array<int,5> b; and int b[5]; [duplicate]

This question already has answers here:
Now that we have std::array what uses are left for C-style arrays?
(7 answers)
Closed 8 years ago.
array<int, 5> b = {12,45,12,4};
int B[5] = { 12, 45, 12, 4 };
for (auto item : b)
{
cout << item << endl; // 12,45,12,4, 0
}
cout << endl;
for (auto item : B)
{
cout << item << endl; // 12,45,12,4, 0
}
What is the difference between array<int,5> b; and int b[5];?
Template class std:;array is defined as a structure. It is an aggregate and has some methods as for example size().
The difference is for example that arrays have no assignment operator. You may not write
int b[5] = { 12, 45, 12, 4 };
int a[5];
a = b;
while structures have an implicitly defined assignment operator.
std::array<int, 5> b = { 12, 45, 12, 4 };
std::array<int, 5> a;
a = b;
Also using arrays you may not use initialization lists to assign an array. For example the compiler will issue an error for the following statement
int b[5];
b = { 12, 45, 12, 4, 0 };
However you can do these manipulations with std::array For example
std::array<int, 5> b;
b = { 12, 45, 12, 4, 0 };