你不應該這樣做手動內存管理。使用向量:
#include <iostream>
#include <sstream>
#include <vector>
struct Image {
unsigned int l;
unsigned int b;
unsigned int h;
};
int main()
{
using namespace std;
std::vector<Image> image;
std::string line;
while(getline(cin,line))
{
if(rand()%2)
{
istringstream iss(line);
Image img;
while (iss >> img.l >> img.b >> img.h)
{
image.push_back(img);
}
}
}
}
更新
既然你沒有提供反饋(爲什麼delete[]
似乎是你的樣品中環內),我所能做的最好是張貼重構的建議包括修復/改進,我會做:
Live On Coliru
#include <iostream>
#include <sstream>
#include <cstring>
#include <cassert>
struct Image {
unsigned int l;
unsigned int b;
unsigned int h;
};
class Images {
private:
size_t capacity;
size_t size;
Image *images;
Images& operator=(Images const&); // not supported
Images(Images const&); // not supported
void autogrow() {
if (size >= capacity) {
int newCapacity = capacity * 2;
Image* newImage = new Image[newCapacity];
std::cout << "growing " << capacity << " -> " << newCapacity << "\n";
//only available in c++11:
static_assert(std::is_pod<Image>::value, "you're screwed");
memcpy(newImage, images, size * sizeof(Image));
capacity = newCapacity;
delete[] images;
images = newImage;
}
}
public:
Images() : capacity(1), size(0), images(new Image[capacity]) {
assert(images);
};
~Images() {
delete[] images;
}
Image& insert(Image const& img) {
autogrow();
assert(size<capacity);
return images[size++] = img;
}
};
int main()
{
using namespace std;
Images collection;
std::string line;
while(getline(cin,line))
{
if(true) {
istringstream iss(line);
Image cur;
while (iss >> cur.l >> cur.b >> cur.h) {
collection.insert(cur);
}
}
}
}
打印,例如
od /dev/urandom -Anone -t u4 -w36 | head -1000 | ./a.out
growing 1 -> 2
growing 2 -> 4
growing 4 -> 8
growing 8 -> 16
growing 16 -> 32
growing 32 -> 64
growing 64 -> 128
growing 128 -> 256
growing 256 -> 512
growing 512 -> 1024
growing 1024 -> 2048
growing 2048 -> 4096
請解釋原因之前,向下投票這個問題,我在這裏是新的,所以請體諒,並幫助我改進 – Harry
這是所有這些有缺陷的代碼,它需要一個更大的文章來告訴什麼。 –
請在這裏詢問之前使用調試器,或抱怨反對票。 –