C++ vector question

EvilManagedCare

Senior member
Nov 6, 2004
324
0
0
Hi. I'm trying to learn about various STL structures and plan to use a vector in an upcoming project. I was playing around with a simple program adding and displaying integers from a vector. Nothing fancy. I wrote a bit having an iterator go through and display the value to which it points. I have followed an example from cppreferrence.com and get an error from windows, not the compiler: vectortest.exe has encountered a problem and mus t close. Sorry for the inconvenience blah blah blah. Pressing the button to display more detailed information seems to give a memory map, but no specific exceptions. FWIW the vector contains only 20 elements. Here's the code. I'm using Dev-C++ as my IDE.

/*
vectortest.cpp
This is a program examining some functionality of vectors.
*/

#include <iostream>
#include <vector>
// #include <algorithm>
// #include <iterator>

using namespace std;

int main()
{
const int MAX = 20;
vector<int> v;
vector<int>::iterator iter = v.begin();
int i;

for (i = 0; i < MAX; i++)
{
v.push_back(i);
printf("Value %d is %d\n", i, v);
}

cout << "First value is " << v.front() << endl;
cout << "There are " << v.size() << " items in this vector." << endl;


// The following generates an error in Windows when not commented out
while (iter != v.end())
{
cout << *iter << endl;
++iter;
}

cin.get();
return 0;

}

I don't know what the problem is, I thought I declared the iterator correctly. Any ideas what is wrong?

Thanks in advance.

BTW this is not a school project, though I am playing with the vector now as I intend to use one in an upcoming project.
 

EvilManagedCare

Senior member
Nov 6, 2004
324
0
0
Lesson learned: don't declare and initialize the iterator before the vector is populated. Waiting to declare it until after the vector is filled took care of it. It works fine now. Nothing to see here. Like I said, I'm learning :eek:
 

Cogman

Lifer
Sep 19, 2000
10,286
147
106
Originally posted by: EvilManagedCare
Lesson learned: don't declare and initialize the iterator before the vector is populated. Waiting to declare it until after the vector is filled took care of it. It works fine now. Nothing to see here. Like I said, I'm learning :eek:

Looks like microsoft's implementation of the iterator is broken. Most likely, they are just using a simple pointer to the beginning of the vector, however, it is supposed to automatically update itself when the vector reallocates memory. (unless you are talking about the ending iterator, then it makes sense that this wouldn't work as that should only be pointing to the nth element of the vector.)