Visual Studio Gives Ambiguous Error for No Real Reason - c++

It gives the following error:
error C2872: 'count' : ambiguous symbol
Count variable has been declared as a global variable and the code compiles and runs in Sublime Text. Don't understand why Visual Studio is crying over it.
#include <iostream>
#include <fstream>
using namespace std;
int** am; // Adjacency matrix
int* ar, * ar2; // Arrays to work with
int n; // Number of nodes
int node1, node2, k; // For reading input from the console
int count;
bool checkReachability(int, int, int);
void fillArray(int);
void updateArray(int,int);
void freeMemory();
int main() {
ifstream in;
in.open("Input2.txt");
int a, b;
if(in.is_open()) {
in >> n;
// Allocate memory on the heap dynamically for the adjacency matrix:
am = new int*[n];
ar = new int[n];
ar2 = new int[n];
for (int i = 0; i < n; i++) {
am[i] = new int[n];
}
// Initialize the values of the adjacency matrix with 0s and the principle diagonal with 1s initially:
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) {
am[i][j] = 1;
} else {
am[i][j] = 0;
}
}
}
while(!in.eof()) {
in >> a >> b;
am[a-1][b-1] = 1;
}
cout << "The adjacency matrix input is as follows: \n\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << am[i][j] << " ";
}
cout << endl << endl;
}
in.close();
} else {
cout << "\nError reading the input file\n\n";
}
char c;
do {
cout << "\nPlease enter the input (node1, node2, k): \n";
cin >> node1 >> node2 >> k;
fillArray(node1-1);
count = 0;
if(checkReachability(node1-1,node2-1,k)) {
cout << "\nReachable within " << k << " steps";
if (count < k) {
cout << " (actually " << count << ")";
}
cout << endl << endl;
} else {
cout << "\nNot reachable within " << k << " steps \n";
}
cout << "\nDo you want to continue? Y/N \n\n";
cin >> c;
} while (c == 'Y' || c == 'y');
freeMemory();
system("pause");
return 0;
}
bool checkReachability(int n1, int n2, int k) {
if (n1 == n2) return true;
count++;
if (count <= k) {
if (ar[n2] != 0) return true;
int x;
for (int i = 0; i < n; i++) {
if (ar[i] != 0 && i != n1) {
ar[i]++;
x = ar[i];
}
}
for(int i = 0; i < n; i++) {
ar2[i] = ar[i];
}
for(int i = 0; i < n; i++) {
if (ar2[i] == x) {
fillArray(i);
updateArray(x,i);
if (checkReachability(ar2[i], n2, k)) return true;
}
}
}
return false;
}
void fillArray(int x) {
// To fill the array with the adjacencies of a particular node
for(int i = 0; i < n; i++) {
ar[i] = am[x][i];
}
}
void updateArray(int x, int y) {
for(int i = 0; i < n; i++) {
if (ar[i] == 1 && i != y) {
ar[i] = x;
}
}
}
void freeMemory() {
// To free the dynamically allocated memory on the heap
for (int i = 0; i < n; i++) {
delete [] am[i];
}
delete [] ar;
delete [] ar2;
}

using namespace std is your problem.
Looks like the Microsoft implementation of either the iostream or fstream headers themselves include algorithm. This is causing the name clash with std::count().

So, as #Retiredninja suggested, if I choose to replace while(!in.eof()) with while(in >> a >> b) in:
while(!in.eof()) {
in >> a >> b;
am[a-1][b-1] = 1;
}
Does the rest of the code in the while loop remain the same or does it mean, the input has already been read into a and b when the condition is checked in while(in >> a >> b)?
And become the following:
while(in >> a >> b) {
am[a-1][b-1] = 1;
}
or does it remain:
while(in >> a >> b) {
in >> a >> b;
am[a-1][b-1] = 1;
}

Related

code to search an integer in a sorted matrix does not execute after taking input

The following piece of code takes the input but does not execute or return any output.It takes a matrix and its size and an integer to be searched as input. I am failing to understand the issue here.
#include<iostream>
using namespace std;
int main()
{
int n, m;
cin >> n >> m;
int a[n][m];
int t;
cin >> t;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> a[i][j];
}
}
int r = 0, c = m - 1;
bool found = false;
while (r < n && c >= 0)
{
if (a[r][c] == t)
{
found = true;
}
else if (a[r][c] < t)
{
r++;
}
else
{
c--;
}
}
if(found)
{
cout << "found";
}
else
{
cout << "not found";
}
return 0;
}
Writing break after the number is found gives what you want. You are not exiting the loop after a number has been found.
#include<iostream>
using namespace std;
int main()
{
int n, m;
cin >> n >> m;
int a[n][m];
int t;
cin >> t;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> a[i][j];
}
}
int r = 0, c = m - 1;
bool found = false;
while (r < n && c >= 0)
{
if (a[r][c] == t)
{
found = true;
break;
// ^^^^^^^
}
else if (a[r][c] < t)
{
r++;
}
else
{
c--;
}
}
if(found)
{
cout << "found";
}
else
{
cout << "not found";
}
return 0;
}
UPDATE 1.0: Updated code considering comments of variable length array. Used vector in C++ to achieve the same purpose.
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int n, m;
cin >> n >> m;
// Using vector of vectors instead of 2-D array
vector< vector <int> > a(n);
for(int i = 0; i < n; i++){
a[i] = vector<int> (m);
}
int t;
cin >> t;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> a[i][j];
}
}
int r = 0, c = m - 1;
bool found = false;
while (r < n && c >= 0)
{
if (a[r][c] == t)
{
found = true;
break;
// ^^^^^^^
}
else if (a[r][c] < t)
{
r++;
}
else
{
c--;
}
}
if(found)
{
cout << "found";
}
else
{
cout << "not found";
}
return 0;
}

Realize "-" operator overloading as a friend function of class

I try to realize difference of sets with "-". For example:
Set a = 1 2 3 4;
Set b = 3 4 5 6;
Set c = a - b; // (1 2);
How i should overload operator? I tried to use frienldy function, but it can't work with variable "size". Visual Studio show error "c2597" at 28th line (size++;)
I can't understand, how to overloading "-" for using it with two sets. When I overload method of class, i can use only one argument. When i use friend-function, i can use twi arguments (Set a, Set b), but i can't work with variable "size".
#include <iostream>
#include <locale.h>
#include <conio.h>
#include <vector>
using namespace std;
class Set {
private:
int size;
vector <int> vect;
public:
Set() { size = 0; }
~Set() { vect.clear(); }
void Enter();
void Show();
friend Set operator-(Set a, Set b)
{
size = 0;
vect.clear();
int i, j, n = 0;
for (i = 0; i < a.size; i++) {
int cnt = 0;
for (j = 0; j < b.size; j++)
{
if (a.vect[i] == b.vect[j]) cnt++;
}
if (cnt == 0) {
size++;
vect.push_back(a.vect[i]);
}
}
return a;
}
void add()
{
int element;
cout << "Введите новый элемент " << endl;
cin >> element;
size = size + 1;
vect.push_back(element);
}
};
void Set::Enter() {
cout << "Введите размер " << endl;
cin >> size;
vect.resize(size);
cout << "Введите элементы :" << endl;
for (int i = 0; i < size; i++)
{
cin >> vect[i];
}
}
void Set::Show() {
cout << "Множество: " << endl;
for (int i = 0; i < size; i++)
cout << vect[i] << " ";
cout << endl;
}
int main() {
setlocale(LC_ALL, "RUS");
Set a;
a.Enter();
Set b;
b.Enter();
Set c;
c = a - b;
c.Show();
c.add();
c.Show();
_getch();
return 0;
}
UPD:
I made it through method:
Set operator-(const Set& b)
{
Set a = *this;
Set tmp;
tmp.size = 0;
vect.clear();
int i, j, n = 0;
for (i = 0; i < a.size; i++) {
int cnt = 0;
for (j = 0; j < b.size; j++)
{
if (a.vect[i] == b.vect[j]) cnt++;
}
if (cnt == 0) {
tmp.size++;
tmp.vect.push_back(a.vect[i]);
}
}
return tmp;
}
friend functions are not member methods, so you have to remove/replace usage of (implicit) this as size = 0, you might add extra object:
friend Set operator-(Set a, Set b)
{
Set res;
for (int i = 0; i < a.size; i++) {
int cnt = 0;
for (int j = 0; j < b.size; j++)
{
if (a.vect[i] == b.vect[j]) cnt++;
}
if (cnt == 0) {
res.size++;
res.vect.push_back(a.vect[i]);
}
}
return res;
}

Sequence for numbers in a vector

void Numbers()
{
do
{
cout << "Enter the value for the sequence: ";
cin >> K;
if ( K <= 3)
{
cout << "Write a bigger number!" << endl;
}
} while(K <= 3);
cout << "Enter the first number: ";
cin >> N;
}
double Sum()
{
vector<double> arr(K);
arr.push_back(N);
for (int i=0; i < arr.size(); i++)
arr.at(i)=i;
cout << "Vector contains: ";
for (int i=0; i < arr.size(); i++)
cout << arr.at(i);
int main()
{
Numbers();
Sum();
return 0;
}
Write a program that generates sequence of K (K > 3) numbers as follows:
The members of the above sequence are obtained as follows:
the first element is N;
the second one is N + 1;
the third - N * 2.
In other words, we consistently add 1 to each element and put it to the end of the sequence, then multiply it by 2 and again, put the product to the end of the sequence. Choose and implement a suitable data structure that can be used to generate the above sequence of numbers.
The users should enter values for K and first element N.
This is my current code(in the code above). I don`t realy know where to go from here onward to be completely honest. Any suggestions on how to create the sequence from the condition above?
You can use this code to get what you want:
#include <iostream>
#include <vector>
using namespace std;
vector<double> createOutputArray (int K, int N)
{
vector<double> arr;
int tmp = N;
arr.push_back(tmp);
for(int i=1; i+2<=K; i+=2)
{
arr.push_back(++tmp);
arr.push_back(tmp * 2);
tmp *= 2;
}
if(K % 2 == 0)
arr.push_back(++tmp);
return arr;
}
int main()
{
int K;
double N;
do
{
cout << "Enter the value for the sequence: ";
cin >> K;
if ( K <= 3)
{
cout << "Write a bigger number!" << endl;
}
} while(K <= 3);
cout << "Enter the first number: ";
cin >> N;
vector<double> output = createOutputArray(K, N);
for (int i=0; i < output.size(); i++)
{
cout << output.at(i);
if(i < output.size()-1)
cout << ",";
else
cout << endl;
}
return 0;
}
Here is one possibility, using a generator to produce the next element in the sequence.
class Seq
{
public:
Seq(int n) : n(n) {}
int operator*() const { return n; }
Seq operator++(int)
{
Seq old(n);
n = fns[fn](n);
fn = 1 - fn;
return old;
}
private:
int n;
int fn = 0;
std::function<int(int)> fns[2] = {[](int x) { return x + 1; },
[](int x) { return x * 2; }};
};
int main()
{
int N = 1;
int K = 20;
Seq seq(N);
for (int i = 0; i < K; i++)
{
std::cout << *seq++ << ' ';
}
std::cout << std::endl;
}

MAX value of matrix and saving indexes in the same loop

I get a NxM sized matrix and I have to find the max value, the number of max values and the lines that contain it.
I tired using three for{for{}} loops, but it took too long. This method seems to work for small inputs, but when I try it with a 1000x1000 matrix, it finishes before it even takes all the input.
I realise this may be too much of a noob question, but I couldn't find anything else.
Here's my code:
#include <iostream>
using namespace std;
int main()
{
int n, m;
int crnt{-51}, cnt{0};
cin >> n >> m;
int vekt[m];
int lines[n];
int inp;
for(int i=0; i<n; i++)
{
for(int p=0; p<m; p++)
{
cin >> vekt[p];
}
for(int j=0; j<m; j++)
{
if(vekt[j] == crnt)
{
lines[cnt] = i + 1;
cnt += 1;
}
if(vekt[j] > crnt)
{
crnt = vekt[j];
lines[0] = i + 1;
cnt = 1;
}
}
}
cout << cnt;
for(int i=0; i<cnt; i++)
{
cout << " " << lines[i];
}
return 0;
}
EDIT : not using vector or [n] was just easier... I simply saved it to a variable and used a bool:
int main()
{
int n, m;
int crnt{-51}, cnt{0};
cin >> n >> m;
int vekt[m];
int lines[n];
int inp;
bool inLine;
inLine = false;
for(int i=0; i<n; i++)
{
inLine = false;
for(int j=0; j<m; j++)
{
cin >> inp;
if(inp == crnt && inLine == false)
{
lines[cnt] = i + 1;
cnt += 1;
inLine = true;
}
if(inp > crnt)
{
crnt = inp;
lines[0] = i + 1;
cnt = 1;
}
}
}
cout << cnt;
for(int i=0; i<cnt; i++)
{
cout << " " << lines[i];
}
return 0;
}
This cut the time by enough so that I went under the limit.
int vekt[m]; is not standard C++, it is a variable length array (which some compilers allow as extension). Use std::vector instead.
That would also fix the bug you currently have: If cnt >= n (i.e. if you find more maxima than the matrix has lines), you will go out of bounds of lines and your program will most likely crash (although anything could happen), which is more likely to happen with larger matrices.
You can do this instead:
Declaration and initialization:
std::vector<int> linesWithMaxima;
When you find another value equal to the current maximum:
linesWithMaxima.push_back(i+1);
When you find a new maximum (larger than current):
linesWithMaxima.clear();
linesWithMaxima.push_back(i+1);
Note that this will list a line with multiple (identical) maxima multiple times. If you want to avoid duplicates, you can either check that you have not already added the current line (linesWithMaxima.back() != i+1) or use std::sort, std::unique and std::vector::erase.
Other than that your code looks fine. I would recommend naming the loop indices better (line instead of i etc.) and possibly merging the p and j loop because separating them seems to have no purpose. And if you want the most negative integer, use std::numeric_limits<int>::lowest().
Check this realization, without STL and vectors:
void input_matrix(int **&matrix, int &lines, int &columns)
{
int m = 0, n = 0;
cout << "input lines count:";
cin >> m;
cout << "input rows count:";
cin >> n;
matrix = new int *[m];
for(int i = 0;i < m;i++)
matrix[i] = new int[n];
cout << endl << "input matrix:" << endl;
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
cin >> matrix[i][j];
lines = m;
columns = n;
}
void print_matrix(int **&matrix, int &lines, int &columns)
{
for(int i = 0; i < lines; i++)
{
for(int j = 0; j < columns; j++)
cout << matrix[i][j] << " ";
cout << endl;
}
}
int find_max(int **matrix, int lines, int columns, int &max_count)
{
int max = INT_MIN;
max_count = 0;
for(int i = 0; i < lines; i++)
for(int j = 0; j < columns; j++)
{
if(matrix[i][j] > max)
{
max = matrix[i][j];
max_count = 1;
}
else
if(matrix[i][j] == max)
++max_count;
}
return max;
}
int main()
{
int **matrix = nullptr;
int m=0, n=0, count=0;
input_matrix(matrix, n, m);
cout << endl;
print_matrix(matrix, n, m);
cout << endl;
int max = find_max(matrix, n, m, count);
cout << "max=" << max << " count=" << count << endl;
for(int i = 0; i < n; i++)
delete[]matrix[i];
delete []matrix;
}
As requested by mister Max Langhof I would also like to propose a more modern solution, based on the std::vector container, which does not need pointers and manual memory management. It's a simple class matrix:
#include <algorithm>
#include <iostream>
#include <vector>
#include <cstdint>
using namespace std;
class matrix
{
private:
vector<vector<int>> m_data;
public:
matrix(int cols, int rows)
{
m_data.resize(cols);
for(auto &r : m_data)
r.resize(rows);
}
int max_element()
{
int max = INT_MIN;
for(auto &row: m_data)
{
auto maxinrow = *std::max_element(row.begin(), row.end());
if(maxinrow > max)
max = maxinrow;
}
return max;
}
int element_count(int elem)
{
int count = 0;
for(auto &row : m_data)
count += std::count_if(row.begin(), row.end(), [elem](int a){return a == elem;});
return count;
}
friend istream& operator>>(istream &os, matrix &matr);
friend ostream& operator<<(ostream &os, matrix &matr);
};
Input and output operators could be realized like this:
istream& operator>>(istream &os, matrix &matr)
{
for(int i = 0; i < matr.m_data.size(); i++)
{
for(int j = 0; j < matr.m_data[i].size(); j++)
cin >> matr.m_data[i][j];
cout << endl;
}
return os;
}
ostream& operator<<(ostream &os, matrix &matr)
{
for(int i = 0; i < matr.m_data.size(); i++)
{
for(int j = 0; j < matr.m_data[i].size(); j++)
cout << matr.m_data[i][j] << " ";
cout << endl;
}
return os;
}
And a sample of using of this matrix:
int main()
{
int m = 5, n = 4;
matrix matr(m, n);
cout << "input matrix:" << endl;
cin >> matr;
cout << endl << matr;
int max = matr.max_element();
cout << "max: " << max << " count:" << matr.element_count(max) << endl;
}
Checkout something like this
#include <iostream>
#include <set>
#include <vector>
int main() {
int rowsNo, columnsNo;
std::cin >> rowsNo >> columnsNo;
std::vector<int> matrix(rowsNo*columnsNo);
//Creating matrix
for(auto row = 0; row < rowsNo; ++row) {
for (auto column = 0; column < columnsNo; ++column)
std::cin >> matrix[row*columnsNo + column];
}
auto maxValue = -51;
//Finding positions of maximums
std::set<int> linesWithMaxValue;
for (auto position = 0; position < matrix.size(); ++position) {
if(matrix[position] == maxValue)
linesWithMaxValue.insert(position / columnsNo);
else if(matrix[position] > maxValue) {
linesWithMaxValue.clear();
maxValue = matrix[position];
linesWithMaxValue.insert(position / columnsNo);
}
}
//Print info
const auto numberOfMaxValues = linesWithMaxValue.size();
std::cout << "Number of maxiums: " << numberOfMaxValues << std::endl;
std::cout << "Lines that contains maximum:";
for (const auto& lineId : linesWithMaxValue)
std::cout << " " << lineId;
return 0;
}

Matrix class: unknown problems in C++

My program compiles but has these problems:
It's not using the member function fill (now). When i got the fill function to work (a while ago), it didn't do adding, subtracting, and multiplication correctly because it didn't record the second matrix it was supposed to do those things with. I got it to work the way you see it now, but this is the result:
ubuntu:~/Desktop$ ./matrix
2
2
enter the matrix element by element(starting from the first row)
1
2
1
2
Segmentation fault (core dumped)
If someone can point out the mistakes, it would be greatly appreciated:
#include <iostream>
#include <cmath>
using namespace std;
class matrix
{
private:
int r;
int c;
double** arr;
double** arr2;
public:
matrix()
{
r = 1;
c = 1;
arr = 0;
arr2 = 0;
}
matrix(int rows, int columns)
{
r = row(r);
c = column(c);
arr = new double* [r];
for(int i =0; i<r; i++)
{
arr[i] = new double[c];
}
}
matrix(matrix& a)
{
r = a.row(r);
c = a.column(c);
arr = new double* [r];
for(int i =0; i<r; i++)
{
arr[i] = new double[c];
}
}
~matrix()
{
for( int i = 0 ; i < r ; i++ )
{
delete [] arr[i];
}
delete [] arr;
}
void copy()
{
arr2 = new double* [r];
for(int i =0; i<r; i++)
{
arr2[i] = new double[c];
}
for (int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
{
arr2[i][j] = arr[i][j];
}
}
}
int row(int r)
{
return r;
}
int column(int c)
{
return c;
}
void fill(const int& r, const int& c)
{
for (int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
{
cin>>arr[i][j];
}
}
}
void print()
{
for (int i=0; i < r; i++)
{
for (int j=0; j<c; j++)
{
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
}
void sum()
{
double ** arr2 = arr;
cout << "enter the matrix you want to add" << endl;
fill(r, c);
for (int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
{
arr[i][j] = (arr2[i][j] + arr[i][j]);
}
}
print();
}
void sub()
{
double ** arr2 = arr;
cout << "enter the matrix you want to subtract" << endl;
fill(r,c);
for (int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
{
arr[i][j] = (arr2[i][j]) - (arr[i][j]);
}
}
print();
}
void multiplication()
{
double ** arr2 = arr;
cout << "enter the matrix you want to multiply by" << endl;
fill(r,c);
int k =0;
double ** arrm = arr;
for(int i=0;i< r;i++)
{
for(int j=0;j< c;j++)
{
arrm[i][j] = 0;
for(k=0;k< r;k++)
{
arrm[i][j] = arrm[i][j] + arr2[i][k] * arr[k][j];
}
}
}
print();
}
bool check(const int r, const int c)
{
if(r==c)
{return true;}
else
{return false;}
}
void get_det(const int r, const int c)
{
if(check(r,c) == true)
{
int n = r;
Determinant(arr,n);
cout <<"the determinant is: "<< endl;
}
else
{
cout << "can't" << endl;
}
}
double Determinant(double** arr, int n)
{
double det = 0;
double** m = NULL;
if (n == 1)
{ det = arr[0][0];}
else if (n == 2)
{
det = arr[0][0] * arr[1][1] - arr[1][0] * arr[0][1];
}
else if (n == 3)
{
det = arr[0][0]*(arr[1][1]*arr[2][2] - arr[1][2]*arr[2][1])
+ arr[0][1]*(arr[1][2]*arr[2][0] - arr[1][0]*arr[2][2])
+ arr[0][2]*(arr[1][0]*arr[2][1] - arr[1][1]*arr[2][0]);
}
else if (n > 3)
{
for (int j1=0;j1<n;j1++)
{
m = new double* [n-1];
for (int i=0;i<n-1;i++)
m[i] = new double[n-1];
for (int i=1;i<n;i++)
{
int j2 = 0;
for (int j=0;j<n;j++)
{
if (j == j1) continue;
m[i-1][j2] = arr[i][j];
j2++;
}
}
det += pow(-1,1+j1+1) * arr[0][j1] * Determinant(m,n-1);
for (int i=0;i<(n-1);i++)
delete m[i];
delete m;
}
}
return(det);
}
};
int main()
{
int r,c,answer;
cin >> r >> c;
matrix g(r,c);
cout << "enter the matrix element by element(starting from the first row)" << endl;
g.fill(r,c);
cout << "do you want add (1=yes / 0=no)" << endl;
cin >> answer;
if(answer == 1)
{
g.sum();
}
else{}
cout << "do you want subtract (1=yes / 0=no)" << endl;
cin >> answer;
if(answer == 1)
{
g.sub();
}
else{}
cout << "do you want multiply (1=yes / 0=no)" << endl;
cin >> answer;
if(answer == 1)
{
g.multiplication();
}
else{}
cout << "do you want to know the determinant (1=yes / 0=no)" << endl;
cin >> answer;
if(answer == 1)
{
g.get_det(r,c);
}
else{}
return 0;
}