Jump to content

New to programming with array questions.

- - - - -

  • Please log in to reply
12 replies to this topic

#1
Reject

Reject

    Newbie

  • Members
  • PipPip
  • 10 posts
Here is what I am working on:

I want a chunk of code that will start will an array of 6 numbers.
Prompt the user to enter one of the 6 numbers.
Check to see if that number is one of the options.
if it is --> assign that value to a variable and delete it from the array
else --> prompt the user again.
Repeat until all numbers have been used.
Verify then end result with a print out.

Here is what I have so far:


int searchList(int[], int, int);                  // In the header


// In the body

int x[] = {1,2,3,4,5,6};

int search, value;


cout << "    What is the value you would like to use?        ";

cin >> search;

value = searchList(x, 6, search);

delete x[value];



Try to compile and get an error saying that the delete command is looking for a pointer...

Tried this:



int searchList(int[], int, int);                  // In the header


// In the body

int x[] = {1,2,3,4,5,6};

int search, value;

int* ptr = x[value];


cout << "    What is the value you would like to use?        ";

cin >> search;

value = searchList(x, 6, search);

delete ptr;



Received an error: invalid conversion int to int...

Okay... Tried this:



int searchList(int[], int, int);                  // In the header


// In the body

int x[] = {1,2,3,4,5,6};

int search, value;

int* ptr = &x[value];


cout << "    What is the value you would like to use?        ";

cin >> search;

value = searchList(x, 6, search);

delete ptr;



I get a long list of "[Linker error] undefined reference to `searchList(int*, int, int)' " on compile.

Need a little guidance, am I trying to do something that is that is not allowed or is there another command I should be using?

Thanks for your help in advance!

#2
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
I believe you must create an array with the new[] keyword before you can deallocate it with the delete[] keyword.

Regardless, you will require a linear algorithm to remove the element, such as copying all elements in front of the unwanted entry left, and copy the resulting array minus one len to another clean array. A sentinel value could be used, such replacing the element with -1 to signify it is not to be used as well.

I would therefor recommend you use a vector to store and remove or sort elements. C++ (and other data structures or containers) are provided to aid in situations exactly as this.
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#3
Reject

Reject

    Newbie

  • Members
  • PipPip
  • 10 posts
Okay, still experiencing boat loads of fail here...

Tried with Vectors:


//...

// Declare

     int search;

     vector<int>::iterator value;

     vector <int> myStats(1);

//Populate

     myStats.push_back(16);

     myStats.push_back(14);

     myStats.push_back(13);

     myStats.push_back(12);

     myStats.push_back(11);

     myStats.push_back(10);

// Print Out

     for ( int i = 1; i < myStats.size(); i++ ){

     cout << myStats[i] << " ";

     }

// User Input

     cout << "    What is the value you would like to use        \n";

     cin >> search;

//Search Vector for value

     value = find(myStats.begin(), myStats.end(), search);

//Test line = ALWAYS comes back as 0

     cout << *value;

     myStats.erase(value);


Little Guidance please?

#4
Flying Dutchman

Flying Dutchman

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 889 posts
  • Location:::1
I don't know what's wrong, I tried your code and it outputs the input number. More importantly, does it remove the element?
A conclusion is where you got tired of thinking.
#define class struct    // All is public.

#5
Zer033

Zer033

    Learning Programmer

  • Members
  • PipPipPip
  • 79 posts
The delete keyword is used to deallocate memory and the new keyword is to allocate memory. A pointer is a data type that holds values of memory addresses. So when you allocate new memory space using the new keyword assign it to a pointer because memory spaces are the data that pointers hold. Pointers can still point to memory spaces after deallocation so you should set pointers to NULL as well.

so use pointer like this:


int *x = new int[6];

//access it like a normal array
x[0] = 1;
x[1] = 2;
//etc

//delete it like this

delete[] x;
x = NULL;

Anyway, I have to go so can't really look too much at your code right now.


For your first post is that your code exactly or did you just copy and paste certain parts? You have the function prototype there, but you haven't actually created the function if so. This could be the reason for undefined reference. You still have to write the function heading and body even though you have a function prototype.

#6
Reject

Reject

    Newbie

  • Members
  • PipPip
  • 10 posts

Flying Dutchman said:

I don't know what's wrong, I tried your code and it outputs the input number. More importantly, does it remove the element?

The problem that I am having is that the
value = find(myStats.begin(), myStats.end(), search);
section, it always returns 0 to the value variable, so if the user inputs 10 as the first input, it erases 16 from the vector.

I will post the entire code below as a separate reply.

#7
Reject

Reject

    Newbie

  • Members
  • PipPip
  • 10 posts
Here is the entire bit of code that I have been working with:

I know, I know, but I thought it would be a fun project that would tap on a lot of different requirements. =)


#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

void Start();

void CharName();

void CharGen();

int CharStats();


int searchList(int[], int, int);


struct Hero{

       char name[20];

       int str, con, dex, intel, wis, cha;

       int ac, fort, ref, will;

       int speed, passin, passperc;

       int hp, blood, surge, surgpday, gen;

       } Slot;


main(){

       Start();

       CharName();

       CharGen();

       CharStats();

//Have not been created yet:

       //CharRace();

       //CharClass();

       //CharFeats();

       //Finalize();

//Test String:

       cout << "\n\n You made it to the end!!";

       system("Pause");

       }


void Start(){

     cout << "                       Welcome to the D&D Charactor Creator\n\n";

//Ignore the sad puns

     cout << "         This is brought to you by idle minds!\n\n";

     system("Pause");

     }


void CharName(){

     char ans;

     char character[20];

     system("cls");

     cout << "            Name\n\n";

     cout << "        Let's start with your name, hero... What should I call you?\n\n";

     cin >> character;

//Having a problem here too... Will not print out struct name correctly...

     Slot.name[20] = character[20];

     cout << "\n\n Is " << Slot.name << " really what you want to call yourself?\n\n";

     cin >> ans;

     switch (ans){

            case ('Y'):

                  cout << "\n\n" << Slot.name << " is it? That's original... \n\n";

                  cout << "Well, lets move on then and see what you are made of hero.\n\n";

                  system("Pause");

                  break;

            case ('y'):

                  cout << "\n\n" << Slot.name << " is it? That's original... \n\n";

                  cout << "Well, lets move on then and see what you are made of hero.\n\n";

                  system("Pause");

                  break;

            case ('N'):

                  cout << "Sorry about that... Too many orcs screaming in my ears....\n\n";

                  cout << "Lets try that again...\n\n";

                  system("pause");

                  CharName();

            case ('n'):

                  cout << "Sorry about that... Too many orcs screaming in my ears....\n\n";

                  cout << "Lets try that again...\n\n";

                  system("pause");

                  CharName();

            default:

                  cout << "One too many goblin clubs to the skull there sonny Jim?\n\n";

                  cout << "Try that again...\n\n";

                  system("pause");

                  CharName();

                  }

                  }


void CharGen(){

     cout << "        Gender Selection\n\n";

     cout << "    Your kind of beat up " << Slot.name << ", what is your gender?\n\n";

     cout << "    1.)  Male\n";

     cout << "    2.)  Female\n\n";

     cin >> Slot.gen;

     

     }


int CharStats(){

     int search;

     vector<int>::interator value;

     vector <int> myStats(1);

     myStats.push_back(16);

     myStats.push_back(14);

     myStats.push_back(13);

     myStats.push_back(12);

     myStats.push_back(11);

     myStats.push_back(10);

     system("cls");

     cout << "        Character Stat Generation\n\n";

     cout << "    Here we will create your charactor's stats.\n";

     cout << "    You have the following stats available to use in your character:\n\n";

     for ( int i = 1; i < myStats.size(); i++ ){

     cout << myStats[i] << " ";

     }

     cout << "    What is the value you would like to use for Strength?        \n";

     cin >> search;

     search = Slot.str;

     value = find(myStats.begin(), myStats.end(), search);

     cout << *value;

     myStats.erase(value);

     cout << "\n\n    You have the following stats available to use in your character:\n\n";

     for ( int i = 1; i < myStats.size(); i++ ){

     cout << myStats[i] << " ";

     }

     cout << "    What is the value you would like to use for Constitution?    \n";

     cin >> search;

     search = Slot.con;

     value = find(myStats.begin(), myStats.end(), search);

     myStats.erase(value);

     cout << "\n\n    You have the following stats available to use in your character:\n\n";

     for ( int i = 1; i < myStats.size(); i++ ){

     cout << myStats[i] << " ";

     }

     cout << "    What is the value you would like to use for Dexterity?       \n";

     cin >> search;

     search = Slot.dex;

     value = find(myStats.begin(), myStats.end(), search);

     myStats.erase(value);

     cout << "\n\n    You have the following stats available to use in your character:\n\n";

     for ( int i = 1; i < myStats.size(); i++ ){

     cout << myStats[i] << " ";

     }

     cout << "    What is the value you would like to use for Intelligence?    \n";

     cin >> search;

     search = Slot.intel;

     value = find(myStats.begin(), myStats.end(), search);

     myStats.erase(value);

     cout << "\n\n    You have the following stats available to use in your character:\n\n";

     for ( int i = 1; i < myStats.size(); i++ ){

     cout << myStats[i] << " ";

     }

     cout << "    What is the value you would like to use for Wisdom?          \n";

     cin >> search;

     search = Slot.wis;

     value = find(myStats.begin(), myStats.end(), search);

     myStats.erase(value);

     cout << "\n\n    You have the following stats available to use in your character:\n\n";

     for ( int i = 1; i < myStats.size(); i++ ){

     cout << myStats[i] << " ";

     }

     cout << "    What is the value you would like to use for Charisma?        \n";

     cin >> search;

     search = Slot.cha;

     value = find(myStats.begin(), myStats.end(), search);

     myStats.erase(value);

     return 0;

     }



#8
Zer033

Zer033

    Learning Programmer

  • Members
  • PipPipPip
  • 79 posts
One thing I noticed dealing with why your name doesn't show up is where you do this:

Slot.name[20] = character[20];

Arrays need to be assigned per component. So you have to use a for loop to set each character of one to the other. Assigning slot.name[20] = character[20] just sets the index of 20 equal to each other.

//Having a problem here too... Will not print out struct name correctly...[FONT=Tahoma]

[/FONT]for (int i = 0; i < 20; i++)
         Slot.name[i] = character[i];

     cout << "\n\n Is " << Slot.name << " really what you want to call yourself?\n\n";



That's all the time I have for now, but I'll look at the other problem a bit later.

#9
Reject

Reject

    Newbie

  • Members
  • PipPip
  • 10 posts

Zer033 said:

One thing I noticed dealing with why your name doesn't show up is where you do this:


Slot.name[20] = character[20];


Arrays need to be assigned per component. So you have to use a for loop to set each character of one to the other. Assigning slot.name[20] = character[20] just sets the index of 20 equal to each other.


//Having a problem here too... Will not print out struct name correctly...[FONT=Tahoma]


[/FONT]for (int i = 0; i < 20; i++)

         Slot.name[i] = character[i];


     cout << "\n\n Is " << Slot.name << " really what you want to call yourself?\n\n";




That's all the time I have for now, but I'll look at the other problem a bit later.

So you actually have to sent each "container slot" equal to each other in order for this to read out correctly?

Okay, then 2 more questions:
1.) Does it make more sense, or is it even possible, to have a pointer change the address directly with a char input?
2.) Does it make more or less sense to use the string command and pass it directly as a complete line? Is there an advantage to either?

#10
Zer033

Zer033

    Learning Programmer

  • Members
  • PipPipPip
  • 79 posts
Yes arrays have to be set per component they can't use the assignment operator to just set one equal to the other. Now that isn't to say you couldn't somehow overload the assignment operator to set two arrays equal which would essentially allow you to use the assignment operator in the way that you used it, but that might be a bit off topic. For example I believe the vector class allows two vectors to be set equal to each other using the assignment operator and that is because the assignment operator for that class is overloaded, which basically means the overloading function is doing the per component assignment and that implementation is hidden from you (the user over the vector class).

The thing that creating a char pointer will do for you is allow you to dynamically allocate the length of the array. For instance in your code you have it hard coded at 20, but you could somehow create an array of just the amount of characters that you need if you used a pointer and this could be changed per run of the program. Now I don't know if it has any value in your example here, but dynamically allocated arrays are much more flexible than static arrays. In the case of static arrays you'll usually just make the array hold more than you think you'll ever need which can waste memory. You'll also find dynamically created arrays useful for creating data structures of your own if you choose like linked lists or queues.

So an example of a dynamically created array (which means the size is created at run time) is below which just shows how you can at run time ask a user for the array length and set it to that. Now this is real simple thing just to show it, but you could use this in classes when making a constructor or something as well so that when an object is created it could be created with a different array length as an example.

int main()
{
int NameSize;

cout << "what is length of array? ";
cin >> NameSize;

char *name = new char[NameSize];

return 0;
}

If you try to do that without using pointers and the new operator you'll get some errors. The reason is at compile time it needs to know how much memory to set aside for that array, but the new operator allows you to dynamically at runtime allocate memory space.

As for using a string, that is probably what most people would do, but I thought you were intentionally using arrays to learn them.

#11
Reject

Reject

    Newbie

  • Members
  • PipPip
  • 10 posts
I guess I am doing a little of both. I am using the basic stuff that I am learning as I go and looking for suggestions as to what *should* be done in different situations.
I guess, I can't use a skill set I haven't learned yet, so direction and guidance is always welcome in any respect.

I am open to all comments regardless!

Thank you all, by the way, for all your time and responses!

#12
Reject

Reject

    Newbie

  • Members
  • PipPip
  • 10 posts
Did anyone have an idea as to why the "vector<int>::iterator value;" always comes back as 0 in the CharStats() function?




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users