A vector or an array of unknown size

This is a discussion on A vector or an array of unknown size within the C++ Programming forums, part of the General Programming Boards category; Dear All, Can anyoneone help me to declare and initialize an array or a vector which size is to be ...

  1. #1
    Registered User
    Join Date
    Dec 2004
    Posts
    50

    A vector or an array of unknown size

    Dear All,
    Can anyoneone help me to declare and initialize an array or a vector which size is to be determined in the course of the programm?
    Thank you

  2. #2
    Handy Andy andyhunter's Avatar
    Join Date
    Dec 2004
    Posts
    540
    Below is an attached program that takes an undefined length string from the user and reverses it. Make not of the use of realloc().

    Code:
    /* Passing addresses demo
       This program takes a string of undeterminate length and reverses it displaying both to the user */
    
    #include <stdio.h>
    #include <stdlib.h> //used for realloc()
    #include <string.h> //used for strlen() function
    
    int reverseString(char*, char*); //function prototype
    
    int main(void) {
    
    	char* str = NULL; //set up and 
    	char* rstr = NULL;// initialize pointers
    	int ch, len = 0;
    
    	printf("Enter a string to reverse: ");
    	fflush(stdout);
    
    	//this takes the string types character by character and adds it to the string str
    	while((ch = getchar()) != '\n' && ch != EOF) {
    		if(!(str = (char*)realloc(str, len+1))) { //<-----------------Increases array size by 1 char
    			return(1);
    		}
    		str[len++] = ch;
    	}
    	//-------------------------------------------------------------------------------
    	str[len] = '\0'; //adds flag to signal string is finished
    	
    	rstr = (char*)realloc(rstr, len);//<------------------------------Makes rstr same size as len = size of str
    	
    	reverseString(str, rstr);
    
    	printf("You entered: %s \n", str);
    	printf("The reverse is: %s \n", rstr);
    	
    	return(0);
    }
    //this function starts at the end of input and writes to the beginning of revInput
    int reverseString(char* input, char* revInput) {
    
    	int curChar = 0;
    
    	for(int i = (strlen(input)-1); i>=0; i--) {
    		revInput[curChar] = input[i];
    		curChar++;
    	}
    	revInput[curChar] = '\0';
    
    	return(0);
    }
    This should answer your question of I understand it.

    Happy Coding!!
    i don't think most standard compilers support programmers with more than 4 red boxes - Misplaced

    It is my sacred duity to stand in the path of the flood of ignorance and blatant stupidity... - quzah

    Such pointless tricks ceased to be interesting or useful when we came down from the trees and started using higher level languages. - Salem

  3. #3
    Never Exist Hermitsky's Avatar
    Join Date
    Jul 2004
    Posts
    149
    as we are programming with C++, it is easy to make an array with variable size .

    a dynamic list:

    Code:
    //class to store info of books and  basic method
    #include<string>
    #include<sstream>
    #include<cstdlib>
    using namespace std;
    
    const long MAX_C =100000;
    const int MAX_Q =10000;
    
    class BMSBook
    {
    public:
    
    BMSBook()
    {
        isbn="";
        title="";
        press="";
        instruction="";
        type="";
        quantity=0;
        next=NULL;
    }
    BMSBook(string _isbn,string _title,string _press,string _instruction,string _type,int _quantity,BMSBook *_next)
    {
        isbn=_isbn;
        title=_title;
        press=_press;
        instruction=_instruction;
        type=_type;
        quantity=_quantity;
        next=_next;
    }
    BMSBook(BMSBook *_book)
    {
        isbn=_book->isbn;
        title=_book->title;
        press=_book->press;
        instruction=_book->instruction;
        type=_book->type;
        quantity=_book->quantity;
        next=_book->next;
    }
    
    
    
    protected:
    string isbn;
    string title;
    string press;
    string instruction;
    string type;
    int quantity;
    BMSBook *next;
    friend class BMSBooks;
    };
    
    
    
    class BMSBooks
    {
    public:
    BMSBooks()
    {
        thebook=NULL;
        current;
        count=0;
    }
    ~BMSBooks()
    {
        while(thebook!=NULL)
        {
            current=thebook;
            thebook=current->next;
            delete current;
        }
    }
    
    
    bool getdata(string &_isbn,string &_title,string &_press,string &_instruction,string &_type,int &_quantity)
    {
      if(current!=NULL)
      {
        _isbn=current->isbn;
        _title=current->title;
        _press=current->press;
        _instruction=current->instruction;
        _type=current->type;
        _quantity=current->quantity;
        return true;
      }
    return false;
    }
    
    
    bool gettitle(string &_title)
    {
      if(current!=NULL)
      {
        _title=current->title;
        return true;
      }
    return false;
    }
    
    
    void moveforward(int index)
    {
        while(index&&(current->next!=NULL))
        {
            current=current->next;
            index--;
        }
    }
    
    
    bool match(string title,string press,string instruction,string type,int quantity)
    {
          if(isempty())return false;
                if(title!="")
                {
                if(title!=current->title)return false;
                }
                if(press!="")
                {
                if(press!=current->press)return false;
                }
                if(instruction!="")
                {
                if(instruction!=current->instruction)return false;
                }
                if(type!="")
                {
                if(type!=current->type)return false;
                }
                if(quantity!=0)
                {
                if(quantity!=current->quantity)return false;
                }
          return true;
    }
    
    bool moveonestep()
    {
        if(current->next!=NULL)
        {
            current=current->next;
            return true;
        }
    return false;
    }
    
    
    long searchbyisbn(int &cmp,const string &isbn)
    {
    BMSBook *temp;
    temp=thebook;
    movetotop();
    long tempindex=1;
    long top=count;
    long bottom=1;
            moveforward((top+bottom)/2-1);
            cmp=strcmp(isbn.c_str(),current->isbn.c_str());
        do
        {
            if(!cmp)
              {
                return (top+bottom)/2;
              }
            else if(cmp>0)
              {
                tempindex=(top+bottom)/2;
                temp=current;
                bottom=tempindex+1;
                moveforward((top+bottom)/2-tempindex);
              }
            else if(cmp<0)
              {
                current=temp;
                top=(top+bottom)/2;
                moveforward((top+bottom)/2-tempindex);
              }
             cmp=strcmp(isbn.c_str(),current->isbn.c_str());
        }while(top>bottom);
    return -1;
    }
    
    
    
    short add(string isbn,string title,string press,string instruction,string type,int quantity)
    {
    if((count>=MAX_C)||(quantity>=MAX_Q))return 2;
    if(checkisbn(isbn))
        {
            BMSBook *temp;
            int cmp;
            if(count)
                {
                    searchbyisbn(cmp,isbn);
                    if(!cmp)
                    {
                        if((current->quantity+quantity)>MAX_Q)return 2;
                        current->quantity+=quantity;
                        return 0;
                    }
                    else if(cmp>0)
                    {
                        temp=current->next;
                        current->next=new BMSBook(isbn, title, press, instruction, type,quantity,temp);
                        if(current->next==NULL)return 1;
                        count++;
                        return 0;
                    }
                    else if(cmp<0)
                    {
                        temp=new BMSBook(current->isbn,current->title,current->press,current->instruction,current->type,current->quantity,current->next);
                        if(temp==NULL)return 1;
                        current->isbn=isbn;
                        current->title=title;
                        current->press=press;
                        current->type=type;
                        current->instruction=instruction;
                        current->quantity=quantity;
                        current->next=temp;
                        count++;
                        return 0;
                    }
                }
            else
            {
                thebook=new BMSBook(isbn,title,press,instruction,type,quantity,NULL);
                if(thebook==NULL)return 1;
                count=1;
                return 0;
            }
        }
    return -1;
    }
    
    
    bool remove()
    {
        if(count)
        {
            BMSBook *temp;            
            if(current==thebook)
            {
                thebook=current->next;
                delete current;
            }
            else if(current->next==NULL)
            {
                delete current;
            }
            else
            {
                temp=current->next;
                current->isbn=temp->isbn;
                current->title=temp->title;
                current->press=temp->press;
                current->instruction=temp->instruction;
                current->type=temp->type;
                current->quantity=temp->quantity;
                current->next=temp->next;
                delete temp;
            }
            count--;
            return true;            
        }
    return false;
    }
    
    
    bool checkisbn(const string &isbn)
    {
    int sum=0,num=0,num1=0;
    if(isbn.size()!=13)return false;
    for(int loops=0;loops<12;loops++)
      {
      if(isdigit(isbn[loops]))
      {
      istringstream temp(isbn.substr(loops,1));
      temp>>num;
      sum+=(num*(++num1));
      }
      }
    num=sum%11;
    if(num>=10)
    {
    if((isbn.substr(12,1)!="x")&&(isbn.substr(12,1)!="X"))return false;
    }
    else
    {
    if(!isdigit(isbn[12]))return false;
    istringstream temp(isbn.substr(12,1));
    temp>>sum;
    if(num!=sum)return false;
    }
    return true;
    }
    
    bool update(string isbn,string title,string press,string instruction,string type,int quantity)
    {
        if(count&&(current!=NULL))
        {
                        current->isbn=isbn;
                        current->title=title;
                        current->press=press;
                        current->type=type;
                        current->instruction=instruction;
                        current->quantity=quantity;
                        return true;
        }
        return false;
    }
    
    bool isempty()
    {
    if(count)return false;
    return true;
    }
    
    void movetotop()
    {
    current=thebook;
    }
    
    void getcount(long &num)
    {
    num=count;
    }
    
    private:
    long count;
    BMSBook *thebook;
    BMSBook *current;
    };

    blow me ... ...

  4. #4
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    Hermitsky, andyhunter...you guys are awesome, *copies* *pastes* *compiles*

  5. #5
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,399
    A linked-list isn't exactly appropriate since the OP mentioned arrays and vectors. It is a simple matter to initialize an STL vector.
    Code:
    int main()
    {
    	vector<int> a(20); //declares a vector of 20 elements
    	vector<int> b(20,5); //declares a vector of 20 elements initialized to 5
    	//do stuff
    	return 0;
    }
    My STL implementation initializes everything to 0 (or empty, in the case of strings), but I'm not sure if that's standard. You can also initialize a vector with another vector or two iterators from a vector that denote a range of elements.
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Allocating an array of unknown size?
    By scarlet00014 in forum C Programming
    Replies: 2
    Last Post: 09-27-2008, 09:53 AM
  2. Replies: 16
    Last Post: 11-23-2007, 12:48 PM
  3. string array of unknown size
    By ringo_shells in forum C++ Programming
    Replies: 5
    Last Post: 05-02-2007, 01:21 PM
  4. Array size
    By tigrfire in forum C Programming
    Replies: 5
    Last Post: 11-14-2005, 07:45 PM
  5. Replies: 1
    Last Post: 09-10-2005, 06:02 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21