Passing a vector to constructor - c++

Iam new in C++ and iam trying to implement classes into my program. I have done similar program in java. But iam struggling to implement classes in c++. I want to pass a vector with strings from main to a class called Search.I can pass a vector either by value or reference. Iam using a vector * which means get vector address.This is what i was told. Iam not sure how i should refer to it. I am sure there are more mistakes in my code. Could please someone help me or explain me how to initialize vector in constructor and how to add a value so I can use the vector in the menthod?? Iam using Visual Studio PRO 2010. Many thanks for replies.
Search.h
// pragma once
#include "std_lib_facilities.h"
#include <vector>
class Search
{
public:
Search();
Search(int dd, int mm, int year,vector<string>* dat);
vector<string> get_result ();
~Search(void);
private:
int d;
int m;
int y;
vector<string> data;
};
Search.cpp
#include "Search.h"
#include <vector>
#include "std_lib_facilities.h"
Search::Search()
:d(1), m(1), y(2000), data(){} //data() is the vector but iam not sure if ihave set the value corectly
Search::Search(int dd, int mm, int year,vector<string>*dat)
:d(dd),m(mm),y(year), data(dat){}//no instance of constructor matches the construcor list -- this is the error iam getting
//iam trying to initiliaze the varibale data of type vector.But i dont know how to do it.
Search::~Search(void)
{
}
vector<string> Search::get_result () {// implementation where i need to use the data stored in a vector
}
//main program
#include "std_lib_facilities.h"
#include <string>
#include <sstream>
#include <stdio.h>
#include "Search.h"
#include <vector>
int main(){
int day, month, year; //iam gonna ask user to input these
day=20;
month=12;
year=2014;
vector<string>flight_info;
ifstream inputFile("flight.txt");
// test file open
if (inputFile) {
string value;
// read the elements in the file into a vector
while ( inputFile >> value ) {
flight_info.push_back(value);//this is the vector i want to pass to class Search
}
}
Search search(day,month,year,flight_info)
//this where i want to create object of Search class but iam gettin error -no instance of constructor matches the `enter code here`construcor list.
}

This defines a vector:
vector<string>flight_info;
This defined a vector member variable:
vector<string> data;
This invoke a constructor by passing the vector to it:
Search search(day,month,year,flight_info)
But this constructor expects a pointer to a vector!
Search(int dd, int mm, int year,vector<string>* dat);
You don't need to pass any of the standard containers around by pointer (and you're probably doing something wrong if you find yourself trying to).
You can rewrite your constructor to be Search(int dd, int mm, int year,vector<string> dat) to resolve your error. You only need to change the prototype of your constructor, because data(dat) will already correctly construct the member vector.

Related

how to use push_back in vector of a struct

hey guys i have created a struct node. one of its fields is a vector (path) where i want to store characters.however when i try to push_back a character the compiler says "error: ‘path’ was not declared in this scope"
#include <iostream>
#include <fstream>
#include <vector>
#include <iomanip>
#include <list>
#include <climits>
using namespace std;
struct node {
int weight;
bool pizza; // true an tin exo
vector <char> path;
int tetmimeni, tetagmeni; // i, j gia na vro geitones
} ;
node a;
int main(){
a.tetmimeni=0; // create start node
a.tetagmeni=0;
a.weight=0;
a.pizza=true;
a.path= path.push_back('S');
Replace a.path= path.push_back('S'); with just a.path.push_back('S');
The original code was trying to assign the return type of push_back to a.path which is invalid.
Instead you simply want to invoke the push_back method of the std::vector member of your struct.
In your code , node is a structure. Path is one element of struct.
Anytime you need to access element of struct , you have to use the name of struct along with it.
e.g. a.pizza or a.weight when 'a' is of the type node.
Similarly you need to access a.path when you want to access vector path. It doesn't matter even if you need to call the functions of vector.
You should go through struct/class

End process error code -1 if acess to string field of structure

#include <cstdlib>
#include <string>
#include <iostream>
#define S 10
using namespace std;
struct List
{
string name;
bool male;
int year;
string addr;
string diag;
bool hosp;
};
main()
{
struct List *l=NULL;
int n=0;
for(int i=0;i<10000;i++)
{
if(!(n%S))
{
l=(List*)realloc(l,(n/S+1)*S*sizeof(struct List));
cout<<"realloc ok\n";
};
l[n].male=rand()%2;
l[n].year=1900+rand()%100;
l[n].hosp=rand()%2;
//!l[n].name="abc";
n++;
cout<<l[rand()%n].male<<" "<<l[rand()%n].year<<" "<<l[rand()%n].hosp<<endl;
}
}
If l[n].name="abc" remarked then program works fine.
If i try put string value to this field the programm compiled without warnings nay, but crash with error code -1 after first realloc.
Any way to solve it?
Since your structure is non-trivial - it contains members of class type, std::string, which need to be initialised by calling their constructors - you can't simply allocate raw memory and pretend that contains a valid object.
The simplest solution is to use a type-aware dynamic array
std::vector<List> l;
which can be resized, perserving its contents, with
l.resize((n/S+1)*S);
Tip! Using "new" operator to allocate this structure will automatically create string object for each field.
List *l=new struct List[S];
It fix this issue, l[n].name="abc" will works, but it not implements reallocation functional.

What is this C++ map doing?

I have a global variable, "testGrid" which I am attempting to create a map to, so that I can reference it with a string. The map seems like it works in that I can assign values to the grid, but it is not assigning them to "testGrid" as I intend it to.
Is the map creating a new grid, separate from the global variable? How can I get the map to reference the grid correctly? In this code, the output from the two tests should be identical.
#include <iostream>
#include <map>
using namespace std;
struct signalGrid{
double signal[20][200];
signalGrid();
};
void mapTest(std::map<string,signalGrid> &temp_map);
map<string,signalGrid> signalIndex;
signalGrid testGrid;
int main(){
int i;
mapTest(signalIndex);
for(i=0;i<5;i++){
signalIndex["T1"].signal[i][0]=5;}
for(i=0;i<5;i++){
cout<<"TEST="<<testGrid.signal[i][0]<<"\n";}
for(i=0;i<5;i++){
cout<<"TEST2="<<signalIndex["T1"].signal[i][0]<<"\n";}
return 0;
}
void mapTest(std::map<string, signalGrid> &temp_map){
temp_map["T1"]=testGrid;
return;
}
signalGrid::signalGrid(){
int i,j;
for(i=0;i<20;i++){
for(j=0;j<200;j++){
signal[i][j]=0;}}
}
Yes, you are copying testGrid into the value corresponding to key "T1". Doing anything with that value will only modify the copy.
You could have a map<string, reference_wrapper<signalGrid>>, but I'm not exactly sure why you want the global testGrid variable in the first place. Why not get rid of testGrid and just deal with signalIndex["T1"]?

incomplete type is not allowed while trying to create an array of pointers

I created 2 classes, Branch and Account and I want my Branch class have an array of Account pointers, but i fail to do it. It says that "incomplete type is not allowed". What is wrong with my code?
#include <string>
#include "Account.h"
using namespace std;
class Branch{
/*--------------------public variables--------------*/
public:
Branch(int id, string name);
Branch(Branch &br);
~Branch();
Account* ownedAccounts[]; // error at this line
string getName();
int getId();
int numberOfBranches;
/*--------------------public variables--------------*/
/*--------------------private variables--------------*/
private:
int branchId;
string branchName;
/*--------------------private variables--------------*/
};
Although you can create an array of pointers to forward-declared classes, you cannot create an array with an unknown size. If you want to create the array at runtime, make a pointer to a pointer (which is of course also allowed):
Account **ownedAccounts;
...
// Later on, in the constructor
ownedAccounts = new Account*[numOwnedAccounts];
...
// Later on, in the destructor
delete[] ownedAccounts;
You need to specify the size of the array... You can't just leave the brackets hanging like that without anything inside them.

Error when changing a vector value in a class

I am attempting to change a value in a vector which is a variable in a class using a function of a class. When I compile, i get the following errors pointing to the "check[c] = cval;" line:
error C3867: 'acc::check': function call missing argument list; use '&acc::check' to create a pointer to member
error C2109: subscript requires array or pointer type
Note: I have already initialized C to be 0 elsewhere in the program. It might be throwing an error because I am giving the address a variable instead of an integer, but when I substitute the variable with an integer, I still get the same errors.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstring>
using namespace std;
class acc
{
public:
void add_Cval(double cval);
private:
vector<double> check(); //vector of all checks
int c; //loop marker for cvals
};
void acc::add_Cval(double cval)
{
check[c] = cval;
c++;
}
vector<double> check(); isn't what you think it is. You just declared a function named check that returns a vector<double>. Get rid of the parenthesis like so vector<double> check;.
Also, your vector<double> is empty, you need to give it some space if you want to do check[c] = cval; (or use check.push_back(cval); instead), allocate the space in the constructor (use "initialization lists" as that is what they are for):
Example:
acc(int vecsize) : check(vecsize), c(0) {}
You might also want to make sure check[c] is a valid position in the vector before assigning anything to it.
check is a method, not a data member, so you need to invoke it - check().
void acc::add_Cval(double cval)
{
check()[c] = cval;
c++;
}
or make it a data member:
class acc
{
public:
void add_Cval(double cval);
private:
vector<double> check; //vector of all checks
int c; //loop marker for cvals
};
The compiler is looking for a function called check() that returns a vector of type double.
private:
vector<double> check(); // A private function that returns a vector of type <double>
Needs to be:
private:
vector<double> check; // A private data member