CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 17

Threaded View

  1. #1
    Join Date
    Jan 2005
    Location
    Akron, Ohio
    Posts
    670

    new to vectors, problems

    Hi all,

    I'm experimenting with vectors and trying to accomplish some basic things:

    1) trying to figure out whether or not "new" objects are deleted when the vector is destroyed or cleared.

    2) Saving and loading a vector by unformatted means.

    The following program should produce:

    0
    0
    1
    2
    3
    4

    but it doesn't. First, it appears that list.clear() is not working. So let's start with that problem. Can anyone tell me why list.clear() is not clearing the vector? Thank you.

    Code:
    #include <vector>
    #include <iostream>
    #include <conio.h>
    #include <fstream>
    using namespace std;
    
    class MyClass
    {
    public:
    	MyClass(int value);
    	virtual ~MyClass();
    
    	int Value;
    
    };
    
    MyClass::MyClass(int value)
    {
    	Value = value;
    }
    
    MyClass::~MyClass()
    {
    
    }
    
    int main()
    {
    int i = 0;
    	vector<MyClass> list;
    	MyClass* pNewMyClass = NULL;
    
    	for( i = 0 ; i < 5 ; i++)
    	{
    		pNewMyClass = new MyClass(i);
    		list.push_back(*pNewMyClass);
    	}
    
    	ofstream out("C:/CppPrograms/VectorExperiment/TempFile", ios::out | ios::binary );
    
    	if(!out)
    	{
    		cout << "Cannot open output file.\n";
    		return 1;
    	}
    
    	out.write((char*) &list, sizeof(class vector<MyClass>));
    	out.close();
    
    	list.clear();
    
    int size = list.size();
    	for( i = 0 ; i < size ; i++ )
    	{
    		cout << list[i].Value << endl;
    	}
    
    	ifstream in("C:/CppPrograms/VectorExperiment/TempFile", ios::out | ios::binary );
    
    	if(!in)
    	{
    		cout << "Cannot open input file.\n";
    		return 1;
    	}
    	in.read((char*) &list, sizeof(class vector<MyClass>));
    
    	for( i = 0 ; i < 5 ; i++)
    	{
    		cout << list[i].Value << endl;
    	}
    	in.close();
    
    	_getch();
    	return 0;
    }
    Last edited by paradoxresolved; September 11th, 2005 at 08:01 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured