c++: vector of class instances, search by class member values failed - c++

I have the following program where I defined a vector of class Point. I pushed into this vector five Point instances, with their Ids. Then I tried to search by Id but didn't get the expected result. The following program didn't return anything.
#include<iostream>
#include<vector>
using namespace std;
class Point {
private:
int id;
public:
Point(){}
void setId(int k){ id=k; }
int GetId() { return id; }
};
int main()
{
vector<Point> datasets;
for(int i=0; i< 5; ++i){
Point temp;
temp.setId(i);
datasets.push_back(temp);
}
for(int i=0;i<5;i++){
if (datasets[i].GetId() ==4){
return i;
}
}
}

Your program is probably working just fine, I think you're mixing up return with cout to actually print it out to the console, currently you're not printing anything and you're just returning i to the OS because you use return in main, making it a status code.
To see the output, use cout:
#include<iostream>
#include<vector>
using namespace std;
class Point{
private:
int id;
public:
Point(){}
void setId(int k){id=k;}
int GetId(){return id;}
};
int main()
{
vector<Point> datasets;
for(int i=0; i< 5; ++i){
Point temp;
temp.setId(i);
datasets.push_back(temp);
}
for(int i=0;i<5;i++){
if (datasets[i].GetId() ==4){
cout << "i is : " << i << endl;
break;
}
}
}
Edit to answer OP's comment:
use : vector<Point> datasets(5);

you arent printing any thing because you put return i after for loop
its certain that you wont got any result
#include<iostream>
#include<vector>
using namespace std;
class Point{
private:
int id;
public:
Point(){}
void setId(int k){id=k;}
int GetId(){return id;}
};
int main()
{
vector<Point> datasets;
for(int i=0; i< 5; ++i){
Point temp;
temp.setId(i);
datasets.push_back(temp);
}
for(int i=0;i<5;i++){
if (datasets[i].GetId() ==4){
cout<<i<<endl;
}
}
system("pause");
return 0;
}
you can use : datasets.insert(datasets.begin()+i,temp);
instead of datasets.push_back(temp);
for more flexibility in adding elements at the index i in vector class

Related

Array of Structures:No matching function to call to and taking user input

I have written a code for Knapsack problem.The code is working perfectly when i hardcode the inputs but now i want to take the inputs from the user in the array of structures but it is showing error.How can i achieve this?
original code:
#include<iostream>
#include<algorithm>
using namespace std;
struct Item{
int value;
int weight;
Item(int value,int weight):value(value),weight(weight){
}
};
bool cmp(struct Item a,struct Item b){
float r1=(float)a.value/a.weight;
float r2=(float)b.value/b.weight;
//cout<<r1<<" "<<r2<<endl;
return r1>r2;
}
void knapsack(int m,int n,struct Item arr[]){
sort(arr,arr+n,cmp);
/* for(int i=0;i<n;i++){ //new sorted array
cout<<arr[i].value<<" "<<arr[i].weight<<" ";
}*/
cout<<endl;
float result[n];
for(int i=0;i<n;i++){
result[i]=0.0;
}
int rem=m;
int j=0;
for(j=0;j<n;j++){
if(arr[j].weight>rem){
break;
}
else{
result[j]=1;
rem=rem-arr[j].weight;
}
}
if(j<n){
result[j]=(float)rem/arr[j].weight;
}
for(int k=0;k<n;k++){
cout<<result[k]<<" ";
}
}
int main(){
struct Item arr[]={{25,18},{24,15},{15,10}};
knapsack(20,3,arr);
return 0;
}
Now i want to take user input in the array of structures but it shows an error "no matching function to call to"
#include<iostream>
#include<algorithm>
using namespace std;
struct Item{
int value;
int weight;
Item(int value,int weight):value(value),weight(weight){
}
};
bool cmp(struct Item a,struct Item b){
float r1=(float)a.value/a.weight;
float r2=(float)b.value/b.weight;
//cout<<r1<<" "<<r2<<endl;
return r1>r2;
}
void knapsack(int m,int n,struct Item arr[]){
sort(arr,arr+n,cmp);
/* for(int i=0;i<n;i++){ //new sorted array
cout<<arr[i].value<<" "<<arr[i].weight<<" ";
}*/
cout<<endl;
float result[n];
for(int i=0;i<n;i++){
result[i]=0.0;
}
int rem=m;
int j=0;
for(j=0;j<n;j++){
if(arr[j].weight>rem){
break;
}
else{
result[j]=1;
rem=rem-arr[j].weight;
}
}
if(j<n){
result[j]=(float)rem/arr[j].weight;
}
for(int k=0;k<n;k++){
cout<<result[k]<<" ";
}
}
int main(){
struct Item arr[10];
int n,m;
cin>>m>>n;
for(int i=0;i<n;i++){
cin>>arr[i].value>>arr[i].weight;
}
knapsack(m,n,arr);
return 0;
}
Check below code:
struct Item{
int value;
int weight;
Item(int value,int weight):value(value),weight(weight){
}
};
There is no default constructor. So the below line fails:
struct Item arr[10];
But the following line works:
struct Item arr[]={{25,18},{24,15},{15,10}};
Solution[1]: Provide a default constructor or remove the explicit constructor.
[1] There may be more problems in the code, but I looked into the one you pointed in your question.
You have provided parameterized constructor Item(int value,int weight), so compiler won't generate default constructor by itself.
You have to define the default constructor explicitly to make the below statement work since it needs default constructor.
struct Item arr[10];
But the below line of code uses the parameterized constructor you have provided.
struct Item arr[]={{25,18},{24,15},{15,10}};

get value from another class c++

Hello I have a getter in adjacencyMatrix class
int AdjacencyMatrix::getVertexFirst() const { return vertexFirst; }
and constructor
AdjacencyMatrix::AdjacencyMatrix() {
this->vertexCount=0;
this->vertexFirst=0;
this->edgeCount=0;
this->matrix=0;
this->wage=0;
}
bool AdjacencyMatrix::createFromFile(string path) {
fstream file;
file.open(path.c_str(), fstream::in);
if (file.good())
{
int vertexF,vertexE,wag;
file >> this->edgeCount;
file >> this->vertexCount;
file >> this->vertexFirst;
matrix = new int *[vertexCount];
wage = new int *[vertexCount];
for (int i = 0; i < vertexCount; i++)
{
matrix[i]=new int[vertexCount];
wage[i]=new int[vertexCount];
}
//fill matrix by zeros
for (int i = 0; i < vertexCount; i++)
{
for(int j=0; j<vertexCount;j++)
{
matrix[i][j]=0;
wage[i][j]=0;
}
}
// fill matrix by 1
for(int i=0; i<edgeCount; i++)
{
file >> vertexF >> vertexE >> wag;
this->matrix[vertexF][vertexE]=1;
this->wage[vertexF][vertexE]=wag;
}
file.close();
return true;
}
return false;
}
of course print works in Adjacency class
And now I want to have this value in Dijkstra class
//Dijkstra.cpp
#include "Dijkstra.h"
AdjacencyMatrix am;
bool Dijkstra::makeDijkstraAlgo() {
int vertexCount=am.getVertexCount();
int vertexFirst=am.getVertexFirst();
int **wage=am.getWage();
cout << vertexCount;
cout << vertexFirst;
.......... }
this is my main class
#include <iostream>
#include "Dijkstra.h"
#include "Screen.h"
using namespace std;
int main() {
AdjacencyMatrix am;
Dijkstra dijkstra;
am.createFromFile("matrix.txt");
dijkstra.makeDijkstraAlgo();
dijkstra.viewDijkstra();
return 0;
}
and this cout show only 0, but in AdjacencyMatrix show normal value. Can you help me ?
UPDATE
I notice that always will be 0 because I initialized value in constructor....
So How to make something like this
I create a matrix from file and add value to vertexCount etc.
am.createFromFile("matrix.txt");
now I want to get this value(vertexCount etc.) from adjacency matrix class to Dijkstry class and make
dijkstra.makeDijkstraAlgo();
dijkstra.viewDijkstra();
How can I solve it ?
You're creating one matrix but using another.
makeDijkstraAlgo uses the global matrix called ”am”, but main has its own matrix by the same name.
Get rid of the global and pass main's matrix to the function
bool Dijkstra::makeDijkstraAlgo(const AdjacencyMatrix& am) {
int vertexCount=am.getVertexCount();
int vertexFirst=am.getVertexFirst();
int **wage=am.getWage();
cout << vertexCount;
cout << vertexFirst;
// ...
}
int main() {
AdjacencyMatrix am;
Dijkstra dijkstra;
am.createFromFile("matrix.txt");
dijkstra.makeDijkstraAlgo(am);
dijkstra.viewDijkstra();
return 0;
}

declaring vectors in scope

In my In-Progress BigInt class, I am having trouble with the declaration of vectors. I am getting the errors:
prog.cpp: In function 'void setBig1(std::string, int)':
prog.cpp:45:3: error: 'big1' was not declared in this scope
big1.push_back(dig[x]);
^
prog.cpp: In function 'voidgetBig1(int)':
prog.cpp:50:11: error: 'big1' was not declared in this scope
cout << big1[x] ;
I believe that my getters and setters involved with the vector big1 are not recognizing the decleration of the vector in the 'public:' portion of the class definition. But I cannot find a solution or a definite reason for the errors. My code is Below:
//my bigInt class
#include <iostream>
#include <vector>
#include <string>
using namespace std;
//class, constructors
//overload operators methods
//add, subtract, multiply, divide
class bigInt{//class
public:
bigInt();
~bigInt();
void setString(string dig);
string getString(void);
int getDigitLength(void);
std::string digit;
int digitLength;
std::string digString;
void setBig1(string dig, int dLength);
std::vector<int> big1;
std::vector<int> big2;
void getBig1(int dLength);
};
//constructors
bigInt::bigInt(void){
std::vector<int> big1;
}
//deconstructor
bigInt::~bigInt(){
}
//getters/setters
void bigInt::setString(string dig){
digit= dig;
digitLength= (digit.length());
}
string bigInt::getString(){
return digit;
}
int bigInt::getDigitLength(){
return digitLength;
}
void setBig1(string dig, int dLength){
for(int x= 0; x<(dLength); x++)
{
big1.push_back(dig[x]);
}
}
void getBig1(int dLength){
for(int x= 0; x<(dLength); x++){
cout << big1[x] ;
}
}
int main(){
string digString= "1"; //string
bigInt my_int{};
//bigInt big1<int>;
my_int.setString(digString); //setInternalString to equal digString
cout << my_int.getString() << endl; //prints internal string
my_int.setBig1(my_int.getString(), my_int.getDigitLength());//sets big1 vector = to string
my_int.getBig1(my_int.getDigitLength()); //print big1 vector
}
I greatly appreciate any assistance.
You forgot to specify class to which the member functions are defined. Instead of
void setBig1(string dig, int dLength){
for(int x= 0; x<(dLength); x++)
{
big1.push_back(dig[x]);
}
}
void getBig1(int dLength){
for(int x= 0; x<(dLength); x++){
cout << big1[x] ;
}
write
void bigInt::setBig1(string dig, int dLength){
for(int x= 0; x<(dLength); x++)
{
big1.push_back(dig[x]);
}
}
void bigInt::getBig1(int dLength){
for(int x= 0; x<(dLength); x++){
cout << big1[x] ;
}
Also you could declare all getters with qualifier const because they do not change an object itself of the class. For example
class bigInt
{
//...
void getBig1(int dLength) const;
};
void bigInt::getBig1(int dLength) const
{
for ( int i = 0; i < dLength; i++ ) cout << big1[i] ;
}
and in general case instead of type int there is better to use at least type size_t or std::vector::size_type
The vectors themselves could be declared with the access control private.

coding error or compiler's fault

I was working on this code for a project on school and when I wanted to try debugging my code just got segmentation fault before even running the first line in main() so i was wondering if i miss something on my code or is the compiler's fault.
#include <iostream>
using namespace std;
class poly
{
public: int a[1000000];
private:
int forx(int x);
public:
poly(){cout<<"add";}
~poly(){cout<<"kill";}
void add();
void sum(int *x,int *y);
void dif(int *x,int *y);
void mult(int *x,int *y);
void renew();
};
void poly::add()
{
int i,n;
cin>>n;
a[0]=n;
for (i=1; i<=n; i++)
{
cin>>a[i];
}
}
int poly::forx(int x)
{
int s,i,p;
p=1;
for (i=1; i<=a[0]; i++)
{
s+=p*a[i];
p*=x;
}
return s;
}
void poly::sum(int *x,int *y)
{
int i,m=x[0]>y[0]?x[0]:y[0];
a[0]=m;
for (i=1; i<=a[0]; i++)
{
a[i]=x[i]+y[i];
}
}
void poly::dif(int *x,int *y)
{
int i,m=x[0]>y[0]?x[0]:y[0];
a[0]=m;
for (i=1; i<=a[0]; i++)
{
a[i]=x[i]-y[i];
}
for (i=a[0]; i>0; i--)
{
if (a[i]!=0) break;
a[0]--;
}
}
void poly::mult(int *x,int *y)
{
int i,j,k;
for (i=1; i<=(x[0]+y[0]-2); i++)
{
j=0;
k=y[0]-1;
while (j+k!=i)
{
if (j+k>i) k--;
if (j+k<i) j++;
}
while (j<x[0] && k>=0)
{
a[i]+=x[j]*y[k];
k--;
j++;
}
}
}
void poly::renew () {
int i;
for (i=1; i<=a[0]; i++)
{
cout<<a[i];
}
}
int main()
{
cout<<"starting";
poly w;
w.add();
poly h;
h.add();
poly o;
o.sum(w.a,h.a);
o.renew();
o.dif(w.a,h.a);
o.renew();
o.mult(w.a,h.a);
o.renew();
}
Becase of int a[1000000];, size of poly class is very large. Making a (actually you are making 3) local variable(s) of this class (on stack) would give you segmentation fault.
You can try making them static or move them to global scope or alloc them dynamically.
...
static poly w;
w.add();
static poly h;
h.add();
static poly o;
...
Another solution is to replace arrays with std::vector
change public: int a[1000000]; to
...
public: std::vector<int> a;
...
poly() : a(1000000) {cout<<"add";}
...
Now you can create local objects of this class.
Another related question Segmentation fault on large array sizes

Pass Vector by reference and Get Error

Following code is for test the pass the reference of a vector to a function. However, it will have some unknown fault. I got the error message from gdb as following:
Source is:
#include<iostream>
#include<vector>
using namespace std;
class ROLE
{
public:
ROLE(int);
int HP;
};
ROLE::ROLE (int input)
{
HP = input;
}
void checkVector(vector<ROLE>&input);
int main()
{
vector<ROLE> R;
ROLE K(102);
R.push_back(K);
K.HP = 111;
R.push_back(K);
checkVector(R);
return 1;
}
void checkVector(vector <ROLE> & input)
{
cout<<"size of vector "<<input.size()<<endl;
for(int i =0; i<input.size();i++)
{
cout<< input[i].HP<<endl;
}
}
I can't find the reason of the error. Any idea is appreciated!
I realized that error probably from the push_back, because I also get the error if I modified the code as following. Are there any idea about what happened?
#include<iostream>
#include<vector>
using namespace std;
class ROLE
{
public:
ROLE(int);
int HP;
};
ROLE::ROLE (int input)
{
HP = input;
}
int main()
{
vector<ROLE> R;
ROLE K(0);
K.HP=1;
R.push_back(K);
K.HP = 113;
R.push_back(K);
K.HP = 111;
R.push_back(K);
return 0;
}
Possible answer:
I get one way which can avoid the error.
Following is the no-error source.
#include<iostream>
#include<vector>
using namespace std;
class ROLE
{
public:
ROLE(int);
void constructAry(int inputHP);
int HP;
};
ROLE::ROLE (int input)
{
HP = input;
}
void ROLE::constructAry(int inputHP)
{
HP = inputHP;
}
void checkVector(vector<ROLE>&input);
int main()
{
vector<int> test;
vector<ROLE> R;
ROLE K(0);
K.constructAry(1);
R.push_back(K);
K.constructAry(2);
R.push_back(K);
K.constructAry(3);
R.push_back(K);
K.constructAry(4);
R.push_back(K);
checkVector(R);
return 1;
}
void checkVector(vector <ROLE> & input)
{
cout<<"size of vector "<<input.size()<<endl;
for(int i =0; i<input.size();i++)
{
cout<< input[i].HP<<endl;
}
}
So it seems that using a constructor-like function to modify the value of the same object and push_back the object in the vector can effectively avoid the bug.
The reason is ambiguous for me. Maybe the memory address's matter.