is there any vay to access iterator's index value without using another variable in the for loop?

Dani AI

Generated

Short answer: there is no single, portable "index" embedded in every STL iterator. Which technique works depends on the iterator category and on performance constraints. demonstrated how it looks for a vector; is correct that iterators are not numeric indices and associative containers (map/set) do not provide positional indices.

For random-access iterators (vector, deque, string) the offset from begin() can be obtained in constant time. For other iterator categories (list, map, set) there is no constant-time subtraction; std::distance will produce the element index but is O(N) for non-random-access iterators. In tight loops or nested comparisons it is therefore usually cheaper to maintain a simple counter that is incremented as the iterator advances.

A few concrete fixes and pitfalls visible in 's snippet:

  • Subtracting two map iterators does not compile because map iterators are not random-access. Use an external counter or std::distance (with the cost caveat).
  • Calling std::advance once and reusing the advanced iterator across outer-loop iterations is wrong; use std::next(it) to get the next iterator for each iteration.
  • The inner for-loop condition using the comma operator only tests the last expression; replace it with a logical AND (&&) or a while loop when walking two sequences in lockstep.
  • Using operator[] on a map (e.g., cube[tempo]) will create an entry if missing. To test existence without creating, use find() or count(), or use emplace/insert safely.

Example patterns (concise, modern C++):

for (auto it = cube.begin(); it != cube.end(); ++it) {
    for (auto its = std::next(it); its != cube.end(); ++its) {
        auto idx1 = std::distance(cube.begin(), it);   // O(N) for map
        auto idx2 = std::distance(cube.begin(), its);  // O(N) for map
        // compare element sequences with: while(p1!=end1 && p2!=end2) { ... }
    }
}

Practical rules: prefer an incremented counter for stable O(1) indexing in loops; only call std::distance when occasional or when working with random-access iterators; pick set/unordered_set/unordered_map when uniqueness and speed matter.

Recommended Answers

All 3 Replies

is there any vay to access iterator's index value without using another variable in the for loop?

#include <iostream>
#include <vector>
using namespace std;

int main()
{
	vector <int> vec;
	vector<int>::iterator iter;

	for(int i = 0; i < 5; ++i)
		vec.push_back(i);

	for(iter = vec.begin(); iter < vec.end(); ++iter)
		cout << iter - vec.begin() <<  " ";

	cin.get();
}

The results: 0 1 2 3 4 :)

That's just the point: a STL iterator is not an index value. It looks like an index value (via incr/decr overloaded operators) but it's not a number. The std::vector container (or std::valarray or std::string) has integer index values for its elements via overloaded subscript operator but std::map (or std::set) container has not any indicies at all.

In actual fact an index is a simplest iterator too but not vice versa.

Hi,

I am trying to see to which key the iterator is pointing in a map. is there a way to do so.
Also, would it be the fastest way to store unique keys in a map.

mapType::iterator it = cube.begin();
	mapType::iterator its = it;
	std::advance(its,1);
	for(; it!= cube.end(); ++it)
	{
		cout << "Inside it = " << (it) - cube.begin() << endl;
		cout << "Inside its = " << (its) - cube.begin() << endl;
		for(; its!= cube.end(); ++its)
		{
			cout << "its = " << (its) - cube.begin() << endl;
			vector<int>::const_iterator it1;
			vector<int>::const_iterator it3;
			for( it1 = it->first.begin(), it3 = its->first.begin(); it1!= it->first.end(), it3!= its->first.end(); ++it1,++it3)
			{
				//cout << *it1 << " " << *it3 << " ";
				if((*it1 == 0 && *it3 == 1) || (*it1 == 1 && *it3 == 0))
				break;
				else if(*it1 == *it3)
				tempo.push_back(*it1);
				else if((*it1 == 0 && *it3 == 2) || (*it1 == 2 && *it3 == 0))
				tempo.push_back(0);
				else 
				tempo.push_back(1);
			}
			if(cube.count(tempo) <= 0)
			cube[tempo].push_back(10);
			cout << endl;
		}
	}

The code marked in green does not work.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.