Harmath Bálint
Harmath Bálint

Reputation: 21

C++ STL vector init

I am just wondering how I could solve this problem.

I have a

vector<char> vstr;

definition in the class Program.

Then in the class constructor I want to init this vector with an array:

char arrayOfChars[] = {'a', 'b', 'c'};

this.vstr = new vector<string>(arrayOfChars, arrayOfChars + sizeof(arrayOfChars)/sizeof(arrayOfChar[0]));

The build gives me a bug:

error: request for member 'vstr' int 'this', which is of non-class type 'Program *const' .

Could you give me a simple solution for this error?

Upvotes: 0

Views: 238

Answers (2)

user4272649
user4272649

Reputation:

I think that piece of code is what you want.

#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

class Program {
    vector<char> vstr;
public:
    Program(const char* data)
    {
        string s(data);
        std::copy(s.begin(), s.end(), std::back_inserter(vstr));
    }
    void PrintData()
    {
        for (auto it = vstr.begin(); it != vstr.end(); it++)
        {
            std::cout << (*it);
        }
    }
};

int main()
{
    Program p("simple data");
    p.PrintData();
}

Upvotes: 1

Andrey Chernukha
Andrey Chernukha

Reputation: 21808

I'm not an expert in C++ but I see at least two problems:

  1. You are trying to initialise an object with a pointer. Don't use new key word.
  2. What is more this pointer points to vector of strings not chars, so replace vector<string> with vector<char>.

  3. As melak47 says in his comment this.vstr is also incorrect because this is a pointer and therefore should be replaced with this->vstr or simply vstr

Once you make all the three corrections it should compile

Upvotes: 1

Related Questions