user1751550
user1751550

Reputation: 85

Initializing vector in class

This piece of code works well out of class -

const char* list[] = {"Author: ", "Label: ", "Price: ", "Date: "};
vector<string> vlist(list, list+4);

but when I put it into class, it behaves like a function - compiler is giving me error "list" is not a type, error: expected ‘,’ or ‘...’ before ‘+’ token etc. ??

Upvotes: 1

Views: 131

Answers (4)

Nikos C.
Nikos C.

Reputation: 51832

Array sizes cannot be deduced automatically in in-class initializers. Instead, you need to specify the size:

const char* list[4] = {"Author: ", "Label: ", "Price: ", "Date: "};

Your vlist member can be initialized from a temporary:

vector<string> vlist = vector<string>(list, list + 4);

But that can be inefficient. It's better to initialize it in the constructor instead in order to avoid temporaries.

However, are you sure you need the plain list array at all? Because if not, it's much easier to just do this instead:

vector<string> list = {"Author: ", "Label: ", "Price: ", "Date: "};

Also, you need to make sure you've enabled C++11 mode in your compiler. With GCC or Clang that would be the -std=c++11 or -std=g++11 (for GNU extensions) compiler flag.

Upvotes: 1

Cory Nelson
Cory Nelson

Reputation: 29981

You're getting an error because your class definition can't call functions, only declare them. You can use the initializer list in the class's constructor to get around this:

const char* list[] = { "Author: ", "Label: ", "Price: ", "Date: " };

class c
{
    vector<string> vlist;
    c() : vlist(list, list + 4) {}
}

Upvotes: 1

tp1
tp1

Reputation: 1207

Common pattern is as follows:

class MyClass {
public:
   template<class It>
   MyClass(It beg, It end) : vec(beg,end) { }

private:
   std::vector<std::string> vec;
 };
int main() {
   std::string s[] = { "abc", "bcd" };
   MyClass c(s, s+2);
};

Upvotes: 1

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39370

If you are using C++11, you can initialize your vector directly by initializer list:

vector<string> vlist {"Author: ", "Label: ", "Price: ", "Date: "};

If not, you have to do it in the constructor, most probably by push_back:

Class::Class() {
    vlist.push_back("Author :");
    vlist.push_back("Label :");
    vlist.push_back("Price :");
    vlist.push_back("Date :");
}

Anyway, there's no point in creating intermediate C-style table, if in the end you are going to use vector.

Upvotes: 0

Related Questions