Error must have class type - c++

I'm kinda new in C++ and when trying to compile this code I get and error that I do not know how to fix:
int main()
{
typedef pair<int,int> nodo;
int x;
cin >> x;
int *g;
g = new int[x];
vector <nodo> g;
g[1].push_back(nodo(2,5));
g[1].push_back(nodo(3,10));
g[3].push_back(nodo(2,12));
g[2].push_back(nodo(4,1));
g[4].push_back(nodo(3,2));
for (int i = 1; i <=4; ++i){
// cout << i << " -> ";
for (int j = 0; j<g[i].size(); ++j){
// cout << g[i][j].first << " c: " << g[i][j].second << " ";
}
// cout << endl;
}
dijkstra(1, x);
system("pause");
return 0;
}
The error I am receiving is:
Error: Expression must have a class type.

Here:
int *g;
g = new int[x];
vector <nodo> g; // ERROR: Redeclaration!
You are first declaring g to be of type int*, and then you re-declare it to be of type vector<nodo>. This is illegal.
Moreover, you need to have a using namespace std directive if you want to omit the std:: qualification for types in the standard namespace. I do not suggest you using that though. Much better explicitly specifying std::, or rather use specific using declarations.
For instance:
typedef std::pair<int,int> nodo;
// ^^^^^
int x;
std::cin >> x;
// ^^^^^
int *g;
g = new int[x];
std::vector <nodo> g;
// ^^^^^
Also make sure you are importing all the necessary standard headers:
Type | Header
--------------------------
std::vector -> <vector>
std::pair -> <utility>
std::cin -> <iostream>

You're redeclaring g, first it's an int* and then you make it into a vector<int>. I'm not sure how that got past the compiler.
Also, rather than using nodo(1,2) consider using make_pair instead. Using new is also considered bad practice and you should use either a dynamic container like std::vector or a static one like std::array.

You have two things named g:
int* g;
and
vector <nodo> g;
This wouldn't even compile.
It looks like you want an array of vectors, in which case you need something like
std::vector<std::vector<nodo> > g(x); // size x vector of vectors.
Then you can do this type of thing:
g[1].push_back(nodo(2,5));
g[1].push_back(nodo(3,10));

pair is not a class because you haven't included <utility>
You also haven't included <vector> or <iostream>.

So this version compiles and I think this is what you meant to do:
// Need to include these headers
#include <utility>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
typedef pair<int,int> nodo;
int x;
cin >> x;
//int *h;
//h = new int[x];
//specify size of vector
std::vector< std::vector<nodo> > g(x);
g[0].push_back(nodo(2,5));
g[1].push_back(nodo(3,10));
g[2].push_back(nodo(2,12));
g[3].push_back(nodo(4,1));
g[4].push_back(nodo(3,2));
for (int i = 0; i < g.size(); ++i){
std::cout << i << " -> ";
for (int j = 0; j<g[i].size(); ++j){
cout << g[i][j].first << " c: " << g[i][j].second << " ";
}
cout << endl;
}
//dijkstra(1, x);
//system("pause");
return 0;
}
Many issues, you use g twice for one. I am not sure what you want to do with the vector but maybe you want a vector of vectors which would be more like this:
std::vector< std::vector<nodo> > g(x) ;
Then this would make more sense:
g[0].push_back(nodo(2,5)) ;
The first element of a vector is going to be at 0 not 1.

Related

Invalid conversion from int* to int even though I delimit the pointer

I've received the following error:
NQueens.cpp:35:19: error: invalid conversion from 'int*' to 'int' [-fpermissive]
solution[i].y = *(possibilities + i);
I believe I delimited the pointer so that I can apply the value being pointed to the y coordinate for the n-queens problem. Am I missing anything, or is my compiler being dumb?
My header file:
#pragma once
#ifndef QUEEN
#define QUEEN
struct Queen {
int x, y;
};
#endif // !QUEEN
My C++ code:
#include "Queen.h"
#include <iostream>
#include <vector>
using namespace std;
bool isDiag(int, int, int, int);
bool solutionFinder(int, int, vector<int*>);
int main()
{
int n;
cout << "Enter a number n for the n-queen problem:\n";
cin >> n;
vector<int*> possibilities;
for (int i = 0; i < n; i++)
{
int arrayInt[n];
arrayInt[0] = i + 1;
for (int j = 1; j < n; j++)
{
arrayInt[j] = 0;
}
possibilities.push_back(arrayInt);
}
if (!solutionFinder(1, n, possibilities))
{
cout << "No Solution.\n";
}
Queen solution[n];
for (int i = 0; i < n; i++)
{
solution[i].x = i + 1;
solution[i].y = *(possibilities.begin() + i);
}
cout << "Solution: [(" << solution[0].x << "," << solution[0].y << ")";
for (int i = 1; i < n; i++)
cout << ", (" << solution[i].x << "," << solution[i].y << ")";
cout << "]\n";
return 0;
}
UPDATE:
I've tried the fix that mch suggested and now it compiles fine. However, I've ran into a new problem. When trying to print the coordinates for the queens, I'm getting what I believe are the locations of the values in memory.
Example:
Enter a number n for the n-queen problem:
4
Solution: [(1,1163548928), (2,32764), (3,1163548704), (4,32764)]
There are multiple issues with this code, but your immediate problem stems from this:
vector<int*> possibilities;
...
for (...)
{
int arrayInt[n];
...
possibilities.push_back(arrayInt);
}
...
solution[i].y = *(possibilities.begin() + i);
You have a vector of int* pointers, which are pointing at int[] arrays which you are creating inside a loop (and will be destroyed at the end of each loop iteration, thus leaving the vector holding dangling pointers to invalid memory).
You are then iterating through the vector, extracting each int* pointer and trying to assign it as-is to a single int, thus the compiler error. You would need to instead dereference the int* to get individual int values from the array, eg:
int *arr = *(possibilities.begin() + i);
solution[i].y = arr[someIndex];
Based on what you have shown, I think you have implemented your solutionFinder() incorrectly (but you didn't show how you actually implemented it). Rather than outputting a vector of int[] arrays, it would be better to have it output a vector of Queens instead, eg:
#include "Queen.h"
#include <iostream>
#include <vector>
using namespace std;
bool isDiag(int, int, int, int);
bool solutionFinder(int, int, vector<Queen>&);
int main()
{
int n;
cout << "Enter a number n for the n-queen problem:\n";
cin >> n;
vector<Queen> solution;
solution.reserve(n);
if (!solutionFinder(1, n, solution))
{
cout << "No Solution.\n";
return 0;
}
cout << "Solution: [(" << solution[0].x << "," << solution[0].y << ")";
for (int i = 1; i < n; ++i)
cout << ", (" << solution[i].x << "," << solution[i].y << ")";
cout << "]\n";
return 0;
}
bool isDiag(int, int, int, int)
{
// ...
}
bool solutionFinder(int, int, vector<Queen> &solution)
{
// populate solution with Queen's as needed...
for (...)
{
Queen q;
q.x = ...;
q.y = ...;
solution.push_back(q);
}
...
}
Contrary to the various comments you /can/ do can do arithmetic on "random access" iterators.
The issue is that you declared you have a vector of pointers.
You access the iterator like a pointer using operator * to indirect, but then you would would need to indirect again (another *) to follow the pointer held in the cell of the vector.
It is simper to use the array index syntax with vector poss[i] rather than *(poss.begin()+i) but you still need to do that extra indirection if you do indeed have a vector of pointers, *(poss[i]) which looks a bit ugly.

Novice C++, seeking help in array division

#include <iostream>
#include <valarray>
using namespace std;
// to get new card number
int main ()
{
int i;
int array[5]= {10,2,6,34,51};
valarray<int> v[5];
int v %= 13;
for (int i=0; i<5 ; i++) {
cout << v[i]%=13 << " ";
}
}
hello, my goal is to get the array to perform a modulus division by number 13.
I've search and try a few different way but I can't figure out a way to make it work.....
Thank you...
Some of the problems with your code:
valarray does not have the same notation as normal arrays: valarray<int> v[5]; declares 5 different valarray objects and puts them in a C-style array. The notation you are looking for is valarray<int> v(10);
Get rid of the int v %= 13; line: this redefines v (an array) as an integer.
Use v[i]=(array[i]%13); for the calculation, what you have doesn't make sense.
Then output cout << v[i] << " ";
Also, you aren't really using any of the features of valarray, so it may make more sense just to use one single array, like:
#include <iostream>
using namespace std;
// to get new card number
int main ()
{
int array[5]= {10,2,6,34,51};
for (int i=0; i<5 ; i++) {
array[i]%=13;
cout << array[i] << " ";
}
}
Edit: by the way, the cool thing about valarray here is that you can apply the same function to every value at once. Like this:
#include <iostream>
#include <valarray>
using namespace std;
int main() {
valarray<int> v(10);
for (int i=0;i<10;++i) {
v[i]=i*i; //Fill the array with 0,1,4,9,16,... as an example
}
v%=13; //This applies the modulo 13 on the whole array at once.
for (int i=0;i<10;++i) {
cout << v[i] << endl;
}
}
Seems you want something like...
int array[5]= {10,2,6,34,51};
int v[5];
for (int i = 0; i < 5; ++i)
v[i] = array[i] % 13;
for (int i = 0; i < 5; ++i)
std::cout << v[i] << " ";
std::cout << '\n';

Trouble with types when passing vector to function in c++

I am starting a c++ class having never done anything in the language before, and I'm pretty confused by vectors.I made a toy example and I don't quite understand why the doubles that I put into a vector become vector's. Here is the code:
#include <iostream>
#include <vector>
using namespace std;
vector<double> a;
void func(vector<double> *);
int main()
{
for (int i = 0; i < 100; i++)
{
a.push_back(double(i));
}
func(&a);
return 0;
}
void func(vector<double> *vec)
{
cout << double(vec[0]) << endl;
return;
}
It ends up giving me this error:
error: cannot convert 'vector' to 'double' without
a conversion operator
and I have no idea what that means. What exactly is happening here and how can I cast a vector into a double?
You don't need to mix using pointers * with std::vector.
Method 1 (not recommended):
Change
cout << double(vec[0]) << endl;
to
cout << double((*vec).at(0)) << endl;
Method 2:
Change
void func(vector<double> *vec)
to
void func(vector<double> vec)
or
void func(const vector<double> &vec)
Change
func(&a);
to
func(a);
The reason for the actual error is more due to a misunderstanding of pointers than vectors . The problem is that you are passing a pointer to a vector. If you want to use the vector itself, then you would do:
cout << (*vec)[0] << endl;
* will dereference the pointer to get the actual vector instance rather than an index into an address which is what you were doing before.
But, as pointed out in the other answer, it is safer just to pass the vector by reference (or better yet, const reference):
void func(const vector<double>& vec)
{
cout << vec[0] << endl;
return;
}
then call as:
func(a);
Another way to use vectors is with a std::vector< TYPE >::const_iterator like this;
#include <iostream>
#include <vector>
double func(std::vector<double>::const_iterator iter);
int main()
{
std::vector<double> vec;
for (double i = 0.0; i < 1; i += 0.1){
vec.push_back(i);
}
std::cout<< func(vec.begin()+3) << " "
<< func(vec.begin()+6) << std::endl;
return 0;
}
double func(std::vector<double>::const_iterator iter){
return *iter;
}
outputs;
0.3 0.6

Print struct element of vector

I am learning about vector. I try to implement a code that print the struct element of a vector as displayed below. Many resources in the internet only teach me a simple vector. I get stcuk in expression when to print it. However, any suggestion for improving the quality and elegance of the code is open, although the change is fundamental (in struct or looping).
Thank you very much.
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
typedef struct _student {
string name;
int age;
vector <string> subject;
}student;
int _tmain(int argc, _TCHAR* argv[])
{
vector <student> x; //assmue at this point we do not know the number of students
student y;
//and I want to insert new information
y.name ="John";
y.age =9;
y.subject.push_back("biology");
y.subject.push_back("math");
y.subject.push_back("art");
x.push_back(y);
//get new information again
//and I want to insert new information
y.name ="Bon";
y.age =12;
y.subject.push_back("history");
y.subject.push_back("physics");
x.push_back(y);
// then I want display all data
cout << "myvector contains:";
for (int i=0; i<x.size(); i++)
{
cout << "Student # " << i+1 <<endl;
cout << " name : " << x.at(i).name <<endl; //Reference in the internet only display a simple vector --
cout << " age : " << x.at(i).age <<endl; //I get stuck to express this and next part
cout <<" Subject : ";
for (int j =0; j < x.at(i).subject.size(); j++)
{
cout << x.at(i).subject.at(j);
}
cout << endl;
cin.get();
return 0;
}
Here, added some comments and stuff. Not sure if this is what you were looking for, but here it is.
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string> // string would be welcome here!
struct _student // the typedef thing is not necessary in C++
{
std::string name; // i find this "using namespace ..." thing a bad habit, it can make code harder to read
int age;
std::vector<std::string> subject;
};
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<student> x;
student y;
size_t size; // calling vector.size() every iterations is a bad idea, performance-wise
size_t size_subj; // same
y.name = "John";
y.age = 9;
y.subject.push_back("biology");
y.subject.push_back("math");
y.subject.push_back("art");
x.push_back(y);
y.name = "Bon";
y.age = 12;
y.subject.clear(); // clear subjects of the other student
y.subject.push_back("history");
y.subject.push_back("physics");
x.push_back(y);
std::cout << "my vector contains:";
for (int i = 0, size = x.size(); i < size; ++i)
{
size_subj = x[i].subject.size();
// I prefer using operator[] when I'm sure nothing can go wrong
std::cout << "Student # " << i + 1 <<endl;
std::cout << "\tname: " << x[i].name <<endl;
std::cout << "\tage: " << x[i].age <<endl;
std::cout << "\tSubjects: ";
for (int j = 0; j < size_subj; ++j)
std::cout << x[i].subject[j];
std::cout << endl;
}
return 0;
}
Finally, using a std::vector< std::string* > or std::vector< std::string& > could be a better idea performance-wise, depending on what you are planning to do with it later.
There is no real question here, so I'm assuming you are asking for "code review"
The "neat" way is of course to create an operator<< that takes your inner structure.
Aside from that, you may want to look at using iterators to walk your way through your vector - that way, you should be able to change your vector for any other container type without having to change the loop(s) that print things.
Use longer variable names than x and y for your vector and temporary student.
Use setw to print fields at the same width every time.
I'm sure there are plenty of other suggestions too.
As the comments point to, it turns out that you're not including the string header file.

c++ references array

I wounder how i can make this code work?
#include <iostream>
using namespace std;
void writeTable(int (&tab)[],int x){
for(int i=0;i<x;i++){
cout << "Enter value " << i+1 <<endl;
cin >> tab[i] ;
}
}
int main(void){
int howMany;
cout << "How many elemets" << endl;
cin >> howMany;
int table[howMany];
int (&ref)[howMany]=table;
writeTable(ref,howMany);
return 0;
}
And here are the errors that I have:
|4|error: parameter ‘tab’ includes reference to array of unknown bound ‘int []’|
|18|error: invalid initialization of reference of type ‘int (&)[]’ from expression of type ‘int [(((unsigned int)(((int)howMany) + -0x00000000000000001)) + 1)]’|
|4|error: in passing argument 1 of ‘void writeTable(int (&)[], int)’|
Thanks for help
If you are intending to pass the size of the array, then remove the reference
void f(int a[])
is equivalent to
void f(int* a)
so no copying will be done, if that is the concern.
If you want to take an array by reference, then you MUST specify the dimension. e.g.
void f(int (&a)[10])
Naturally, the best of the two is the third solution, which is to use std::vector's and pass them by reference, reference to const or by value if needed. HTH
Here is a slightly more C++ style of doing it:
#include <iostream>
#include <vector>
void writeTable(std::vector<int> &tab)
{
int val;
for (unsigned int i=0; i<tab.size(); i++)
{
std::cout << "Enter value " << i+1 << std::endl;
if (std::cin >> val)
{
tab[i] = val;
}
}
}
int main()
{
int howMany;
std::cout << "How many elements?" << std::endl;
std::cin >> howMany;
std::vector<int> table(howMany);
writeTable(table);
return 0;
}
You need not specify the dimension of the array if you make writeTable a function template.
template <typename T,size_t N>
void writeTable(T (&tab)[N]) //Template argument deduction
{
for(int i=0 ; i<N ; i++){
// code ....
}
}
.
int table[howMany]; // C++ doesn't have Variable Length Arrays. `howMany` must be a constant
writeTable(table); // type and size of `table` is automatically deduced
Following Amardeep's answer, here is a C++11 way to do it:
#include <iostream>
#include <vector>
void writeTable(std::vector<int> &tab)
{
int val;
for (auto& cell : tab)
{
std::cout << "Enter value " << i+1 << std::endl;
if (std::cin >> val)
{
cell = val;
}
}
}
int main()
{
int howMany;
std::cout << "How many elements?" << std::endl;
std::cin >> howMany;
std::vector<int> table(howMany);
writeTable(table);
return 0;
}
Note the range-based for used in writeTable.
Arrays of references are illegal, if that is what you are trying to do. It's not 100% clear to me from the title.