Pass Vector by reference and Get Error - c++

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.

Related

accessing a function using 2d array

i want to access the seating[row][col].getFirstName but with the following code i am getting an error and the same error in strcmp in the if condition can anyone explain what does it mean
Error C3867 'Guest::getFirstName': non-standard syntax; use '&' to
create a pointer to member
Auditorium.cpp
Auditorium::Auditorium(int rowNum, int columnNum) {
rowNum1 = rowNum;
columnNum1 = columnNum;
Guest** seating =new Guest*[rowNum];
for (int i = 0; i < rowNum; i++)
{
seating[i] = new Guest[columnNum];
Guest();
}
}
bool Auditorium::assignGuestAt(int row,int col, Guest* tempGuest){
if ((strcmp(seating[row][col].getFirstName ,"???")==0)&& (strcmp(seating[row][col].getLastName , "???")==0)) \\ error
{
for (int i = 0; i < row; i++)
{
seating[row][col].getFirstName= tempGuest->getFirstName;\\ error
seating[row][col].getLastName = tempGuest->getLastName;\\ error
return 1;
}
}
else {
return 0;
}
}
Auditorium.h
#include<iostream>
#include "guest.h"
using namespace std;
class Auditorium
{
private:
Guest **seating;
public:
Auditorium(int, int);
Guest* getGuestAt(int, int);
bool assignGuestAt(int, int, Guest *);
bool checkBoundaries(int, int);
void toString();
};
guest.cpp
#include<iostream>
#include"guest.h"
using namespace std;
Guest::Guest()
{
strcpy_s(firstName,"???");
strcpy_s(lastName, "???");
}
char* Guest::getFirstName()
{
return firstName;
}
char* Guest::getLastName()
{
return lastName;
}

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

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

C++ What's wrong with my DFS code?

I have tried to code the DFS algorithm as given in CLRS. Here's the code below. When I run it I got an error as "Your program stopped unexpectedly." When I debugged the code I got this line in the call stack "msvcrt!malloc()" and "operator new(unsigned int)". I'm using CodeBlocks. Where am I wrong?
#include<iostream>
#include<cstdlib>
#include<vector>
#include<list>
#include<utility>
#include<algorithm>
#include<string>
using namespace std;
struct prop
{
int p;
int value;
int d;
int f;
string color;
};
vector<prop>v;
prop make_prop(int a,int b,int c,int d,string e)
{
prop p = {a,b,c,d,e};
return p;
}
class Dfs
{
public:
int time;
vector<list<int> >adj;
Dfs(int nv)
{
v.resize(nv);
adj.resize(nv);
for(int i=0;i<nv;i++)
{
v[i].value = i;
v[i].p = -1;
v[i].color = "WHITE";
}
}
void addinput()
{
adj[0].push_back(1);
adj[0].push_back(2);
adj[0].push_back(3);
adj[1].push_back(0);
adj[1].push_back(3);
adj[2].push_back(0);
adj[2].push_back(3);
adj[3].push_back(0);
adj[3].push_back(1);
adj[3].push_back(2);
}
void dfs();
void dfsvisit(prop);
};
void Dfs::dfs()
{
time = 0;
for(int i=0;i<v.size();i++)
{
if(v[i].color == "WHITE")
{
dfsvisit(v[i]);
}
}
}
void Dfs::dfsvisit(prop m)
{
time++;
m.d = time;
m.color = "GRAY";
int val = m.value;
for(auto it = adj[val].begin();it != adj[val].end();it++)
{
if(v[*it].color == "WHITE")
{
v[*it].p = val;
dfsvisit(v[*it]);
}
}
m.color = "BLACK";
cout<<m.value;
time++;
m.f = time;
}
int main()
{
Dfs d(4);
d.addinput();
d.dfs();
return 0;
}
void Dfs::dfsvisit(prop m) // should be prop&
dfsvisit(prop m) will make a copy of the property while dfsvisit(prop& m) receives a reference, working directly on the property you passed to the function
the stack will overflow!
In function dfsvisit,you pass parameter by value,which will never change the actual parameter.You should pass parameter by reference.
void dfsvisit(prop& m);

undefined reference to function in main()

i tried to make a program on seperate files. Unfortunatelty i had erros while trying to build the code. It was pointing on undefined references to constuctors,destructos and function CzynnikiPierwsze. So i decied to put the whole code in one code. Still there is a problem in main() function: undefined reference to 'CzynnikiPierwsze(int)' Any ideas whats wrong? Here is the whole code:
#include <iostream>
#include <cctype>
#include <vector>
using namespace std;
vector<int> CzynnikiPierwsze(int);
class NieprawidlowaDana //wyjatki
{};
class SpozaZakresu
{};
class RozkladLiczby{
private:
int *tab;
public:
RozkladLiczby(int); //konstruktor
vector<int> CzynnikiPierwsze(int); //metoda
~RozkladLiczby();
};
/////////////////BODY of the CLASS/////////////////////////////////////
RozkladLiczby::~RozkladLiczby() //destruktor
{}
RozkladLiczby::RozkladLiczby(int n){
int* tab = new int[n+1];
int i,j;
for( i=0;i<=n;i++)
tab[i]=0; //zerujemy tablice
for( i=2;i<=n;i+=2)
tab[i]=2; //zajmujemy sie liczbami parzystymi
for(i=3; i<=n;i+=2)
for(j=i;j<=n;j+=i) //sito erastotesa
if(tab[j]==0)
tab[j]=i;
}
vector<int> RozkladLiczby::CzynnikiPierwsze(int m){
vector<int> tablica;
while(m!=1){
tablica.push_back(tab[m]);
m=m/tab[m];
}
return tablica;
}
////////////////////////END OF THE BODY//////////////////////////////
int parsuj(char* argz){
int i=0;
while(argz[i] != '\0'){ //funckja ktora konwertuje na int i sprawdza czy wprowadzaony zostal string
if( !isdigit(argz[i]))
throw NieprawidlowaDana();
i=i+1;
}
int x = stoi(argz);
if (x >= 2)
return x;
else
throw SpozaZakresu();
}
//////////////////GLOWNY BLOK///////////////////////////////////////
int main(int argc,char* argv[]){
vector<int> tablica,p;
int i,n;
int max;
for( i=1;i<=argc-1;i++){
n = parsuj(argv[i]);
tablica.push_back(n);
}
max=tablica[0];
for(i=1; i<=argc-1;i++){
if(tablica[i]>max)
max=tablica[i]; } // sprawdzamy max
RozkladLiczby odp = RozkladLiczby(max); //utwoorzylismy obiekt z maxa
for(unsigned int i=0;i<=tablica.size()-1;i++){
p=CzynnikiPierwsze(tablica[i]);
cout<<tablica[i]<<" = ";
int x= p[0];
int licznik = 1;
for(unsigned int j=1;j<=p.size()-1;j++){
if(x==p[j])
licznik++;
else if(licznik!=1)
cout<<x<<"^"<<licznik<<"*";
else
cout<<x<<"*";
}
cout<<endl;
}
return 0;
}
I would be grateful if u could solve this.
You have declared global function vector<int> CzynnikiPierwsze(int); but you have not defined it anywhere in your program. In your main you are calling global function and not the one which is your class member.

This code shows error "stu undeclared"?? what should i do

I know this error is because i have declared stu inside the for loop scope but its the necessity of the program.I want to declare an array for each test case (test case should all be input at once).Suggest me a way to achieve this.Is dynamic memory an alternative.
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
int t;
cin>>t;
int n[t],g[t];
int m =0;
for(int w=0;w<t;t++)
{
cin>>n[w]>>g[w];
int stu[n[w]];
for(int i=0;i<n[w];i++)
{
cin>>stu[i];
}
}
while(m<t)
{
int a,b;
int e;
e = (n[m]*(n[m]-1))/2;
int diff[e];
if (g[m]=1)
{
cout<<0<<endl;
return 0;
}
b=*(min_element(stu,stu+n[m]-1));
a=*(max_element(stu,stu+n[m]-1));
if (g[m]=n[m])
{
cout<<a-b<<endl;
return 0;
}
int z = 0;
for(int j=0;j<(n[m]-1);j++)
{
for(int k=(j+1);k<n[m];k++)
{
diff[z]=abs(stu[j]-stu[k]);
++z;
}
}
cout<<*(min_element(diff,diff+e-1))<<endl;
++m;
}
cin.ignore();
cin.get();
return 0;
}
You are declaring stu inside of a for loop, so it is limited to the scope of the loop. You then try to use it outside of the loop, where it is undeclared.
for(int w=0;w<t;t++)
{
...
int stu[n[w]]; // Beware: stu is a VLA. Non-standard C++.
// OK to use stu here
...
}
// stu doesn't exist here
Also note that standard C++ does not support variable length arrays (VLAs), which is what you are attempting to use in the declaration of stu, as well as here:
int t;
cin>>t;
int n[t],g[t];
You can replace these arrays by std::vector<int>:
#include <iostream>
#include <vector>
int main()
{
int t=0;
cin>>t;
std::vector<int> n(t);
std::vector<int> g(t);
std::vector<int> stu ...;
}
The line
int stu[n[w]];
is inside a block and outside that block it won't be seen. You should move it out of the block, but doing so of course you can't use n[w], being w the looping var. You coudl put a limit to the max value n[w] can have, e.g.
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
const int MAXV = 100;
int main()
{
int t;
cin>>t;
int n[t],g[t]; // <- supported by some compiler, but not std
int m =0;
int stu[MAXV];
for(int w=0;w<t;t++) {
cin>>n[w]>>g[w];
for(int i=0;i<n[w] && i < MAXV;i++) {
cin>>stu[i];
}
}
while(m<t) {
int a,b;
int e;
e = (n[m]*(n[m]-1))/2;
int diff[e];
if (g[m]==1) {
cout<<0<<endl;
return 0;
}
b=*(min_element(stu,stu+n[m]-1));
a=*(max_element(stu,stu+n[m]-1));
if (g[m]==n[m]) {
cout<<a-b<<endl;
return 0;
}
int z = 0;
for(int j=0;j<(n[m]-1);j++) {
for(int k=(j+1);k<n[m];k++) {
diff[z]=abs(stu[j]-stu[k]);
++z;
}
}
cout<<*(min_element(diff,diff+e-1))<<endl;
++m;
}
cin.ignore();
cin.get();
return 0;
}
(I've fixed a couple of assignment in conditional when I suppose you meant == and not =, but I've not tested if the code does what you expect: it just compile, with g++ but not with other compiler likely, see comment in code)