because of not enough reputation I can't comment a post on the the thread:
How to get position of a certain element in strings vector, to use it as an index in ints vector?
I want to know something regarding this answer:
Original answer on thread:
To get a position of an element in a vector knowing an iterator pointing to the element, simply subtract v.begin()
from the iterator:
ptrdiff_t pos = find(Names.begin(), Names.end(), old_name_) - Names.begin();
Now you need to check pos
against Names.size()
to see if it is out of bounds or not:
if(pos >= Names.size()) {
//old_name_ not found
}
vector iterators behave in ways similar to array pointers; most of what you know about pointer arithmetic can be applied to vector iterators as well.
Starting with C++11 you can use std::distance
in place of subtraction for both iterators and pointers:
ptrdiff_t pos = distance(Names.begin(), find(Names.begin(), Names.end(), old_name_));
Questions:
- How does this exactly work for the compiler? What happens in the background?
I know, that im passing two iterators to the find method, which seems logic: I pass the start and the end position. In between, I'm searching for the element. std::find() returns an iterator of the first element satisfying the value passed as third parameter to the std::find() method. So is std::distance doing nothing else than incrementing in a for loop something like a counter until it reaches the "end-point" iterator?
I could also write:
int index = distance(Names.begin(), find(Names.begin(), Names.end(), old_name_));
Why is it better to use ptrdiff_t
than an integer? Someone commented in the original post that it lets you store the distance between any pair of iterators into the same container, even in situations when the result is negative. But I do not really get the point of it. Maybe you could explain that a bit further. (:
I'm coming from C#, where you can use something like (demonstrated on a string):
string test = "Hello World"; int index = test.IndexOf("d");
This seems a lot easier compared to the methods used above in C++. Is there something equivalent in C++?
Thank you very much for your help!
Best regards