I need index access to my std::vector
, and therefore I must check if an index is already available to first delete them, and then set a new value.
Here's my setter function:
void SetVector(int position, int value) {
std::vector<int>iterator it = testVector.begin();
// need a check here
testVector.insert(it-testVector.begin()+position, value);
}
Or is this the wrong C++ collection for my needs? (should grow dynamically, so no std:array
possible). Could use a std::map
but maybe it's also possible with std::vector
.
I don't believe the question is clear. If you want
"to first delete them, and then set a new value."
this might work
void SetVector(int position, int value) {
if (position < testVector.size()) {
testVector[position] = value;
}
else {
testVector.push_back(value);
}
}
You should really make the int position
the testVector
's size_type
.
The requirements aren't entirely clear from the question, but I'm assuming that you want to end up with testVector[position] == value
, whether or not position
was in range to begin with.
First grow the vector if it's too small. This will insert zero-values after whatever is already there.
if (position >= testVector.size()) {
testVector.resize(position+1);
}
Then assign the element you want to set:
testVector[position] = value;
You can use std::vector::at who throw an exception if you don't have anything at this index.
The function automatically checks whether n is within the bounds of valid elements in the vector, throwing an out_of_range exception if it is not (i.e., if n is greater or equal than its size). This is in contrast with member operator[], that does not check against bounds.
And since you get a reference on the object at the given index, you can change/delete the value
void SetVector(int position, int value) {
try
{
testVector.at(position) = value;
}
catch (const std::out_of_range& oor) {
testVector.resize(position + 1);
testVector[position] = value;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With