I know this sound easy to you guys but I think this may be different
Here is my simple code in which i am getting error in declaring Array
#include<iostream>
using namespace std;
int top=-1,capacity=2;
int arr[capacity];
main(){
}//main
A fixed length array needs a compile-time constant to declare its size. You need to declare capacity as const or constexpr in order to use it in an array declaration, eg:
#include <iostream>
using namespace std;
int top = -1;
const int capacity = 2;
int arr[capacity];
main(){
}
If you want to define the capacity at runtime then you need to use a dynamic array, like std::vector, eg:
#include <iostream>
#include <vector>
using namespace std;
int top = -1, capacity;
vector<int> arr;
main(){
capacity = ...;
arr.resize(capacity);
}
Related
I'm trying to build a class named "Tombola" which should contain as private variable an empty vector. This should be filled at runtime through the class member Tombola.estrai(), which generates a random number and insert it inside the vector named "order" by the method order.push_back(number). This is the class definition in the tombola.h header:
#ifndef TOMBOLA_H
#define TOMBOLA_H
#include <cstdlib>
#include <vector>
using namespace std;
class Tombola {
private:
bool on_off[90];
int tabellone[9][10];
int x_max = 9;
int y_max = 10;
vector<int> order;
public:
Tombola();
~Tombola();
void nuovo();
int estrai();
bool completato();
void stampa();
void stampa_tab();
};
#endif
And this is the implementation of constructor/destructor and Tombola::estrai() inside tombola.cc:
#include "tombola.h"
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <vector>
#include <iostream>
using namespace std;
Tombola::Tombola () {
vector<int> ord;
order = ord;
int z=1;
for(int i=0;i<90;i++) {
on_off[i] = false;
}
for(int j=0;j<=x_max;j++) {
for (int k=0;k<=y_max;k++) {
tabellone[j][k] = z;
z++;
}
}
}
Tombola::~Tombola() {
cout << "Tombola is destroyed" << endl;
}
int Tombola::estrai() {
srand(time(NULL));
int estrazione = int(ceil(rand()/double(RAND_MAX)*90));
on_off[estrazione]==true;
order.push_back(estrazione);
return order.back();
}
and this is the call to the method in the main.cpp file:
#include "tombola.h"
#include <cstdlib>
#include <iostream>
#include <vector>
#include <ctime>
using namespace std;
int main () {
Tombola natale;
cout << natale.estrai();
}
When I compile the program everything goes fine, but when I execute the main I get a segmentation fault error which seems to be due to some sort of allocation error when trying to store the item inside the order vector, as reported by the debugger. Could someone explain to me how to solve the error and why the error occours? Thank you.
The reason of segmentation fault is in the constructor. You have to change for(int j=0;j<=x_max;j++) to for(int j=0;j<x_max;j++) in order not to cross the bounds of the array.
for(int j=0;j<x_max;j++) {
for (int k=0;k<y_max;k++) {
tabellone[j][k] = z;
z++;
}
}
However, there are also some minor issues in the code that are worth being mentioned
declaring default-initialized ord vector and assigning it to order is pointless because order is already default-initialized.(See member initializer list for more information).
using namespace std; in a header file is a terrible idea, because if you had a large codebase, and had multiple source files where you want to include that header, everywhere the using statement will be applied, which probably is not desired.
I am trying to create a function that returns in main.cpp in the header and .cpp file and run it in the main function.
This process I do works on main.
#include <iostream>
#include <sstream>
#include "Cards.h"
using namespace std;
//this function returns array
int *function1(){
int a=12;
int b=13;
int c=14;
static int list[3]={a,b,c};
return list;
}
int main(int argc, const char * argv[]) {
int *list;
list=function1();
cout<<list[1]<<endl;
return 0;
}
However, I cannot do these in a header and a separate cpp file.
I have a Cards header
#ifndef Cards_H
#define Cards_H
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
class Cards{
public:
char suit; //A,H,D,C,S. A is empty card
int number; //00-13
int visibilty;//0 - 1. O invisible 1 is visible
int * function2();
};
#endif
This is the class cpp file
#include "Cards.h"
using namespace std;
//function
int Cards:: function2(){
int a=12;
int b=13;
int c=14;
int list[3]={a,b,c};
return list; // error code Cannot initialize return object of type 'int Cards::*' with an lvalue of type 'int [3]'
}
How do I fix this problem and run it in main?
As pointed out in the comments, there is already a SO thread
Return array in a function
which handles your issue.
If your really want to use C arrays then your program shall look like:
Cards_CStyle.h:
#ifndef Cards_CStyle_H
#define Cards_CStyle_H
using namespace std;
class Cards {
public:
int* function2(int arr[]);
};
#endif
Cards_CStyle.cpp:
#include "Cards_CStyle.h"
using namespace std;
//function
int* Cards::function2(int arr[]){
int a=12, b=13, c=14;
arr[0] = a;
arr[1] = b;
arr[2] = c;
return arr;
}
main_CStyle.cpp:
#include <iostream>
#include "Cards_CStyle.h"
using namespace std;
int main(int argc, const char * argv[]) {
int arr[3]; // Take care that all your functions use size <= 3
Cards cards;
int* list=cards.function2(arr);
cout<<list[1]<<endl;
return 0;
}
As recommended in the comments, you should use the containers of the STL, e.g. array for fixed length or vector for variable length. Assuming that fixed length of 3 will be fine for you, then your code would be looking like this:
Cards_STLStyle.h:
#ifndef Cards_STLStyle_H
#define Cards_STLStyle_H
#include<array>
using namespace std;
typedef array<int, 3> my_array;
class Cards {
public:
my_array function2();
};
#endif
Cards_STLStyle.cpp:
#include "Cards_STLStyle.h"
using namespace std;
//function
my_array Cards::function2(){
int a=12, b=13, c=14;
return my_array { a,b,c};
}
main_STLStyle.cpp:
#include <iostream>
#include <array>
#include "Cards_STLStyle.h"
using namespace std;
int main(int argc, const char * argv[]) {
Cards cards;
my_array list=cards.function2();
cout<<list[1]<<endl;
return 0;
}
Please find more information here:
array
I am trying to print the first value from each vector shown below in the main function.
#include <iomanip>
#include <map>
using namespace std;
typedef unsigned int vect;
int main() {
std::vector<vect> p;
vector<vect> a = { 4,2,3,1 };
vector<vect> b = { 4,2,3,1 };
vector<vect> c = { 4,2,3,1 };
vector<vect> d = { 4,2,3,1 };
int i;
for (i=0; i<a.size(); i++)
cout << a[i];
}
Function first_preference() from my function.cpp shown below
#include "function.h"
#include <string>
#include <iostream>
using namespace std;
person test::first_preference() const {
const person& first = p.front();
return first; //current first pref
}
The function is declared in this header class
#ifndef FUNCTION_H
#define FUCNTION_H
#include <vector>
typedef unsigned int person;
typedef unsigned int vect;
std::vector<vect> p;
class test {
public:
person first_preference() const;
};
#endif
I want the function first_preference() to be called from main() where the function should print the first value of each vector, how would I go about this?
I want the function first_preference() to be called from main() where the function should print the first value of each vector
Some issues:
You have a global std::vector<vect> p in your header file (which is not a good idea to begin with) which is shadowed by std::vector<vect> p in main. What you put in the p in main will not be accessible from instances of test. Those instances only knows about the global p.
You don't #include "function.h" in main.cpp so you can't create test objects in main.
If you #include "function.h" in main.cpp there's no need to typedef unsigned int vect; since you did that in function.h already. It's not an error, but confusing and unnecessary.
The vector<vect> instances a, b, c and d have no connection with test or any of the ps whatsoever so what you put in those vectors can't possibly be printed by instances of test unless you pass them on to test somehow.
You declare vectors of vect but first_preference() returns a person by value. vect and person happen to be aliases of the same fundamental type, but it seems like there is something wrong with this interface.
In main.cpp you don't instantiate a test, you iterate over a and first_preference() is never called so there's no hope for it to be used.
Why is “using namespace std;” considered bad practice?
I am using g++ 7.1.0, yet using begin() with array as an argument throws an error. My code is
#include <iostream>
#include<algorithm>
using namespace std;
int main()
{
int n;
cin>>n;
int a[n];
for(int i = 0; i < n; i++) {
cin>>a[i];
}
sort(begin(a), end(a));
return 0;
}
It says
no matching function for call to 'begin(int [n])'
int a[n]; is invalid statement in C++. C++ doesn't allow variable length array. It is allowed only in C since C99 standard. If you need dynamic array, you should be using std::vector 99% of the time in C++.
You can do this:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
int main() {
std::cout<<"Enter size of array\n";
int size;
std::cin>>size;
std::vector<int> v(size);
std::cout<<"Enter "<<size<< " elements\n";
for(size_t i=0;i<v.size();++i)
std::cin>>v[i];
std::sort(v.begin(),v.end());
std::cout<<"Sorted elements are: \n";
for(const auto& i : v)
std::cout<<i<<' ';
}
See live demo here.
#include <iterator>
<algorithm> is the wrong header for begin(), end(), and, well, all the iteration functions.
Also, for the iteration functions to work, the array must be sized with a compile-time constant, so, int a[10]; works, but int a[n]; does not.
you can do this:-
#include <algorithm>
int main(){
int arr[2000];
int n = sizeof(arr)/sizeof(arr[0]);
std::sort(arr, arr+n);
}
if you are using array instead of vector then use
sort(a,a+n);
Here is my code
main.cpp
#include <iostream>
#include "header.h"
#include "source.cpp"
using namespace std;
int main()
{
cout << "Hello world!" << endl;
int testarray[]={1,3,5,7};
mymatrix* first=new mymatrix(testarray,2,2);
return 0;
}
and header.h
using namespace std;
#include <iostream>
#include <string>
class mymatrix{
public:
int i;
int j;
int marray[];
mymatrix(int m[],int rows,int cols ) : marray(m),i(rows),j(cols)
{
cout<<"this is for testings ";
}
mymatrix()
{};
~mymatrix(){
// delete[] marray;
};
};
I get this error :Invalid use of non static data member mymatrix::i
what I wanna do is make a object of my
matrix class and pass an array
Convert it from
int marray[];
to
int *marray;
In addition, either use C paradigm or use C++ one but not the mixture.
Instead of
mymatrix* first=new mymatrix(testarray,2,2);
use
mymatrix first(testarray,2,2);
Let the compiler allocate and release the memory instead of you.
If you have no restriction about the C++ libraries that you use, consider std::vector library to manage your dynamic arrays.
Instad of managing memory out of the object, manage it inside the object specially inside constructor and destructor.