Template argument deduction/substitution failed: - c++

I have a compile error when using "output_array()" in a templated member function, the following code is a simple example:
#include <iostream>
using namespace std;
int menu()
{
int opt;
cout << "\n**********MENU**********";
cout << "\n1. Print the Array in reverse order";
cin >> opt;
return opt;
}
void input_array(int b[], int n)
{
cout << "\nEnter the elements of the array";
for (int i = 0; i < n; i++)
{
cin >> b[i];
}
return;
}
void output_array(int c[], int n)
{
for (int j = 0; j < n; j++)
{
cout << c[j] << " ";
}
return;
}
void rev_arr(int b[], int n)
{
int start = 0, end = n - 1;
cout << "Array before reversing : " << output_array(b, n);
for (int i = 0; i < n / 2; i++)
{
float temp = b[start];
b[start] = b[end];
b[end] = temp;
start++;
end--;
}
cout << "Array after reversing : " << output_array(b, n);
return;
}
void task(int b[], int n, int opt)
{
switch (opt)
{
case 1:
rev_arr(b, n);
break;
default:
cout << "!!! Sorry Wrong Choice !!!";
}
return;
}
int main()
{
int size;
int a[50];
cout << "\n You can Enter 50 elements in the array.\nHow much you want to enter?";
cin >> size;
input_array(a, size);
int opt = menu();
task(a, size, opt);
return 0;
}

The output_array(int*, int) is a printing function, not an opertot<< overlaod. Therefore, your can't place output_arrry(b, n) after operator<<. Simple separate into two statments:
Change
cout << "Array after reversing : " << output_array(b, n); // Not good.
into
cout << "Array after reversing : "; output_array(b, n); // ok.
Or you have to write an operator<< overloading, give rules for operator<< to print you array. But, before doing this, you have to bind the size n in your array (as some kind of structure). The size is needed to be used in the function operator<<.

Related

error: invalid types 'int[int]' for array subscript|

the code returns error: invalid types 'int[int]' for array subscript| and everything else seems to run fine. What can I do about it ? (line 10,22,23)
#include <iostream>
using namespace std;
int n, x[50], y[50], z[50];
void citire(int &n, int v)
{
int i;
cin >> n;
for (int i = 1; i <= n; i++)
{
cout << "v[" << i << "]=";
cin >> v[i];
}
}
void afisare(int n, int v[])
{
int i;
for (i = 1; i <= n; i++)
cout << v[i] << " " << endl;
}
void s(unsigned n, int x[], int y[], int z[])
{
int i;
for (i = 1; i <= n; i++)
z[i] = abs(x[i] - y[i]);
}
int main()
{
cout << "n=";
cin >> n;
cout << "x[]:" << endl;
citire(n, x);
cout << "y[]:" << endl;
citire(n, y);
cout << "Elementele primului vector" << endl;
afisare(n, x);
cout << "Elementele celui de-al doilea vector:" << endl;
afisare(n, y);
s(n, x, y, z);
cout << "z[]:" << endl;
return 0;
}
You are using v as an array, but it isn't an array, it is int. You probably want to use int* v.
void citire(int &n, int* v) {
// ...
cin>>v[i];
}

How to pass array size to different functions?

I have a problem and it seems like I cannot find a proper answer that would do the trick... So I have this static array arr[some_number] and I want to have a menu which does things with that array. Of course 1 of the options is to fill the array. Everything should be in separate functions. Here is the first one:`
void fill_array(int arr[], const int size) {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
}
`
There should be the option to let the user input how much elements he wants for the array, obv. n < some_number in this case... but with this comes my question : How can I pass the variable n in this particular case to another function so it can illiterate the number of elements the user input but not the const size of the array. Thanks in advance.
The best option is to separate responsibilities. A function like fill_array() has no business prompting the user for the array size at all. It already has a size value being passed in as input, just use that value as-is:
void fill_array(int arr[], const int size)
{
for (int i = 0; i < size; i++)
cin >> arr[i];
}
Prompt the user beforehand, and then pass the entered size to your functions as needed, eg:
int ask_user_for_size(int max_number)
{
int n;
do
{
cout << "Enter a number between 1 - " << max_number << ": ";
cin >> n;
if ((n > 0) && (n <= max_number)) break;
cout << "Invalid number, try again" << endl;
}
while (true);
return n;
}
void fill_array(int arr[], const int size)
{
for (int i = 0; i < size; i++)
cin >> arr[i];
}
void output_array(const int arr[], const int size)
{
for (int i = 0; i < size; i++)
cout << arr[i];
}
...
int arr[some_number];
int n = ask_user_for_size(some_number);
cout << "Enter " << n << " numbers: ";
fill_array(arr, n);
output_array(arr, n);
Alternatively:
int ask_user_for_size()
{
int n;
do
{
cout << "Enter a number greater than 0: ";
cin >> n;
if (n > 0) break;
cout << "Invalid number, try again" << endl;
}
while (true);
return n;
}
void fill_array(int *arr, const int size)
{
for (int i = 0; i < size; i++)
cin >> arr[i];
}
void output_array(const int *arr, const int size)
{
for (int i = 0; i < size; i++)
cout << arr[i];
}
...
int n = ask_user_for_size();
int *arr = new int[n];
cout << "Enter " << n << " numbers: ";
fill_array(arr, n);
output_array(arr, n);
delete[] arr;

Getting (lldb) output and hang on runtime

I have a simple program that is calculating factorials, permutations and combinations. I feel good about my math but for whatever reason I cannot get this program to execute. Full disclosure I am new student to C++. Here is my code:
#include <iostream>
using namespace std;
int factorial(int);
int permutations(int, int);
int combinations (int ,int);
void perms_and_combs(int, int, int&, int&);
int numPerms;
int numCombs;
int main() {
int factorialVal;
cout << "enter an int!\n";
cin >> factorialVal;
cout << "The factorial of " << factorialVal << " is " << factorial(factorialVal) << endl;
int permVal1;
int permVal2;
do {
cout << "Input a two values: ";
cin >> permVal1;
cout << ", ";
cin >> permVal2;
} while ( permVal1 < 0 || permVal2 > permVal1);
cout << "test"; // This line doesn't get executed
perms_and_combs(permVal1, permVal2, numPerms, numCombs);
cout << "Number of permutations: "<<numPerms << ". Number of combinations: " << numCombs;
return 0;
}
int factorial(int n) {
int product = 1;
for (int i = 1; i <= n; i++) {
product *= i;
}
return product;
}
int permutations (int n, int k) {
int result;
int denominator = n-k;
cout << denominator;
result = (factorial(n)/factorial(denominator));
return result;
}
int combinations (int n, int k) {
int result;
result = permutations(n, k) * (1/factorial(k));
return result;
}
void perms_and_combs(int n, int k, int& numPerms, int& numCombs) {
numPerms = permutations(n, k);
numCombs = combinations(n, k);
return;
}

Passing 2D array to a Function in c++

I am Having Problem with Passing a 2D array to a c++ Function. The function is supposed to print the value of 2D array. But getting errors.
In function void showAttributeUsage(int)
Invalid types for int(int) for array subscript.
I know the problem is with the syntax in which I am passing the particular array to function but I don't know how to have this particular problem solved.
Code:
#include <iostream>
using namespace std;
void showAttributeUsage(int);
int main()
{
int qN, aN;
cout << "Enter Number of Queries : ";
cin >> qN;
cout << "\nEnter Number of Attributes : ";
cin >> aN;
int attVal[qN][aN];
cout << "\nEnter Attribute Usage Values" << endl;
for(int n = 0; n < qN; n++) { //for looping in queries
cout << "\n\n***************** COLUMN " << n + 1 << " *******************\n\n";
for(int i = 0; i < aN; i++) { //for looping in Attributes
LOOP1:
cout << "Use(Q" << n + 1 << " , " << "A" << i + 1 << ") = ";
cin >> attVal[n][i];
cout << endl;
if((attVal[n][i] > 1) || (attVal[n][i] < 0)) {
cout << "\n\nTHE VALUE MUST BE 1 or 0 . Please Re-Enter The Values\n\n";
goto LOOP1; //if wrong input value
}
}
}
showAttributeUsage(attVal[qN][aN]);
cout << "\n\nYOUR ATTRIBUTE USAGE MATRIX IS\n\n";
getch();
return 0;
}
void showAttributeUsage(int att)
{
int n = 0, i = 0;
while(n != '\0') {
while(i != '\0') {
cout << att[n][i] << " ";
i++;
}
cout << endl;
n++;
}
}
I really suggest to use std::vector : live example
void showAttributeUsage(const std::vector<std::vector<int>>& att)
{
for (std::size_t n = 0; n != att.size(); ++n) {
for (std::size_t i = 0; i != att.size(); ++i) {
cout << att[n][i] << " ";
}
cout << endl;
}
}
And call it that way:
showAttributeUsage(attVal);
Looking at your code, I see no reason why you can't use std::vector.
First, your code uses a non-standard C++ extension, namely Variable Length Arrays (VLA). If your goal is to write standard C++ code, what you wrote is not valid standard C++.
Second, your initial attempt of passing an int is wrong, but if you were to use vector, your attempt at passing an int will look almost identical if you used vector.
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
typedef std::vector<int> IntArray;
typedef std::vector<IntArray> IntArray2D;
using namespace std;
void showAttributeUsage(const IntArray2D&);
int main()
{
int qN, aN;
cout << "Enter Number of Queries : ";
cin >> qN;
cout << "\nEnter Number of Attributes : ";
cin >> aN;
IntArray2D attVal(qN, IntArray(aN));
//... Input left out ...
showAttributeUsage(attVal);
return 0;
}
void showAttributeUsage(const IntArray2D& att)
{
for_each(att.begin(), att.end(),
[](const IntArray& ia) {std::copy(ia.begin(), ia.end(), ostream_iterator<int>(cout, " ")); cout << endl;});
}
I left out the input part of the code. The vector uses [] just like a regular array, so no code has to be rewritten once you declare the vector. You can use the code given to you in the other answer by molbdnilo for inputing the data (without using the goto).
Second, just to throw it into the mix, the showAttributeUsage function uses the copy algorithm to output the information. The for_each goes throw each row of the vector, calling std::copy for the row of elements. If you are using a C++11 compliant compiler, the above should compile.
You should declare the function like this.
void array_function(int m, int n, float a[m][n])
{
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
a[i][j] = 0.0;
}
where you pass in the dimensions of array.
This question has already been answered here. You need to use pointers or templates. Other solutions exists too.
In short do something like this:
template <size_t rows, size_t cols>
void showAttributeUsage(int (&array)[rows][cols])
{
for (size_t i = 0; i < rows; ++i)
{
std::cout << i << ": ";
for (size_t j = 0; j < cols; ++j)
std::cout << array[i][j] << '\t';
std::cout << std::endl;
}
}
You're using a compiler extension that lets you declare arrays with a size determined at runtime.
There is no way to pass a 2D array with such dimensions to a function, since all but one dimension for an array as a function parameter must be known at compile time.
You can use fixed dimensions and use the values read as limits that you pass to the function:
const int max_queries = 100;
const int max_attributes = 100;
void showAttributeUsage(int array[max_queries][max_attributes], int queries, int attributes);
int main()
{
int attVal[max_queries][max_attributes];
int qN = 0;
int aN = 0;
cout << "Enter Number of Queries (<= 100) : ";
cin >> qN;
cout << "\nEnter Number of Attributes (<= 100) : ";
cin >> aN;
cout << "\nEnter Attribute Usage Values" << endl;
for (int n = 0; n < qN; n++)
{
cout << "\n\n***************** COLUMN " << n + 1 <<" *******************\n\n";
for (int i = 0; i < aN; i++)
{
bool bad_input = true;
while (bad_input)
{
bad_input = false; // Assume that input will be correct this time.
cout << "Use(Q" << n + 1 << " , " << "A" << i + 1 << ") = ";
cin >> attVal[n][i];
cout << endl;
if (attVal[n][i] > 1 || attVal[n][i] < 0)
{
cout << "\n\nTHE VALUE MUST BE 1 or 0 . Please Re-Enter The Values\n\n";
bad_input = true;
}
}
}
}
cout << "\n\nYOUR ATTRIBUTE USAGE MATRIX IS\n\n";
showAttributeUsage(attVal, qN, aN);
getch();
return 0;
}
void showAttributeUsage(int att[max_queries][max_attributes], int queries, int attributes)
{
for (int i = 0; i < queries; i++)
{
for (int j = 0; j < attributes; j++)
{
cout << att[i][j] << " ";
}
cout << endl;
}
}
For comparison, the same program using std::vector, which is almost identical but with no size limitations:
void showAttributeUsage(vector<vector<int> > att);
int main()
{
cout << "Enter Number of Queries (<= 100) : ";
cin >> qN;
cout << "\nEnter Number of Attributes (<= 100) : ";
cin >> aN;
vector<vector<int> > attVal(qN, vector<int>(aN));
cout << "\nEnter Attribute Usage Values"<<endl;
for (int n = 0; n < qN; n++)
{
cout<<"\n\n***************** COLUMN "<<n+1<<" *******************\n\n";
for (int i = 0; i < aN; i++)
{
bool bad = true;
while (bad)
{
bad = false;
cout << "Use(Q" << n + 1 << " , " << "A" << i + 1 << ") = ";
cin >> attVal[n][i];
cout << endl;
if (attVal[n][i] > 1 || attVal[n][i] < 0)
{
cout << "\n\nTHE VALUE MUST BE 1 or 0 . Please Re-Enter The Values\n\n";
bad = true;
}
}
}
}
cout << "\n\nYOUR ATTRIBUTE USAGE MATRIX IS\n\n";
showAttributeUsage(attVal);
getch();
return 0;
}
void showAttributeUsage(vector<vector<int> > att);
{
for (int i = 0; i < att.size(); i++)
{
for (int j = 0; j < att[i].size(); j++)
{
cout << att[i][j] << " ";
}
cout << endl;
}
}
The Particular Logic worked for me. At last found it. :-)
int** create2dArray(int rows, int cols) {
int** array = new int*[rows];
for (int row=0; row<rows; row++) {
array[row] = new int[cols];
}
return array;
}
void delete2dArray(int **ar, int rows, int cols) {
for (int row=0; row<rows; row++) {
delete [] ar[row];
}
delete [] ar;
}
void loadDefault(int **ar, int rows, int cols) {
int a = 0;
for (int row=0; row<rows; row++) {
for (int col=0; col<cols; col++) {
ar[row][col] = a++;
}
}
}
void print(int **ar, int rows, int cols) {
for (int row=0; row<rows; row++) {
for (int col=0; col<cols; col++) {
cout << " | " << ar[row][col];
}
cout << " | " << endl;
}
}
int main () {
int rows = 0;
int cols = 0;
cout<<"ENTER NUMBER OF ROWS:\t";cin>>rows;
cout<<"\nENTER NUMBER OF COLUMNS:\t";cin>>cols;
cout<<"\n\n";
int** a = create2dArray(rows, cols);
loadDefault(a, rows, cols);
print(a, rows, cols);
delete2dArray(a, rows, cols);
getch();
return 0;
}
if its c++ then you can use a templete that would work with any number of dimensions
template<typename T>
void func(T& v)
{
// code here
}
int main()
{
int arr[][7] = {
{1,2,3,4,5,6,7},
{1,2,3,4,5,6,7}
};
func(arr);
char triplestring[][2][5] = {
{
"str1",
"str2"
},
{
"str3",
"str4"
}
};
func(triplestring);
return 0;
}

How do I return my dynamically allocated array?

So for my problem I need to have a dynamically allocated array that is to be created in the main function and populated in another function. The issue I'm having is that I then need to use that array in other functions and my array has no value after I populate it in my function (or at least this seems to be the case) Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
//prototypes
int getNumber();
void getMovieData(int *ptrToArray, int arraySize);
void sort(int *ptrToArray, int arraySize);
double getAverage(int *ptrToArray, int arraySize);
void print(int *ptrToArray, int arraySize);
int main()
{
int stuNum = 0;
int* stuArray;
stuArray = new int[stuNum];
getMovieData(stuArray, stuNum);
cout << "--- Here is the data you entered ---" << endl;
print(stuArray, stuNum);
sort(stuArray, stuNum);
cout << "--- Here is the data you entered sorted ---" << endl;
print(stuArray, stuNum);
cout << fixed << setprecision(2);
cout << "Here is the average of your survey" << getAverage(stuArray, stuNum) << endl;
system("pause");
return 0;
}
int getNumber()
{
int userNum;
cin >> userNum;
while (userNum <= 0)
{
cout << "Error number must be greater than zero." << endl;
cin >> userNum;
}
return userNum;
}
void getMovieData(int *ptrToArray, int arraySize)
{
cout << "Enter the number of students being surveyed: ";
arraySize = getNumber();
for (int i = 0; i < arraySize; i++)
{
cout << "Enter the movies seen by Student " << i + 1 << ": ";
ptrToArray[i] = getNumber();
}
return;
}
void sort(int *ptrToArray, int arraySize)
{
for (int i = 0; i < arraySize; i++)
{
for (int j = 0; j < arraySize - 1; j++)
{
if (ptrToArray[j] > ptrToArray[j + 1])
{
int temp = ptrToArray[j];
ptrToArray[j] = ptrToArray[j + 1];
ptrToArray[j + 1] = temp;
}
}
}
}
double getAverage(int *ptrToArray, int arraySize)
{
int total = 0;
for (int i = 0; i < arraySize; i++) { total = total + ptrToArray[i]; }
return total;
}
void print(int *ptrToArray, int arraySize)
{
for (int i = 0; i < arraySize; i++) { cout << ptrToArray[i] << "\t"; }
cout << endl;
}
You are allocating an array with zero elements. Change the value of stuNum to a positive number representing the number ints you need.