简体   繁体   English

C ++ STL向量初始化

[英]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. 类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' . 错误:请求成员'vstr'int'this',它是非类类型'Program * const'。

Could you give me a simple solution for this error? 您能给我一个解决此错误的简单方法吗?

I'm not an expert in C++ but I see at least two problems: 我不是C ++专家,但我至少看到两个问题:

  1. You are trying to initialise an object with a pointer. 您正在尝试使用指针初始化对象。 Don't use new key word. 不要使用new关键字。
  2. What is more this pointer points to vector of strings not chars, so replace vector<string> with vector<char> . 更重要的是,此指针指向的是字符串的矢量而不是char,因此将vector<string>替换为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 正如melak47在他的评论中所说, this.vstr也是不正确的,因为这是一个指针,因此应替换为this->vstr或简单地使用vstr

Once you make all the three corrections it should compile 完成所有三个更正后,便应编译

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM