Προς το περιεχόμενο

c++ πινακας δεικτων


fonsde

Προτεινόμενες αναρτήσεις

Δημοσ.

έχω μια κλάση Letter, και θέλω σε μια άλλη κλάση να δημιουργώ letters

 

ορίζω λοιπόν

>Letter *gramma;

 

θέλω κάθε φορά να τα δημιουργώ ένα ένα

>for (i=1;i<100;i++){
  for (i=1;i<100;i++)
  gramma=new Letter[i];}

 

τι πρέπει να γράψω ώστε να μην χάνονται τα παλιά γράμματα ? δηλαδή να κάνω copy τα προηγούμενα και να δημιουργείται το τελευταίο κάθε φορά

 

 

ty

Δημοσ.

δεν ειμαι απολυτεα σιγουρος πως καταλαβα τι θες αλλα.....

 

το παρακάτω δημιουργει ενα πίνακα με 100 δεικτες

>
Letter **letters = new Letter*[100];

for(int i=0; i<100; i++)
    letters[i] = new Letter();

Δημοσ.

πίνακες vs vector

 

>
What's wrong with arrays?

In terms of time and space, an array is just about the optimal construct for accessing a sequence of objects in memory. It is, however, also a very low level data structure with a vast potential for misuse and errors and in essentially all cases there are better alternatives. By "better" I mean easier to write, easier to read, less error prone, and as fast. 

The two fundamental problems with arrays are that 
an array doesn't know its own size 
the name of an array converts to a pointer to its first element at the slightest provocation 
Consider some examples: 
void f(int a[], int s)
{
	// do something with a; the size of a is s
	for (int i = 0; i<s; ++i) a[i] = i;
}

int arr1[20];
int arr2[10];

void g()
{
	f(arr1,20);
	f(arr2,20);
}
The second call will scribble all over memory that doesn't belong to arr2. Naturally, a programmer usually get the size right, but it's extra work and ever so often someone makes the mistake. I prefer the simpler and cleaner version using the standard library vector: 
void f(vector<int>& v)
{
	// do something with v
	for (int i = 0; i<v.size(); ++i) v[i] = i;
}

vector<int> v1(20);
vector<int> v2(10);

void g()
{
	f(v1);
	f(v2);
}

 

απο εδώ

Δημοσ.

Εφ'όσον δεν ξέρεις το μέγεθος του πίνακα, μπορείς να χρησιμοποιήσεις είτε vector είτε δυναμικό πίνακα αντιγράφοντας τον κάθε φορά που εξαντλούνται οι θέσεις του σε έναν μεγαλύτερο. Vector σαφώς και είναι πιο εύκολη, άμεση, και γρήγορη λύση.

Αρχειοθετημένο

Αυτό το θέμα έχει αρχειοθετηθεί και είναι κλειστό για περαιτέρω απαντήσεις.

  • Δημιουργία νέου...