私はこのC++構造を有する:私は次のがかかりますどのくらいのメモリ見つけるためにしようとしている要素を追加するとベクトルのサイズが同じになるのはなぜですか?
typedef unsigned long T;
struct Node {
T index;
T length;
Node(): index(0), length(0), next(0) {}
Node(const T &ind, const T &len): index(ind), length(len), next(0) {}
vector<Node*> next;
};
を。私はそれが最大5つの要素を持つことを知っています。だからここに私は何をすべきかです:
int main(int argc, const char * argv[]) {
Node n;
Node* x = new Node(3, 4);
cout << "An empty vector of pointers: " << sizeof(n.next) << " bytes\n";
// Add five elements
for(int i = 0; i < 5; i++)
n.next.push_back(x);
cout<< "New size of the vector of pointers: " << n.next.size() << " elements\n";
cout<< "New size of the vector of pointers: " << sizeof(n.next) << " bytes\n";
return 0;
}
そして、ここでは私の出力です:
An empty vector of pointers: 24 bytes
New size of the vector of pointers: 5 elements
New size of the vector of pointers: 24 bytes
私の質問:どのように空のベクターは、5と24のバイトが、同じベクトルを取ることも可能ということです要素はまだ24バイトかかりますか?それ以上の記憶を取るべきではありませんか? * 24 + 5 * sizeof(Node *)*のように?
'int * x = new int [1]; int * y =新しいint [100] '。なぜ、sizeof(x)== sizeof(y) 'というのは、異なるサイズの配列を指していても、考えてみてください。 –
どちらの場合でもポインタのサイズは? – alekscooper
ベクトルがどのくらいのメモリを使用しているか知る必要がある場合は、正確にどのくらいの量のメモリが必要かを知る必要がある場合は、 'sizeof(n.next)+ n.next.capacity()* sizeof(Node *);ベクトルが割り当てられた場合は、独自のアロケータをベクターに与えます。 – evan