Using for loop inside declaration of variable - c++

Can I use for loop inside declaration a variable?
int main() {
int a = {
int b = 0;
for (int i = 0; i < 5; i++) {
b += i;
}
return b;
};
printf("%d", a);
}

You can use a lambda:
int main() {
int a = []{
int b = 0;
for (int i = 0; i < 5; i++) {
b += i;
}
return b;
}();
printf("%d", a);
}
It's important to note that you have to immediately execute it otherwise you attempt to store the lambda. Therefore the extra () at the end.
If you intent to reuse the lambda for multiple instantiations, you can store it separately like this:
int main() {
auto doCalculation = []{
int b = 0;
for (int i = 0; i < 5; i++) {
b += i;
}
return b;
};
int a = doCalculation();
printf("%d", a);
}
If you need it in more than one scope, use a function instead.

actually has been prepared by C++ committee..
constexpr has many usefulness not yet exlpored
constexpr int b(int l) {
int b=0;
for (int i = 0; i < l; i++)
b += i;
return b;
}
int main() {
constexpr int a = b(5);
printf("%d", a);
}

Related

Swapping elements in array doesn't work when using function pointer

So i want to use AscendingSort() and DecendingSort() as an argument but it seems like after return the value the swap part just get skipped, hope someone explain to me, thanks!.
bool AscendingSort(int a, int b)
{
return a > b;
}
bool DecendingSort(int a, int b)
{
return a < b;
}
void SortArray(int* a, int size, bool(*func)(int, int))
{
int saveElement;
for (int x = 0; x < size; x++)
{
for (int y = x + 1; y < size; y++)
{
if (func(a[x], a[y]))
{
saveElement = a[x];
a[x] == a[y]; //Those 2 lines getting skipped.
a[y] == saveElement;
}
}
}
}
void main()
{
int a[1000];
int arrSize;
SortArray(a, arrSize, AscendingSort);
};
You probably meant to use = operator instead of ==.

Coufused about using cpp to achieve selection sort

I tried to implement selection sorting in C++,when i encapsulate the swap function, the output shows a lot of zeros.But at beginning of array codes still work.When I replace swap function with the code in the comment, the output is correct.
I am so confused by this result, who can help me to solve it.
#include <iostream>
#include <string>
using namespace std;
template<class T>
int length(T& arr)
{
return sizeof(arr) / sizeof(arr[0]);
}
void swap(int& a, int& b)
{
a += b;
b = a - b;
a = a - b;
}
int main()
{
int array[] = { 2,2,2,2,6,56,9,4,6,7,3,2,1,55,1 };
int N = length(array);
for (int i = 0; i < N; i++)
{
int min = i; // index of min
for (int j = i + 1;j < N; j++)
{
if (array[j] < array[min]) min = j;
}
swap(array[i],array[min]);
// int temp = array[i];
// array[i] = array[min];
// array[min] = temp;
}
for (int i = 0; i < N; i++)
{
int showNum = array[i];
cout << showNum << " ";
}
return 0;
}
Problem is that your swap function do not work if a and b refer to same variable. When for example swap(array[i], array[i]) is called.
Note in such case, this lines: b = a - b; will set b to zero since a and b are same variable.
This happens when by a chance i array element is already in place.
offtopic:
Learn to split code into functions. Avoid putting lots of code in single function especially main. See example. This is more important the you think.
Your swap function is not doing what it is supposed to do. Just use this instead or fix your current swap.
void swap(int& a, int& b){
int temp = a;
a = b;
b = temp;
}

Initialize C++ struct that contains a fixed size array

Suppose I have a POD C struct as so:
struct Example {
int x;
int y[10];
int yLen;
}
With the following code, the program doesn't compile:
Example test() {
int y[10];
int yLen = 0;
auto len = this->getSomethingLength();
for (int i = 0; i < len; i++) {
y[yLen++] = this->getSomething(i);
}
return Example{ 0, y, yLen };
}
However, doing return {0, {}, 0}; does seem to compile. Problem is, I can't know the size of y until doing some sort of logic ahead of time. Initializing int y[10]{} in test doesn't seem to make a difference. I know this seems like a pretty simple question, but I can't seem to find anything that works.
Declare the structure as a whole instead of its parts and then initialize it:
Example test() {
Example result;
auto len = this->getSomethingLength();
for (result.yLen = 0; result.yLen < len; result.yLen++) {
result.y[result.yLen] = this->getSomething(result.yLen);
}
return result;
}
Declaring y as an int* and allocating memory with new, when the size is known, would be an even better solution.
Declare constructor in Example:
struct Example {
int x;
int y[10];
int yLen;
Example(int xNew, int *yNew, int yLenNew)
{
x = xNew;
yLen = yLenNew;
for (int i = 0; i < yLenNew; i++)
{
y[i] = yNew[i];
}
}
};
And use it like this:
Example test() {
int y[10];
int yLen = 0;
auto len = this->getSomethingLength();
for (int i = 0; i < len; i++) {
y[yLen++] = this->getSomething(i);
}
return Example( 0, y, yLen );
}

How to initialize dynamic array inside a class?

I wish to initialize a multidimensional, dynamic array inside a class. But, I am getting an error.
I have seen several examples on the net. They seem to be difficult. I am new to coding. I would like a simple solution if possible.
class myp
{
int ntc = 5;
public:
double** y = new double*[ntc];
for(int i = 0; i < ntc; ++i)
y[i] = new int[3];
};
int main()
{
int x;
myp mp;
mp.y[1][1] = 3;
cout<<mp.y[1][1]<<endl;;
return 0;
}
test.cpp:12:2: error: expected unqualified-id before ‘for’
for(int i = 0; i < ntc; i++)
^~~
test.cpp:12:17: error: ‘i’ does not name a type
for(int i = 0; i < ntc; i++)
^
test.cpp:12:26: error: ‘i’ does not name a type
for(int i = 0; i < ntc; i++)
You need to do class initialisation in the constructor function, and cleanup in the destructor.
class myp
{
int m_numColumns;
int m_numRows;
double** y;
public:
// overload array operators
double* operator [] (size_t row) { return y[row]; }
const double* operator [] (size_t row) const { return y[row]; }
// return dimensions of array
int numColumns() const { return m_numColumns; }
int numRows() const { return m_numRows; }
// constructor
myp(int nc, int nr) : m_numColumns(nc), m_numRows(nr)
{
y = new double*[m_numRows];
for(int i = 0; i < m_numColumns; ++i)
y[i] = new int[m_numColumns];
}
// destructor
~myp()
{
for(int i = 0; i < m_numColumns; ++i)
delete [] y[i];
delete [] y;
}
// be careful of the copy ctor. I'm deleting it in this case!
myp(const myp&) = delete;
// edit: as per user4581301's suggestion
myp() = delete;
myp(myp&&) = delete; // remove move ctor
myp& operator = (const myp&) = delete; // remove assignment
myp& operator = (myp&&) = delete; // remove move assignment
};
int main()
{
myp mp(5, 3);
mp[1][1] = 3;
cout << mp[1][1]<<endl;
return 0;
}
Just For Run.
class myp
{
int ntc = 5;
public:
double **y;
void initArray()
{
y = new double*[ntc];
for(int i = 0; i < ntc; ++i)
y[i] = new double[3]; // i change this line [new int] to [new double]tv
}
};
int main()
{
int x;
myp mp;
mp.initArray();
mp.y[1][1] = 3;
cout<<mp.y[1][1]<<endl;;
return 0;
}
using constructor & destructor
class myp
{
int ntc = 5;
public:
double **y;
myp() // run at created
{
y = new double*[ntc];
for(int i = 0; i < ntc; ++i)
y[i] = new double[3];
}
~myp() // run at the end of life cycle
{
/* free memory here */
}
};
int main()
{
int x;
myp mp; // myp() called
mp.y[1][1] = 3;
cout<<mp.y[1][1]<<endl;
return 0;
}
using constructor with parameter, for dynamic size
class myp
{
// int ntc = 5; // using at created
public:
double **y;
myp(int ntc, int size) // run at created
// if you want to use only myp mp;
// myp(int ntc = 5, int size = 3) {} will be helpful
{
y = new double*[ntc];
for(int i = 0; i < ntc; ++i)
y[i] = new double[size];
}
~myp() // run at the end of life cycle
{
/* free memory here */
}
};
int main()
{
int x;
myp mp(5, 3); // myp(int, int) called
mp.y[1][1] = 3;
cout<<mp.y[1][1]<<endl;
return 0;
}

How to avoid returning pointers in a class

Assume I have a class A that has say 3 methods. So the first methods assigns some values to the first array and the rest of the methods in order modify what is computed by the previous method. Since I wanted to avoid designing the methods that return an array (pointer to local variable) I picked 3 data member and store the intermediate result in each of them. Please note that this simple code is used for illustration.
class A
{
public: // for now how the class members should be accessed isn't important
int * a, *b, *c;
A(int size)
{
a = new int [size];
b = new int [size];
c = new int [size];
}
void func_a()
{
int j = 1;
for int(i = 0; i < size; i++)
a[i] = j++; // assign different values
}
void func_b()
{
int k = 6;
for (int i = 0; i < size; i++)
b[i] = a[i] * (k++);
}
void func_c()
{
int p = 6;
for int (i = 0; i < size; i++)
c[i] = b[i] * (p++);
}
};
Clearly, if I have more methods I have to have more data members.
** I'd like to know how I can re-design the class (having methods that return some values and) at the same time, the class does not have the any of two issues (returning pointers and have many data member to store the intermediate values)
There are two possibilities. If you want each function to return a new array of values, you can write the following:
std::vector<int> func_a(std::vector<int> vec){
int j = 1;
for (auto& e : vec) {
e = j++;
}
return vec;
}
std::vector<int> func_b(std::vector<int> vec){
int j = 6;
for (auto& e : vec) {
e *= j++;
}
return vec;
}
std::vector<int> func_c(std::vector<int> vec){
//same as func_b
}
int main() {
std::vector<int> vec(10);
auto a=func_a(vec);
auto b=func_b(a);
auto c=func_c(b);
//or in one line
auto r = func_c(func_b(func_a(std::vector<int>(10))));
}
Or you can apply each function to the same vector:
void apply_func_a(std::vector<int>& vec){
int j = 1;
for (auto& e : vec) {
e = j++;
}
}
void apply_func_b(std::vector<int>& vec){
int j = 6;
for (auto& e : vec) {
e *= j++;
}
}
void apply_func_c(std::vector<int>& vec){
// same as apply_func_b
}
int main() {
std::vector<int> vec(10);
apply_func_a(vec);
apply_func_b(vec);
apply_func_c(vec);
}
I'm not a big fan of the third version (passing the input parameter as the output):
std::vector<int>& func_a(std::vector<int>& vec)
Most importantly, try to avoid C-style arrays and use std::vector or std::array, and don't use new, but std::make_unique and std::make_shared
I'm assuming you want to be able to modify a single array with no class-level attributes and without returning any pointers. Your above code can be modified to be a single function, but I've kept it as 3 to more closely match your code.
void func_a(int[] arr, int size){
for(int i = 0; i < size; i++)
arr[i] = i+1;
}
void func_b(int[] arr, int size){
int k = 6;
for(int i = 0; i < size; i++)
arr[i] *= (k+i);
}
//this function is exactly like func_b so it is really unnecessary
void func_c(int[] arr, int size){
int p = 6;
for(int i = 0; i < size; i++)
arr[i] *= (p+i);
}
But if you just want a single function:
void func(int[] arr, int size){
int j = 6;
for(int i = 0; i < size; i++)
arr[i] = (i+1) * (j+i) * (j+i);
}
This solution in other answers is better, if you are going to allocate memory then do it like this (and test it!) also if you are not using the default constructor and copy constructor then hide them, this will prevent calling them by accident
class A{
private:
A(const &A){}
A() {}//either define these or hide them as private
public:
int * a, *b, *c;
int size;
A(int sz) {
size = sz;
a = new int[size];
b = new int[size];
c = new int[size];
}
~A()
{
delete[]a;
delete[]b;
delete[]c;
}
//...
};