Reputation: 768
I have a vector of text labels std::vector<sf::Text> texts_
. I can create texts and push them into the vector like this:
texts_.push_back(utils::createText(x, y, "SomeString1"));
texts_.push_back(utils::createText(x, y, "SomeString2"));
// etc.
and then easily draw them like this:
for (std::size_t i = 0; i < texts_.size(); ++i) {
renderTarget.draw(texts_.at(i));
}
I occasionally want to update the texts' strings. What I currently do is:
texts_.at(0).setString("SomeUniqueString1");
texts_.at(1).setString("SomeUniqueString2");
texts_.at(2).setString("SomeUniqueString3");
// ...
All of the above works just fine. Now to the problem:
When updating the strings, what if I accidentally try to access an index of for example 10 even though there are only for example 5 texts in the vector?
If I do that the program will obviously crash. I could check each time if the index is less than the vector's size but that's kind of overkill (I'd have to add a lot more checks to the code...)? How can I without much effort make sure that the text at that index exists in the vector?
Upvotes: 1
Views: 3583
Reputation: 308452
If the amount of boilerplate you'd need to write bothers you, just write it once in a function.
template<class T, typename ValueType>
void SafeSetValue(T & container, size_t index, const ValueType & value)
{
if (index < container.size())
container[index] = value;
}
SafeSetValue(texts_, 0, "SomeUniqueString1");
You can change the function to do something different in the case of an out-of-bounds index.
Upvotes: 4
Reputation: 104698
If I do that the program will obviously crash. I could check each time if the index is less than the vector's size but that's kind of overkill (I'd have to add a lot more checks to the code...)? How can I without much effort make sure that the text at that index exists in the vector?
If you're accessing the elements using std::vector<>::at()
, the check is being performed. If the index is out of range, then an exception will be thrown. Other member functions (notably operator[]
) are not checked.
Upvotes: 0