【发布时间】:2020-10-02 13:02:23
【问题描述】:
我已经从this question 改进了我的数组,以便在一个类中创建,我还使用std::vector 对其进行了优化,因此它不是分配在堆上而是在堆栈上,因此它更快并且我也不必手动管理内存。
但我无法创建一个可以为元素设置值的函数。我收到了类似expression must have pointer-to-object type 的错误(当我尝试将我的元素声明为int cell 或an array may not have element of this type (当我尝试将其声明为int cell[][] 时),当我尝试声明它时出现分段错误像这样int *cell[]。
这是我的代码
.hpp
#pragma once
#include <iostream>
#include <vector>
class myPlan
{
int slots;
int rows = 3;
int cell[][];
public:
myPlan(int slots);
void setCellValue(int row, int slot, int value)
};
.cpp
#include "myPlan.hpp"
myPlan::myPlan(int slots)
{
this->slots = slots;
std::vector<std::vector<int> > cell(STATUS_N);
for (int i = 0; i < STATUS_N; i++)
{
// declare the i-th row to size of column
cell[i] = std::vector<int>(slots);
}
//Print the array
for (int i = 0; i < STATUS_N; i++) {
for (int j = 0; j < cell[i].size(); j++)
{
cell[i][j] = 0;
std::cout << cell[i][j] << " ";
}
std::cout << "\n";
}
}
void myPlan::setCellValue(int row, int slot, int value)
{
cell[row][slot] = value;
}
main.cpp
#include "myPlan.hpp"
int main()
{
myPlan plan(N_PLAN);
plan.setCellValue(0,2,42);
}
非常感谢您的任何帮助 附:我希望这个比this array更优化,如果有更好的优化版本,我会很高兴了解它。
【问题讨论】:
-
" 所以它不是分配在堆上而是分配在堆栈上,因此速度更快。"抱歉,
std::vector确实将其元素存储在堆上。也许您正在寻找std::array -
向量从堆中为其元素分配内存。向量本身可能在堆栈上。这与指针的情况完全相同,指针本身可能在堆栈上,但它指向的内存在堆上。
-
请一字不差地包含错误信息,请勿总结或解释它
-
int cell[][];-- 这应该做什么?这不是有效的 C++。
标签: c++ arrays optimization vector