0

I'm playing around with Vectors, trying to better my knowledge of them. I created (i think) an empty vector: vector<string> contents; I created (i think) an accessor method: vector<string> getContents(); The method looks like this:

    vector<string> Album::getContents()
    {
        cout << "\nAlbum Contents:\n\n" << endl;
        for(vector<string>::iterator iter = contents.begin(); 
                                     iter !=contents.end(); iter++)
           {
               cout << *iter << endl;
           }
    }

Is this a suitable accessor method or am I over thinking something? Because my getContents doesn't return anything but prints it instead...

Assuming this is a valid method, what would be a better way to return the contents of a vector collection? Thanks.

Edit: I've just compiled it and my method needs to return something... So now im assuming my method is pointless and you should be able to return the vectors collection item by item similar to a Java array using a for-loop? I dunno.

4

1 回答 1

3

It is almost suitable. But your method needs to return something. It is defined to return a copy of a vector, so it could work by returning a copy of contents:

vector<string> Album::getContents()
{
    cout << "\nAlbum Contents:\n\n" << endl;
    for(vector<string>::iterator iter = contents.begin(); 
                                 iter !=contents.end(); iter++)
    {
           cout << *iter << endl;
    }
    return contents;  // return a copy of contents
}

You need to decide whether you want the caller to get a copy of the vector, or whether you want to allow them to get a reference to it. If you wanted to do so, your method would have to be one or both of

vector<string>& getCOntents();    // caller can get a read-write reference to contents
const vector<string>& getContents() const; // caller can get a read only reference to contents.

But beware, providing references to the internals of a class can be tricky to manage. At the very least, you must be sure that a Album object whose reference is taken by a caller lives at least as long as the reference.

于 2012-12-08T17:59:14.560 回答