PDA

View Full Version : [C++]Assegnare input a elemnto del vector.


codreanu
21-12-2007, 18:29
Ciao ragazzi. Sto studiando il C++, come libro ho "Thinking in C++" di Bruce Eckel. Ho il seguente codice:

#include <iostream>
#include <vector>
using namespace std;

int
main() {
vector<float> myVector;

for(int i = 0; i <= 5; i++) {
cout << "Enter a number: ";
cin >> myVector[i];
}
}


Uso Linux, sapete dirmi perche' mi da Segmentation fault? Grazie :).

variabilepippo
21-12-2007, 19:24
Uso Linux, sapete dirmi perche' mi da Segmentation fault?


Perché è sbagliato, quel codice non può funzionare su nessun sistema operativo.

Riporto una porzione del testo di Eckel (capitolo 2 - Introducing vector):


To add a brand-new element on the end of a vector, you use the member function push_back( ). (Remember that, since it’s a member function, you use a ‘.’ to call it for a particular object.) The reason the name of this member function might seem a bit verbose – push_back( ) instead of something simpler like “put” – is because there are other containers and other member functions for putting new elements into containers. For example, there is an insert( ) member function to put something in the middle of a container. vector supports this but its use is more complicated and we won’t need to explore it until Volume 2 of the book. There’s also a push_front( ) (not part of vector) to put things at the beginning. There are many more member functions in vector and many more containers in the Standard C++ Library, but you’ll be surprised at how much you can do just knowing about a few simple features.

cionci
21-12-2007, 19:37
In alternativa a push_back puoi continuare ad usare l'operatore [], ma devi usare il costruttore:

vector<float> myVector(5);

Ovviamente questa cosa è valida visto che in questo caso conosci il numero di elementi...se non lo conosci è meglio utilizzare push_back o ridimensionare il vettore (sconsigliabile).

codreanu
21-12-2007, 20:50
per curiosta', la cosa che ho fatto non puo' funzionare perche' un vector non e' indicizzato come un array?

variabilepippo
21-12-2007, 20:58
non puo' funzionare perche' un vector non e' indicizzato come un array?


Non può funzionare perché non hai specificato quanti elementi contiene il vector.

codreanu
21-12-2007, 21:28
Non può funzionare perché non hai specificato quanti elementi contiene il vector.

Grazie :).

kk3z
22-12-2007, 10:26
Potresti provare così:
#include <iostream>
#include <vector>
using namespace std;

int
main() {
vector<float> myVector;

for(int i = 0; i <= 5; i++) {
cout << "Enter a number: ";
cin >> back_inserter(myVector);
}
}

Può funzionare?

codreanu
22-12-2007, 15:24
Io ho risolto cosi:


#include <iostream>
#include <vector>
using namespace std;

int
main() {
vector<float> myVector;
float tmpVar;

for(int i = 0; i < 5; i++) {
cout << "Enter a number: ";
cin >> tmpVar;
myVector.push_back(tmpVar);
}
}


Ciao :)