-1

I have the following vector:

std::vector< std::pair<std::string,bool > > myvec;

How can i browse and print elements of my vector with iterators?

nickhar
  • 19,981
  • 12
  • 60
  • 73
PersianGulf
  • 2,845
  • 6
  • 47
  • 67

2 Answers2

7

What is your problem?

typedef std::vector<std::pair<std::string, bool> > vector_type;
for (vector_type::const_iterator pos = myvec.begin();
     pos != myvec.end(); ++pos)
{
   std::cout << pos->first << " " << pos->second << std::endl;
}

or you can use std::for_each with some functor.

ForEveR
  • 55,233
  • 2
  • 119
  • 133
  • 1
    The overload won't work: both of the operand types are in the `std` namespace, so the overload would need to be placed in the `std` namespace. But, you aren't allowed to declare overloads in the `std` namespace. – James McNellis Aug 10 '12 at 18:29
  • You defined `typedef` as `vector` and defined `const_iterator` When i changed my code same you i get error, Because i'm using `find_if`. – PersianGulf Aug 10 '12 at 18:34
2
  1. Create iterator, pointing to the first element of the vector (syntax: Container::iterator iter = myContainer.begin())
  2. in a for-loop, iterate through all elements ( iterator has operator++; the end condition is - check if the iterator has reached the end of your container, like: iter != myContainer.end())
  3. Iterators are like pointers, to reach it's members, use operator->.
  4. std::pair is like a struct with two fields - first and second, so you can print a vector's element like: iter->first and iter->second.
Kiril Kirov
  • 37,467
  • 22
  • 115
  • 187