Monday, April 25, 2011

How to create multiple objects in the same function but without overwriting each other?

I'm trying to create an object in a function, but I am running into the problem that variable names have to be defined at runtime. Is there something I can do like with arrays that allows ne to dynamically create a variable in a function and preferably give it a different name from the one created when the function was called last?

***I'm working in C++

EDIT: I can't give any code because I don't have any right now. All I have right now is pseudo code.

Basically, I'm trying to create a linked list, but the addNewItem() method that I want to use would require using the same method to create different objects.

EDIT: Technically, we're not making a linklist, just more of a proof of concept to understand how they work.

EDIT: Here's the code:

#include "linklist.h"
#include <iostream>
using namespace std;

struct linklist
{
    Student * obj;
    linklist * next;
};

linklist * head;

int main()
{

}
void addStudent(char * newsdnt)
{
    if(!head){
            linklist * a = new linklist;
            a->obj = new Student(newsdnt);
            a->next = 0;
            head = a;
            return;
    }else{
            linklist * a = new linklist;
            a->obj = new Student(newsdnt);
            a->next = 0;
            if(!head->next){
                    head->next = a;  // Can only have one or two items in list
            }
    }

}

From stackoverflow
  • I would suggest a vector:

    #include <vector>
    using namespace std;
    void foo()
    {
        vector<int> v;
        v.push_back(1);
        v.push_back(2);
        v.push_back(3);
        cout << v[0] + v[1] << endl;
    }
    
  • Assuming that you need N objects of some type T:Arrays are very much present in C++. So is the STL which provides you with a host of oppertunities. You need to define how you will want to access and use these objects -- that influences the choice of your container. But can you post some code so that our answers are a little less vague (and more helpful to you)?

  • I'm not exactly sure what you want but is sounds like you could use Multiset.

    Please provide more details, and I might be able to provide more help.

  • If you want a linked list - call new to create each new node and then add it to the list.

    Smth like this:

    void addStudent(char * newsdnt)
    {
        linklist* a = new linklist;
        a.obj = new Student(newsdnt);
        a.next = 0;
    
        if( head == 0 ) {
            head = a;
        } else {
            linklist* whereToAdd = head;
            while( whereToAdd.next != 0 ) {
                whereToAdd = whereToAdd.next;
            }
            whereToAdd.next = a;
        }
    }
    
    sharptooth : @Luc:What exactly was changed for formatting to become correct?
    Luc Touraille : I removed
     and added indentation. Otherwise, the first and last lines were left out of the code block (at least on my browser (Firefox 3)).
                                        
    sharptooth : Yeap, the same was on IE6. So should I just indent all the lines of code with at least one space to make them look as preformatted?
    Luc Touraille : You must indent your code with four spaces (or use the "code" button of the editor): http://stackoverflow.com/editing-help .
  • The easiest way to build a (singly) linked list is to add the new item at the front:

    linklist *head = 0;
    
    ...
    a->next = head;
    head = a;
    ...
    

    If it is acceptable to add items at the tail in O(N) time, then you scan the list each time to find the end.

    linklist head;
    
    ...
    a->next = 0;
    item = &head;
    while (item->next != 0)
        item = item->next;
    item->next = a;
    ...
    

    If you must add new items at the tail of the list in O(1) time, then keep a circular list, and a pointer to the tail of the list (so that tail->next is a pointer to the head of the list). (The previous list structures could be called 'open ended'.)

    linklist  root = { 0, &root };
    linklist *tail = &root;
    
    ...
    a->next = tail;
    tail->next = a;
    ...
    

    Beware: the termination conditions for iterating over the entire list (e.g. to find an item in the list) vary depending on the structure used (circular versus open-ended).

    Caveat: untested code!

    If you aren't sure what O(1) and O(N) means, then read up on 'Big O' notation.

    sharptooth : Circular list may be difficult to manupulate. If "add to end at O(n)" is needed it's often better to use an open-ended list with a service root element storing addresses of the first and last elements.
    Jonathan Leffler : Circular lists are relatively standard in doubly-linked lists. There's no big problem with singly-linked lists either; the termination condition ceases to be 'a->next == 0' and becomes 'a->next == start', not a huge difference and perfectly systematic (just like open-ended lists).
  • For starters I would suggest you rename your linkedlist struct to node and add a new linked list struct that holds the head, and (maybe) current / tail pointers. You should then implement methods in this class / struct that will allow you to manipulate it.

    What you're missing at the moment is a method that will traverse the list (recursively getting the next pointer until you're at the end) and return a pointer to the last element. Once you have that, you can set the next pointer of that element to your newly created object.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.