Hello everyone,
As a high school student I've been working game in my spare time as a way of furthering my programming skills, however I recently ran into a roadblock when attempting to learn vectors and convert some of my arrays into vectors.
I've been running into segmentation faults no matter how much I work on it and I think its due to how I'm defining objects in the vector.
With the code that you posted, you seem to be violating the bounds of the vector (s). The vector (s) need to be pushed-back for it/them to grow. For example:
1 2 3
std::vector<int> ints; // No items within this vector.
ints.push_back(10); // There's 1 item within the vector, now.
Thank you, that makes a lot more sense!
Unfortunately I'm still running into some errors. Regarding using the information within the vector, how exactly can I check and/or modify those values? For example, I have the code pasted below and I'm not sure if the syntax stays the same or do I need to change it for checking within vectors?
"how exactly can I check and/or modify those values?" (sic)
There's two ways you can access the data within a vector:
1) Use the vector::at() method. This returns a non-constant reference to the specified item.
2) Use the overloaded vector::operator[] operator.
Both do the same thing. However, vector::at() throws an std::out_of_range exception when the bounds of the vector are exceeded. The overloaded operator, however, doesn't, which effectively allows you to write to an unknown section of memory without generating a run-time error. The choice is yours.
Here's an example that uses both of the latter:
1 2 3 4 5 6 7 8 9 10 11 12
// Create a new vector with two items, both of which have the value of zero.
std::vector<int> new_vector(2, 0);
std::cout << "Values are: ";
// Using the overloaded sub-script operator:
std::cout << new_vector[0U] << ", ";
// Using vector::at():
std::cout << new_vector.at(1U)
std::endl(std::cout);
dev geo wrote:
"I'm not sure if the syntax stays the same or do I need to change it for checking within vectors?" (sic)