compiler not recognizing vector as class member - c++

enter image description hereI am trying out some STL programs. I have declared a vector in main and tried to run the program it is working but if i declare the same(vector) inside the class then am getting a compilation error. I think compiler is not recognizing vector(declared inside the class).
I have tried with std:: also still same error. I am using netbeans IDE and cigwin compiler.
please find the code below
#include <cstdlib>
#include <iostream>
#include <vector>
#include <cctype>
using namespace std;
/*
*
*/
class vectorcl
{
vector<int> v(10);
int i;
public:
vectorcl();
void add_vector();
void dis_vector();
};
vectorcl :: vectorcl()
{
for(i =0;i<10 ;i++)
{
v[i] = 0;
}
}
void vectorcl :: dis_vector()
{
cout<< " The vale is : \n";
for(i =0;i<10 ;i++)
{
cout << "\t " <<v[i];
}
}
void vectorcl :: add_vector()
{
for (i =0 ; i<10; i++)
{
v[i] = i+1;
}
}
int main(int argc, char** argv) {
// vector<int> vp(10);
// for(int j =0;j<10 ;j++)
// {
// cout << " " << vp[j];
// }
vectorcl v1;
v1.dis_vector();
v1.add_vector();
v1.dis_vector();
return 0;
}
Please help me in this, my question is why my compiler is not recognizing vector declared inside a class.
error : expected identifier before numeric constant
expected ',' or '...'before numeric constant
Error

You can not use vector<int> v(10); as member variable. The solution is to replace it by vector<int> v; and add this alter the constructor like this:
vectorcl::vectorcl():
v(std::vector<int>(10,0/* This 0 is instead of the for-loop*/)){
}
Or another option is to declare it as :
std::vector<int> v = std::vector<int>(10);
P.S. there is no need to declare int i as class member. Just declare it in every function you need.

From first glance, you are trying to call the constructor in the class prototype: vector<int> v(10);. Your constructor for that class will be called in your wrapper class constructor unless you use a member initialization list.
Edit: using member initialization
vectorcl :: vectorcl(): v(10)
{
}

Related

Vector declared in header file isn't being recognized C++

I have been having a lot of issues with header files, and now it seems that the vector that is declared in my header file, Polynomial.hpp, is not being recognized in Polynomial.cpp. I have already included std:: which seems to be a common mistake, so I don't know where to go from here.
Header file:
#ifndef POLYNOMIAL_HPP
#define POLYNOMIAL_HPP
#include<vector>
#include"term.hpp"
class Polynomial {
private:
std::vector<Term> vect;
public:
Polynomial();
~Polynomial();
void add(Term t);
void print();
Polynomial combineLikeTerms();
};
#endif
cpp File:
#include "term.hpp"
#include "Polynomial.hpp"
#include<iostream>
#include<map>
using namespace std;
void add(Term t) {
vect.push_back(t);
}
void print() {
for(int i = 0; i < vect.size(); i++) {
cout << vect[i].toString();
}
}
Polynomial combineLikeTerms() {
Polynomial poly;
map<int, int> combinedPoly;
for(int j = 0; j < vect.size(); j++)
{
combinedPoly.insert(pair<int, int>(vect[j].getExponent(), vect[j].getCoefficient());
}
for(map<int,int>::iterator itr = combinedPoly.begin(); itr != combinedPoly.end(); itr++) {
Term newTerm(itr->second, "x", itr->first);
poly.add(newTerm);
}
return poly;
}
Error (1/6):
Polynomial.cpp:9:5: error: use of undeclared identifier 'vect'
vect.push_back(t);
In Polynomial.cpp you are defining new functions instead of member functions. Change the definitions to use the class name like
void Polynomial::add(Term t) {
vect.push_back(t);
}
Your void add(Term T) in Polynomial.cpp is not the member function of the Polynomial.
You must implement this function as member of Polynomial like this
void Polynomial::add(Term T){
...
}
I think this is a syntax error. First, you defined the add method in the Polynomial class of the header file, but the CPP file did not add the class scope, which caused this problem. So you should adjust your code like this:
void Polynomial::add(Term t) {
vect.push_back(t);
}
The root cause of this problem is that the methods of the class only work within the scope of the class, and if there is a function with the same name inside the class, it will lead to a naming conflict. Therefore, the root cause of this problem is not the reference error of the vector file.
The issue is that instead of defining the members add and print of the class Polynomial, you are defining functions in global scope completely unrelated to the class Polynomial
Make changes in the function definition of void add(Term) and void print() to void Polynomial::add(Term) and void Polynomial::print().
#include "term.hpp"
#include "Polynomial.hpp"
#include<iostream>
#include<map>
using namespace std;
void Polynomial::add(Term t) { // change here
vect.push_back(t);
}
void Polynomial::print() { //change here
for(int i = 0; i < vect.size(); i++) {
cout << vect[i].toString();
}
}
Polynomial combineLikeTerms() {
Polynomial poly;
map<int, int> combinedPoly;
for(int j = 0; j < vect.size(); j++)
{
combinedPoly.insert(pair<int, int>(vect[j].getExponent(), vect[j].getCoefficient());
}
for(map<int,int>::iterator itr = combinedPoly.begin(); itr != combinedPoly.end(); itr++) {
Term newTerm(itr->second, "x", itr->first);
poly.add(newTerm);
}
return poly;
}

dynamically allocate memeory for Eigen Vector

I am using the Eigen linear algebra library. I struggling trying to allocate Eigen Vectors in the constructor in a class, and then calling the elements of those vectors.
For example,
#include <Eigen/Dense>
using Eigen::VectorXd;
#include <memory>
using std::unique_ptr;
class Cl
{
public:
unique_ptr<VectorXd> v;
Cl(const int n);
~Cl(void);
}
Cl::Cl(const int n)
{
auto v= unique_ptr<VectorXd>(new VectorXd(n));
}
Cl::~Cl(void)
{
v= nullptr;
}
main(void)
{
Cl cl(10);
/* call an element of v how? */
}
For example, using "cl.v(2)" gives me the compiler error (I am using clang++)
error: type 'unique_ptr<VectorXd>' (aka 'unique_ptr<Matrix<double, Dynamic, 1> >') does
not provide a call operator
while using "cl.(*v)(2)" gives me
error: expected unqualified-id
cout << cl.(*v)(2) << endl;
I am new to c++, so I may be missing something very basic here.
Why are you trying to dynamically allocate the Eigen::VectorXd v; itself? Unless you would like to extend the lifetime of v beyond the lifetime of cl (in which case you would indeed have to do so), I would recommend to follow the following simple example:
#include <Eigen/Dense>
using Eigen::VectorXd;
class Cl
{
public:
VectorXd v;
Cl(int n) : v(n) {}
~Cl() {}
}
int main()
{
Cl cl(10);
for (int i=0; i<10; ++i)
cl.v(i) = i;
}
I believe in addition to the answers already regarding std::vector you are also misusing your 'unique_ptr', if indeed you actually require the use of one (reference ggael answer). Please see below example on the use of unique_ptr:
#include <iostream>
#include <memory>
#include <vector>
class Cl {
public:
std::unique_ptr<std::vector<int>> v;
Cl(const int size, int default_values);
~Cl(void);
int Size();
};
Cl::Cl(const int size, int default_values = 0) {
v.reset(new std::vector<int>(size, default_values));
}
Cl::~Cl(void) {
// do not require to reset/destroy an auto_ptr so this can be ommitted
}
int Cl::Size() {
return v->size();
}
int main(int argc, char* argv[]) {
Cl blob(10);
int size = blob.Size();
std::cout << size << std::endl;
}
In your provided code you're declaring a new auto in the constructor rather than using the variable you've defined in your Public class definition. I've included a 'Size' method so you can see the scope extends beyond the constructor.

C++ parallel_for error

I am trying to learn how to use TBB, so I'm modifying a sample program I found that is designed to compute powers of an array of complex numbers. Originally, it was passing an array into the parallel_for loop, but I am trying to change it so that it passes in a vector. However, I cannot get my code to compile; I get the following error (compiled using g++ -g program_name.cpp -ltbb):
error: passing ‘const std::complex<double>’ as ‘this’ argument
discards qualifiers [-fpermissive] result[i] = z;
My code is below:
#include <cstdlib>
#include <cmath>
#include <complex>
#include <ctime>
#include <iostream>
#include <iomanip>
#include "tbb/tbb.h"
#include "tbb/blocked_range.h"
#include "tbb/parallel_for.h"
#include "tbb/parallel_for_each.h"
#include "tbb/task_scheduler_init.h"
using namespace std;
using namespace tbb;
typedef complex<double> dcmplx;
dcmplx random_dcmplx ( void )
{
double e = 2*M_PI*((double) rand())/RAND_MAX;
dcmplx c(cos(e),sin(e));
return c;
}
class ComputePowers
{
vector<dcmplx> c; // numbers on input
int d; // degree
vector<dcmplx> result; // output
public:
ComputePowers(vector<dcmplx> x, int deg, vector<dcmplx> y): c(x), d(deg), result(y) { }
void operator() ( const blocked_range<size_t>& r ) const
{
for(int i=r.begin(); i!=r.end(); ++i)
{
dcmplx z(1.0,0.0);
for(int j=0; j < d; j++) {
z = z*c[i];
};
result[i] = z;
}
}
};
int main ( int argc, char *argv[] )
{
int deg = 100;
int dim = 10;
vector<dcmplx> r;
for(int i=0; i<dim; i++)
r.push_back(random_dcmplx());
vector<dcmplx> s(dim);
task_scheduler_init init(task_scheduler_init::automatic);
parallel_for(blocked_range<size_t>(0,dim),
ComputePowers(r,deg,s));
for(int i=0; i<dim; i++)
cout << scientific << setprecision(4)
<< "x[" << i << "] = ( " << s[i].real()
<< " , " << s[i].imag() << ")\n";
return 0;
}
You're trying to modify non-mutable member field result in const-qualified operator().
Resolve this discrepancy.
Edit #1: I have already mentioned the two keywords above. Either:
Remove const qualifier from operator():
void operator() ( const blocked_range<size_t>& r ) { ... }
Make result mutable:
mutable vector<dcmplx> result;
Additional erorrs may emerge after applying (although strongly preferred) variant no. 1. No. 2 is just for completeness and is used only in marginal situations.
It indeed results in an error with the 1st variant. This is because tbb::parallel_for takes Func by const&, so it can call only const-qualified member functions on your functor. Why? TBB doesn't want to waste performance by copying large functors (STL passes them by value).
I don't know what's the common practice here, I've never used this library.
Edit #2: Probably all you were missing was that result wasn't a reference:
vector<dcmplx> &result;
Now you'll be able to modify it, even in const-qualified operator(). Modifying a member that gets destructed afterwards wouldn't make sense.
Don't forget to change the constructor's signature to pass y by reference, too.
Off topic issues in your code:
Not included <vector> header
using namespace bulky_namespace globally
not using size_t for i in the for-loop
maybe more...

Trouble printing out data of a nested vector in a template class (C++)

I'm having some trouble printing out the values of my nested vector.
So I've got a template for a class with one of the protected variables being a nested vector.
I tried using iterators as you can see, but running on visual studio 2015, there were no problems with the build just a horrible debugger window popped up!
Here is the template class in my header file:
template <class T> class experiment : public measurement <T> {
protected:
std::vector < std::vector <T> > vdata; //declared the nested vector here
std::vector <T> verror; //another normal vector
public:
experiment(int m);
void print() { //problem with print!
using namespace std; //I've created my own namespace for the rest of my programme
for (int i = 0; i != vdata.size(); i++) {
for (int k = 0; k != vdata[i].size(); i++) {
cout << "Value : " << vdata[i][k] << " Error: " << verror[i] << endl;
}
}
};
Here is my main cpp
#include <iostream>
#include <vector>
#include "HeaderClass.h"
using namespace test;
using namespace std;
int main() {
experiment <double> exp(3);
exp.print(); //code is perfectly fine until here
return 0;
}
I just can't see what's wrong.
I hope you can help, thanks! :)

Structure Arrays & Pointers

I have to use a struct array called Robot_parts[] for each part_rect struct (part_num, part_name, part_quantity, part_cost)
And through the void display function, I have to display Robot_parts[] array entirely through pointer but I don't know how, and I don't know where to declare Robot_parts[] and whether i have to put any number value inside the brackets.
So far I have:
#include <iostream>
#include <string>
using namespace std;
void display();
struct part_rec
{
int part_num;
string part_name;
int part_quantity;
double part_cost;
};
int main()
{
part_rec Robot_parts[ ] = {
{7789, "QTI", 4, 12.95},
{1654, "bolt", 4, 0.34},
{6931, "nut", 4, 0.25}
};
return 0;
}
void display()
{
cout<<Robot_parts[]<<endl<<endl;
}
If I also made a few other errors, please let me know. Thanks!
As stated in a comment it would be much better to use a c++ container like a std::vector or std::array.
But since your professor requires an old-style array, you could try like the code below - see the comments for explanation:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct part_rec
{
int part_num;
string part_name;
int part_quantity;
double part_cost;
};
// You have to pass a pointer (to the array) and the size of the array
// to the display function
void display(part_rec* Robot_parts, int n);
// Make a function so that you can "cout" your class directly using <<
// Note: Thanks to #BaumMitAugen who provided this comment and link:
// It makes use of the so called Operator Overloading - see:
// https://stackoverflow.com/questions/4421706/operator-overloading
// The link is also below the code section
std::ostream &operator<<(std::ostream &os, part_rec const &m)
{
// Note - Only two members printed here - just add the rest your self
return os << m.part_num << " " << m.part_name;
}
int main()
{
part_rec Robot_parts[] {
{7789, "QTI", 4, 12.95},
{1654, "bolt", 4, 0.34},
{6931, "nut", 4, 0.25}
};
display(Robot_parts, 3);
return 0;
}
void display(part_rec* Robot_parts, int n)
{
// Loop over all instances of your class in the array
for (int i = 0; i < n; ++i)
{
// Print your class
cout << Robot_parts[i] << endl;
}
}
The link recommended by #BaumMitAugen:
Operator overloading