Hi everyone,
I need to pass a vector to an external function and then have that function read the items within the vector. I'm assuming I have to pass the vector by pointer. Other than that, there's no real reason I'm using a pointer here.
Below is a bit of code which shows what I'm trying to do. Everything works fine except for the "cout << PtrMyVector;" line.
Any suggestions whatsoever will be greatly appreciated!
Thanks,
-George

=================================================

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

void ReadMyVector(vector <int>* PtrMyVector)
  {
  cout << "Vector is:  { ";
  for (int i=0; i<PtrMyVector->size(); i++)
    {
    cout << PtrMyVector[i];
    cout << ", ";
    }
  cout << " }";
  }

void main()
  {
  int MyInts[] = {1, 2, 3, 4, 5, 6};
  vector<int> MyVector (MyInts, MyInts + sizeof(MyInts) / sizeof(int) );
  vector <int>* PtrMyVector = &MyVector;

  ReadMyVector( PtrMyVector );
  }

Recommended Answers

All 7 Replies

The reason that doesn't work is because it's an incorrect method of reading what is at point i in the vector.
You should be using his method

PtrMyVector->at(i);

Also i wanna make this comment:

do NOT use void main()!!!!
use int main() and make sure you return and interger! (return 0; )

code tags are also very nice!

Chris

The std::vector::at member function is not identical to std::vector::operator[] , use (*PtrMyVector)[i] . In actual fact better pass vector by reference:

void ReadMyVector(vector <int>& PtrMyVector);
commented: didn't know that, thanks :D +1

Hmm, thanks for that ArkM. My thought's were pass by refrence initally but...i though he may of had a reason behind not doing that

Chris

The only difference between vector::operator[] and vector::at is: at() must raise exception out_of_range for bad position values. So at function is (potentially) more expensive than subscript operator (has boundary check overheads).

Thanks Chris, that did the trick! Much appreciated!
Dumb C++ 101 question... why is it so terrible that main() doesn't return an int?

In a word, portability. int main() is the standard and therefore will work on any compiler which is compliant with the standard. void main() may work on some compilers, but isn't gauranteed to work on any, whether they are compliant with the standard or not. Besides, int has one less letter to type, so why waste your energy!

Thanks Chris, that did the trick! Much appreciated!
Dumb C++ 101 question... why is it so terrible that main() doesn't return an int?

Don't knock aside ArkM's suggestion of pass by refrence. It's probably the best method. Cuts out alot of stuff.

Also if you have no further question please mark as solved

Thanks,
Chris

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.