Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ compile time error: expected identifier before numeric constant

Tags:

c++

g++

vector

I have read other similar posts but I just don't understand what I've done wrong. I think my declaration of the vectors is correct. I even tried to declare without size but even that isn't working.What is wrong?? My code is:

#include <vector>  #include <string> #include <sstream> #include <fstream> #include <cmath>  using namespace std;  vector<string> v2(5, "null"); vector< vector<string> > v2d2(20,v2);  class Attribute //attribute and entropy calculation {     vector<string> name(5); //error in these 2 lines     vector<int> val(5,0);     public:     Attribute(){}  int total,T,F;  };    int main() {   Attribute attributes; return 0; } 
like image 841
user1484717 Avatar asked Jul 15 '12 09:07

user1484717


1 Answers

You cannot do this:

vector<string> name(5); //error in these 2 lines vector<int> val(5,0); 

in a class outside of a method.

You can initialize the data members at the point of declaration, but not with () brackets:

class Foo {     vector<string> name = vector<string>(5);     vector<int> val{vector<int>(5,0)}; }; 

Before C++11, you need to declare them first, then initialize them e.g in a contructor

class Foo {     vector<string> name;     vector<int> val;  public:   Foo() : name(5), val(5,0) {} }; 
like image 143
juanchopanza Avatar answered Sep 22 '22 19:09

juanchopanza