Reputation: 37
template<typename T>
void findposition(T t, long value, typename T::iterator &before, typename T::iterator &position) {
typename T::iterator it = t.begin();
while(it != t.end()) {
before = it;
position = it;
if(*it > value) {
if(before != t.begin()) {
before = --it;
}
break;
}
++it;
}
}
vector<long>::iterator itVectorBefore;
vector<long>::iterator itVectorPosition;
findposition(myVector, 31, itVectorBefore, itVectorPosition);
myVector.insert(itVectorPosition, 31);
I don't understand why this piece of code is no working. When i ran it, i will get a segmentation fault. Another strange thing is, when du call findposition(myVector, 1, itVectorBefore, itVectorPosition). Both Iterators will hold a value of 0. I used gdb to investigate, but i couldn't find what is going wrong, because the before has the right value in the function findposition.
When someone of you has an idea what i have made wrong. I would be very pleased for an explanation.
Thanks for you help.
Upvotes: 0
Views: 78
Reputation: 206607
Neither before
nor after
get initialized when the container is empty.
typename T::iterator it = t.begin();
while(it != t.end()) { // When the input is empty, nothing
// is set to before or after.
The returned iterators are on a copy of the input argument.
You should change:
template<typename T>
void findposition(T t, long value,
typename T::iterator &before,
typename T::iterator &position) {
to
template<typename T>
void findposition(T& t, long value,
typename T::iterator &before,
typename T::iterator &position) {
Upvotes: 2