Novice C++, seeking help in array division - c++

#include <iostream>
#include <valarray>
using namespace std;
// to get new card number
int main ()
{
int i;
int array[5]= {10,2,6,34,51};
valarray<int> v[5];
int v %= 13;
for (int i=0; i<5 ; i++) {
cout << v[i]%=13 << " ";
}
}
hello, my goal is to get the array to perform a modulus division by number 13.
I've search and try a few different way but I can't figure out a way to make it work.....
Thank you...

Some of the problems with your code:
valarray does not have the same notation as normal arrays: valarray<int> v[5]; declares 5 different valarray objects and puts them in a C-style array. The notation you are looking for is valarray<int> v(10);
Get rid of the int v %= 13; line: this redefines v (an array) as an integer.
Use v[i]=(array[i]%13); for the calculation, what you have doesn't make sense.
Then output cout << v[i] << " ";
Also, you aren't really using any of the features of valarray, so it may make more sense just to use one single array, like:
#include <iostream>
using namespace std;
// to get new card number
int main ()
{
int array[5]= {10,2,6,34,51};
for (int i=0; i<5 ; i++) {
array[i]%=13;
cout << array[i] << " ";
}
}
Edit: by the way, the cool thing about valarray here is that you can apply the same function to every value at once. Like this:
#include <iostream>
#include <valarray>
using namespace std;
int main() {
valarray<int> v(10);
for (int i=0;i<10;++i) {
v[i]=i*i; //Fill the array with 0,1,4,9,16,... as an example
}
v%=13; //This applies the modulo 13 on the whole array at once.
for (int i=0;i<10;++i) {
cout << v[i] << endl;
}
}

Seems you want something like...
int array[5]= {10,2,6,34,51};
int v[5];
for (int i = 0; i < 5; ++i)
v[i] = array[i] % 13;
for (int i = 0; i < 5; ++i)
std::cout << v[i] << " ";
std::cout << '\n';

Related

Declaring sqrt(var) as a compile time constant in c++

I have a c++ program where I need to pass the square root of a number in a for loop.
#include<random>
#include<iostream>
#include<algorithm>
#include<string>
#include<math.h>
#include <stdlib.h>
#include <windows.h>
#include <ctype.h>
#include <omp.h>
using namespace std;
int main()
{
vector<int>inputDataBits(49); // vector of randomly generated input data bits
#ifdef printDebug
std::cout << "the input data bits are" << endl;
std::cout << "-------------------------" << endl << endl;
int var =49;
const int r=(int)sqrt(var);
float input2d[r][r];
for (int i = 0; i < r; i++)
{
for (int j = 0; j < r; j++)
{
input2d[i][j] = inputDataBits[(j %r) + (i *r)];
std::cout << input2d[i][j] << "\t";
}
std::cout << endl << endl;
}
std::cout << endl << endl;
#endif
return 0;
}
I get an error 'expression must have a constant value'. Is there a way to do this in c++?
This is the purpose of the constexpr keyword (make the value known at compile time).
constexpr int var=49;
constexpr int r=(int)sqrt(var);
Unfortunately, in the documentation sqrt() is not declared as a constexpr function.
Only gcc seems to consider it as constexpr but it is not portable.
The size of an array needs to be known at compile-time.
Instead you can use a std::vector, which has a dynamic size.
std::vector<std::vector<float>> input2d(std::vector<float>(r), r);

Invalid conversion from int* to int even though I delimit the pointer

I've received the following error:
NQueens.cpp:35:19: error: invalid conversion from 'int*' to 'int' [-fpermissive]
solution[i].y = *(possibilities + i);
I believe I delimited the pointer so that I can apply the value being pointed to the y coordinate for the n-queens problem. Am I missing anything, or is my compiler being dumb?
My header file:
#pragma once
#ifndef QUEEN
#define QUEEN
struct Queen {
int x, y;
};
#endif // !QUEEN
My C++ code:
#include "Queen.h"
#include <iostream>
#include <vector>
using namespace std;
bool isDiag(int, int, int, int);
bool solutionFinder(int, int, vector<int*>);
int main()
{
int n;
cout << "Enter a number n for the n-queen problem:\n";
cin >> n;
vector<int*> possibilities;
for (int i = 0; i < n; i++)
{
int arrayInt[n];
arrayInt[0] = i + 1;
for (int j = 1; j < n; j++)
{
arrayInt[j] = 0;
}
possibilities.push_back(arrayInt);
}
if (!solutionFinder(1, n, possibilities))
{
cout << "No Solution.\n";
}
Queen solution[n];
for (int i = 0; i < n; i++)
{
solution[i].x = i + 1;
solution[i].y = *(possibilities.begin() + i);
}
cout << "Solution: [(" << solution[0].x << "," << solution[0].y << ")";
for (int i = 1; i < n; i++)
cout << ", (" << solution[i].x << "," << solution[i].y << ")";
cout << "]\n";
return 0;
}
UPDATE:
I've tried the fix that mch suggested and now it compiles fine. However, I've ran into a new problem. When trying to print the coordinates for the queens, I'm getting what I believe are the locations of the values in memory.
Example:
Enter a number n for the n-queen problem:
4
Solution: [(1,1163548928), (2,32764), (3,1163548704), (4,32764)]
There are multiple issues with this code, but your immediate problem stems from this:
vector<int*> possibilities;
...
for (...)
{
int arrayInt[n];
...
possibilities.push_back(arrayInt);
}
...
solution[i].y = *(possibilities.begin() + i);
You have a vector of int* pointers, which are pointing at int[] arrays which you are creating inside a loop (and will be destroyed at the end of each loop iteration, thus leaving the vector holding dangling pointers to invalid memory).
You are then iterating through the vector, extracting each int* pointer and trying to assign it as-is to a single int, thus the compiler error. You would need to instead dereference the int* to get individual int values from the array, eg:
int *arr = *(possibilities.begin() + i);
solution[i].y = arr[someIndex];
Based on what you have shown, I think you have implemented your solutionFinder() incorrectly (but you didn't show how you actually implemented it). Rather than outputting a vector of int[] arrays, it would be better to have it output a vector of Queens instead, eg:
#include "Queen.h"
#include <iostream>
#include <vector>
using namespace std;
bool isDiag(int, int, int, int);
bool solutionFinder(int, int, vector<Queen>&);
int main()
{
int n;
cout << "Enter a number n for the n-queen problem:\n";
cin >> n;
vector<Queen> solution;
solution.reserve(n);
if (!solutionFinder(1, n, solution))
{
cout << "No Solution.\n";
return 0;
}
cout << "Solution: [(" << solution[0].x << "," << solution[0].y << ")";
for (int i = 1; i < n; ++i)
cout << ", (" << solution[i].x << "," << solution[i].y << ")";
cout << "]\n";
return 0;
}
bool isDiag(int, int, int, int)
{
// ...
}
bool solutionFinder(int, int, vector<Queen> &solution)
{
// populate solution with Queen's as needed...
for (...)
{
Queen q;
q.x = ...;
q.y = ...;
solution.push_back(q);
}
...
}
Contrary to the various comments you /can/ do can do arithmetic on "random access" iterators.
The issue is that you declared you have a vector of pointers.
You access the iterator like a pointer using operator * to indirect, but then you would would need to indirect again (another *) to follow the pointer held in the cell of the vector.
It is simper to use the array index syntax with vector poss[i] rather than *(poss.begin()+i) but you still need to do that extra indirection if you do indeed have a vector of pointers, *(poss[i]) which looks a bit ugly.

Just need to know if my way of printing pattern in c++ is efficient , or there is an another way to do it efficiently

I have posted a code to print the pattern given below . just need to know if there is another efficient way to do it .
#include<iostream>
#include <string>
using namespace std;
int main()
{
for (int i = 0; i < 5; i++)
{
cout<< string (i+1, '*') << '\n';
}
return 0;
}
This code prints a pattern as drawn below:
*
**
***
****
*****
The most efficient way is:
#include <iostream>
int main()
{
std::cout <<
"*\n"
"**\n"
"***\n"
"****\n"
"*****";
}
You could use lower-level stdio-style calls if you want to avoid the overhead of string manipulations and I/O streams:
#include <stdio.h>
int main(int, char **)
{
for (int i = 1; i <= 5; i++)
{
for (int j = 0; j < i; j++) putc('*', stdout);
putc('\n', stdout);
}
return 0;
}
It's hard to imagine why efficiency would matter here, though.
The following is 4 lines.
#include <iostream>
int main()
{
std::cout << std::setfill('*'); // change fill
for (int i=1; i<= 5; ++i)
std::cout << std::setw(i) << '*' << '\n';
std::cout << std::setfill(' ') << endl; // restore fill
}
I will leave the measurement of run-time comparison to the OP.

what is the exact time to run a program?

I want the exact time to run a program, I use it from clock(). But there is a problem that I can not give an exact time for small n like 2000.
I want it to return the correct answer for n=1000.
#include <iostream>
#include <ctime>
#include <algorithm>
using namespace std;
#define show_time(x, y) cout << endl << #x << " : " << y << endl;
int main()
{
int n;
cin >> n;
int *a = new int[n];
for(int i=0; i<n; i++)
a[i] = i;
random_shuffle(a, a+n);
int last = clock();
//STL_sort:
sort(a, a+n);
int lastP = clock();
show_time(STL_sort, (double)(lastP-last)/CLOCKS_PER_SEC);
return 0;
}
The output is 0. (Definitely 0 will not be the answer)
What platform are you running on? If you're on Windows, you could try the high-resolution time library.
If you have access to C++11, there is a header called chrono that has similar functionality, and is portable (ish)!

Print struct element of vector

I am learning about vector. I try to implement a code that print the struct element of a vector as displayed below. Many resources in the internet only teach me a simple vector. I get stcuk in expression when to print it. However, any suggestion for improving the quality and elegance of the code is open, although the change is fundamental (in struct or looping).
Thank you very much.
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
typedef struct _student {
string name;
int age;
vector <string> subject;
}student;
int _tmain(int argc, _TCHAR* argv[])
{
vector <student> x; //assmue at this point we do not know the number of students
student y;
//and I want to insert new information
y.name ="John";
y.age =9;
y.subject.push_back("biology");
y.subject.push_back("math");
y.subject.push_back("art");
x.push_back(y);
//get new information again
//and I want to insert new information
y.name ="Bon";
y.age =12;
y.subject.push_back("history");
y.subject.push_back("physics");
x.push_back(y);
// then I want display all data
cout << "myvector contains:";
for (int i=0; i<x.size(); i++)
{
cout << "Student # " << i+1 <<endl;
cout << " name : " << x.at(i).name <<endl; //Reference in the internet only display a simple vector --
cout << " age : " << x.at(i).age <<endl; //I get stuck to express this and next part
cout <<" Subject : ";
for (int j =0; j < x.at(i).subject.size(); j++)
{
cout << x.at(i).subject.at(j);
}
cout << endl;
cin.get();
return 0;
}
Here, added some comments and stuff. Not sure if this is what you were looking for, but here it is.
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string> // string would be welcome here!
struct _student // the typedef thing is not necessary in C++
{
std::string name; // i find this "using namespace ..." thing a bad habit, it can make code harder to read
int age;
std::vector<std::string> subject;
};
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<student> x;
student y;
size_t size; // calling vector.size() every iterations is a bad idea, performance-wise
size_t size_subj; // same
y.name = "John";
y.age = 9;
y.subject.push_back("biology");
y.subject.push_back("math");
y.subject.push_back("art");
x.push_back(y);
y.name = "Bon";
y.age = 12;
y.subject.clear(); // clear subjects of the other student
y.subject.push_back("history");
y.subject.push_back("physics");
x.push_back(y);
std::cout << "my vector contains:";
for (int i = 0, size = x.size(); i < size; ++i)
{
size_subj = x[i].subject.size();
// I prefer using operator[] when I'm sure nothing can go wrong
std::cout << "Student # " << i + 1 <<endl;
std::cout << "\tname: " << x[i].name <<endl;
std::cout << "\tage: " << x[i].age <<endl;
std::cout << "\tSubjects: ";
for (int j = 0; j < size_subj; ++j)
std::cout << x[i].subject[j];
std::cout << endl;
}
return 0;
}
Finally, using a std::vector< std::string* > or std::vector< std::string& > could be a better idea performance-wise, depending on what you are planning to do with it later.
There is no real question here, so I'm assuming you are asking for "code review"
The "neat" way is of course to create an operator<< that takes your inner structure.
Aside from that, you may want to look at using iterators to walk your way through your vector - that way, you should be able to change your vector for any other container type without having to change the loop(s) that print things.
Use longer variable names than x and y for your vector and temporary student.
Use setw to print fields at the same width every time.
I'm sure there are plenty of other suggestions too.
As the comments point to, it turns out that you're not including the string header file.