[英]how to access to a vector in the class from a function that belongs to that class in C++
I am new in C++.我是 C++ 新手。 I created a cpp and a header file.
我创建了一个 cpp 和一个头文件。 Here is the header file:
这是头文件:
class LISCH{
public:
class lisch_entry{
public:
bool valid;
int link;
int data;
lisch_entry(){
valid = false;
}
};
vector<lisch_entry> data_vec;
public:
LISCH(int);
void insert(int);
};
In cpp file , i need to access that data_vec vector in insert function but i couldn't do it because it's my first time coding in C++.在 cpp 文件中,我需要在插入函数中访问该 data_vec 向量,但我无法这样做,因为这是我第一次用 C++ 编码。 Here is the cpp file:
这是cpp文件:
#include "lisch.h"
#include <iostream>
using namespace std;
LISCH::LISCH(int table_size){
table_size=10;
int x=5;
}
void LISCH::insert(int new_data){
lisch_entry entry;
int add=new_data%11;
if(LISCH.data_vec[add] == NULL) //here i need to acces data_vec
{
}
data_vec.insert(add,new_data); //and also here
}
How can i manage to do that?我怎样才能做到这一点? I need to check if a specific position of the vector is empty or not.
我需要检查向量的特定位置是否为空。
There are quite a few of things wrong with code, probably for lack of planning or formulating the desired effect.代码有很多问题,可能是由于缺乏计划或制定所需的效果。
using namespace std; // never do this in real programs.
// Even some tests may fail accidently.
LISCH::LISCH(int table_size){
table_size=10; // those are local variables, why assigning values to them?
int x=5;
}
data_vec
is defined as a vector of lisch_entry
: data_vec
被定义为lisch_entry
的向量:
vector<lisch_entry> data_vec;
The you out of blue access element of type lisch_entry
with index add
.您突然访问带有索引
add
lisch_entry
类型的元素。 Did you allocate that many elements already?你已经分配了那么多元素吗? It may not exist at all, the program would crash:
它可能根本不存在,程序会崩溃:
if(LISCH.data_vec[add] == NULL)
An instance lisch_entry
cannot be equal, cannot be compared to NULL as far as you had defined it.实例
lisch_entry
不能相等,不能与您定义的 NULL 进行比较。 The check itself looks suspicious, what had you wanted to do?支票本身看起来很可疑,你想做什么?
data_vec.insert(add,new_data);
insert
receives an iterator as first parameter. insert
接收一个迭代器作为第一个参数。 An integer value isn't an iterator.整数值不是迭代器。 It looks like have to check the documentation on
std::vector
.看起来必须检查
std::vector
上的文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.