Home > Net >  Can we take the value of iterator which was returned from lower_bound as vector index?
Can we take the value of iterator which was returned from lower_bound as vector index?

Time:04-22

I'm new to vector in C and trying to get how it works. First, I have a vector array:

vector<int>container;

Then I want to get the position of a given number in a vector array.

vector<int>::iterator position;
    position = lower_bound(container.begin(), container.end(), temp);

After that, I want to get the value at that position that was returned from lower_bound by

container[position]

But I get the error that

No viable overloaded operator[] for type 'vector'

When I change it into *(position 1), it works fine. So what is the different between those two?

CodePudding user response:

Welcome to stackoverflow :)

First of all, we should understand what an iterator is. According to the hackingcpp

  • objects that point to a location
  • may point to a readable memory address / object
  • ..

There are a lot of containers in C STL, such as vector, list, map and others.

A iterator is an abstraction of pointer, which allows you to access elements stored in container, use algorithm(such as sort, find, lower_bound) provided by STL no matter what kind of container we have.

Therefore, the return type of std::lower_bound is an iterator as you know vector<int>::iterator,

You couldn't access an element by calling container[position], there is no such function vector[iterator] provided by vector.

When I change it into *(position 1)

*itreator means return the value of where an iterator points out.

By the way, it's dangerous to do something like this *(position 1).

Since perhaps the given value tmp is in vector, perhaps it's not, so you should check whether the given value tmp is in vector by calling iterator != vector.end().

CodePudding user response:

std::lower_bound returns a ForwardIterator (See: C named requirements: LegacyForwardIterator).
You can dereference it just like you would a pointer, eg:

std::vector<int> container;
// ...
auto it = std::lower_bound(container.begin(), container.end(), foo);
if (container.end() == it) { 
  throw or_something("handle error?");
}
const int x = *it;
const int y = container[std::distance(container.begin(), it)];

In that example x == y is true. (See: Compiler Explorer)

  • Related