我试图编写一个在容器类中存储id和值的类.我使用嵌套类作为我的数据结构.当我编译代码有时它打印完美,有时它什么都不打印,有时打印一半的数据然后停止.当我调试代码时,同样奇怪的行为发生,当它在调试期间失败时抛出错误"Map.exe已触发断点.",当我使用cout时,错误在print方法中出现.
cmap.h
#pragma once
class CMap
{
public:
CMap();
~CMap();
CMap& Add(int id, int value);
void print() const;
private:
class container
{
public:
~container();
int container_id = 0;
int container_value = 0;
};
container* p_komp_;
int dim_ = -1;
void resize();
};
Run Code Online (Sandbox Code Playgroud)
cmap.cpp
#include "cmap.h"
#include <iostream>
using namespace std;
CMap::CMap()
{
p_komp_ = new container[0];
}
CMap::~CMap()
{
p_komp_ = nullptr;
cout << "destroy cmap";
}
CMap& CMap::Add(int id, int value)
{
resize();
p_komp_[dim_].container_id = id;
p_komp_[dim_].container_value = value; …Run Code Online (Sandbox Code Playgroud) 通常我们以下列格式声明数组:
DataType array_name[SIZE];
Run Code Online (Sandbox Code Playgroud)
所以如果我尝试为例如创建0长度数组
int arr[0]; //Line#1
arr[0] = 5; //Line#2
Run Code Online (Sandbox Code Playgroud)
执行上面的代码时,我没有收到任何错误.在这种情况下,是否为单个整数分配了内存?
// new T[0] 分配一个零大小的数组可以有值吗?
auto pv=new int[0];
cout<<pv<<endl; //0x... ?
*pv=123;
cout<<*pv<<endl; //123 ?
delete[] pv;
Run Code Online (Sandbox Code Playgroud)
为什么?如果是这样,新 T[0] 和新 T[1] 之间有什么区别
为什么我可以设置 0 大小数组的值...?
我研究了两种不同的方法来为矩阵的元素分配内存
方法n.1
int** matrix = new int*[rows];
for (int i = 0; i < rows; ++i)
matrix[i] = new int[cols];
Run Code Online (Sandbox Code Playgroud)
方法n.2
int** matrix = new int*[rows];
if (rows)
{
matrix[0] = new int[rows * cols];
for (int i = 1; i < rows; ++i)
matrix[i] = matrix[0] + i * cols;
}
Run Code Online (Sandbox Code Playgroud)
我可以弄清楚方法n.1做了什么,但我无法弄清楚究竟应该在方法n.2中做什么if子句(我会在没有它的情况下实现它,并且它不起作用,使用if子句,它...)
编辑:这是一个显示我的问题的代码.为什么加载需要这么长时间(~30秒)?
Codepad拒绝显示输出(超时),所以如果你想运行它,只需自己编译即可.
另外,为什么一旦程序启动就不执行cout <<语句?
已经有一段时间了(去年的Java课程).自从我的学校不提供C++以来,我一直在努力学习C++.我写了一个简单的程序,只是为了测试我到目前为止所学到的东西 - 实际上只是语法 - 然后才进入中间件.无论如何我只想强调我从不寻找答案,我宁愿你质疑我的物流,所以我可以重新思考一些事情,并可能自己完成.我认为既然我可以用Java成功地编写这个,那么在C++中一切都会很好,但我遇到了各种各样的问题.我试图调试并逐步完成,但我仍然不明白为什么我的一些变量没有得到我指定的值.如果你能指出我正确的方向,我会非常感激.
// This program will create any number of teams the user chooses,
// give each a score and calculate the average of all the teams.
#include <iostream>
using namespace std;
int main(){
//number of teams
int teamCount;
//array to keep scores
int team[0];
//total of scores
int total=0;
//average of all scores
int average=0;
cout<<"How many teams do you want to keep scores of?"<<endl;
cin>>teamCount;
//cout<<teamCount;
//ask the person for the score as many time …Run Code Online (Sandbox Code Playgroud)