| | |
How can I access these arrays without ifs
Please support our C++ advertiser: Intel Parallel Studio Home
Thread Solved |
I was wondering how I could access my several countryAttachedXX arrays(in this post they start on line 85), without many if statements, determined by user input. I was thinking maybe an array of arrays, but had difficulty finding out how to do that on the web. Thanks,
-Matt
-Matt
C++ Syntax (Toggle Plain Text)
/**************************** * ISU program (text risk) * * created by Matthew * * in grade 12 programming. * ****************************/ #include <iostream> #include <list> #include <iterator> #include <vector> #include <algorithm> using namespace std; class humanPlayer { public: humanPlayer(string thePlayersName, unsigned int thePlayersTurnNum); ~humanPlayer(){}; void addToList(unsigned int countryToAdd) {countriesOwned.push_back(countryToAdd);} void showList(); int getSpecificListEntry(unsigned int memberSpot); int listSize() {return countriesOwned.size();} void removeFromList(unsigned int countryToRemove) {countriesOwned.remove(countryToRemove);} bool checkIfInList(unsigned int countryToCheck); string getPlayerName() {return playerName;} string getPlayerInitial() {return playerInitial;} int getPlayerTurnNum() {return playerTurnNum;} void setPlayerTurnNum(unsigned int newPlayerTurnNum); private: list<int> countriesOwned; string playerName; string playerInitial; unsigned int playerTurnNum; }; humanPlayer::humanPlayer(string thePlayersName, unsigned int thePlayersTurnNum) { playerName = thePlayersName; playerTurnNum = thePlayersTurnNum; playerInitial = thePlayersName[0]; } bool humanPlayer::checkIfInList(unsigned int countryToCheck) { if(find(countriesOwned.begin(), countriesOwned.end(), countryToCheck) != countriesOwned.end()) { return true; } else { return false; } } void humanPlayer::showList() { copy(countriesOwned.begin(),countriesOwned.end(),ostream_iterator<int>(cout,", ")); cout << endl; } void humanPlayer::setPlayerTurnNum(unsigned int newPlayerTurnNum) { playerTurnNum = newPlayerTurnNum; } int humanPlayer::getSpecificListEntry(unsigned int memberSpot) { list<int>::iterator iter; iter = countriesOwned.begin(); (*iter) += memberSpot; return (*iter); } int getName(), attackFunction(humanPlayer &), fortifyFunction(humanPlayer &); void countryDivider(), renderBoard(), mainTurn(), worldAffairsFunction(); unsigned int numOfPlayers; list<humanPlayer> jailHouse; list<humanPlayer>::iterator iter; vector<int> virginCountries; string playerInitialList[20] = " "; int countryPopulationArray[20] = {1}; int countryAttached00[2] = {1,3}; int countryAttached01[4] = {0,2,3,4}; int countryAttached02[4] = {1,4,5,13}; int countryAttached03[4] = {0,1,4,6}; int countryAttached04[6] = {1,2,3,5,6,7}; int countryAttached05[3] = {2,4,7}; int countryAttached06[4] = {3,4,7,8}; int main() { cout << "Welcome to text risk, the rules are the same as the board game,\n" << "minus risk cards, and an altered fortification rule set. \n" << "First off "; getName(); cout << endl << "The countries are now going to be randomly divided between the " << numOfPlayers << " of you:" << endl; countryDivider(); renderBoard(); mainTurn(); cout << "\n"; system("PAUSE"); } void mainTurn() { int initialTurnChoice = 0; while(true) { for(iter = jailHouse.begin(); iter != jailHouse.end(); ++iter) { bool turn = true; while(turn == true) { cout << endl << "Do you, " << (*iter).getPlayerName() << ", wish to: " << endl << "(1) Attack someone." << endl << "(2) Fortify somewhere." << endl << "(3) Don't do anything to anyone." << endl << "(4) Display current world affairs." << endl; cin >> initialTurnChoice; switch(initialTurnChoice) { case 1: attackFunction(*iter); break; case 2: fortifyFunction(*iter); break; case 3: turn = false; break; case 4: worldAffairsFunction(); break; } } } } } int getName() { cout << "how many players will there be? "; cin >> numOfPlayers; cout << endl; while(true) { if(numOfPlayers < 2) { cout << endl << "You cannot play risk with less than two players, \n" << "it's just not going to work. So how many people are\n" << "actually playing risk, total? "; cin >> numOfPlayers; } if(numOfPlayers > 8) { cout << endl << "Have you ever tried to play risk with more than 8 players?\n" << "Cut a couple people and then say how many people are going to\n" << "play risk, total: "; cin >> numOfPlayers; } if(numOfPlayers > 1) { if(numOfPlayers < 9) { break; } } } for(unsigned int i=0 ; i<numOfPlayers ; i++) { char name[256]; cin.ignore(255,'\n'); cout << "What is player " << (i+1) << "'s name? "; cin.get(name,256); jailHouse.push_back(humanPlayer(name,(i+1))); } } void countryDivider() { unsigned int counter = 0; for(unsigned int i=0 ; i<20 ; i++) { virginCountries.push_back(i); } random_shuffle(virginCountries.begin(), virginCountries.end()); while(counter != 20) { for(iter = jailHouse.begin(); iter != jailHouse.end(); ++iter) { (*iter).addToList(virginCountries.at(0)); playerInitialList[virginCountries.at(0)] = (*iter).getPlayerInitial(); virginCountries.erase(virginCountries.begin()); counter += 1; if(counter == 20) { break; } } } //test for(iter = jailHouse.begin(); iter != jailHouse.end(); ++iter) { cout << (*iter).getPlayerName() << ": "; (*iter).showList(); } } void renderBoard() { cout << endl << " __ ____" << endl << " N.A. | \\ / ." << endl << " \\__| \\ 2 | ____" << endl << " ____________ |" << playerInitialList[2] << " / __ Eu / | |" << endl << " / | 1 | \\ \\| /13\\ ___/ | |" << endl << "/ 0 |__" << playerInitialList[1] << "__|_/ |\\ ." << playerInitialList[13] << "_// 14 / |" << endl << "| " << playerInitialList[0] << " | 3 | 4|__|5\\ / " << playerInitialList[14] << " / |" << endl << " [url="http://www.daniweb.com/techtalkforums/"]\\/[/url] \\|__" << playerInitialList[3] << "_|_" << playerInitialList[4] << "__|_" << playerInitialList[5] << "_\\ __ |_/|_/| 19 /" << endl << " / | 6 | 7 / /15\\ __/ | " << playerInitialList[19] << " /" << endl << " |__" << playerInitialList[6] << "__|_" << playerInitialList[7] << "_/ ." << playerInitialList[15] << "_/ | 16 | /" << endl << " \\ 8 | / _" << playerInitialList[16] << " | |" << endl << " \\ " << playerInitialList[8] << " \\ /\\ / [url="http://www.daniweb.com/techtalkforums/"]\\/\\[/url] |" << endl << " \\ \\ /17|18/ ||" << endl << " _\\_ |" << playerInitialList[17] << "_/ ." << playerInitialList[18] << " \\|" << endl << " S.A._/ 9 \\__" << endl << " /___" << playerInitialList[9] << "____|" << endl << " | | /" << endl << " \\ 10|11/" << endl << " |" << playerInitialList[10] << " |" << playerInitialList[11] << "/" << endl << " |__|/" << endl << " |12/" << endl << " |" << playerInitialList[12] << "/" << endl << " |/" << endl; } int attackFunction(humanPlayer & obj) { unsigned int countryToAttackFrom; unsigned int countryToAttack; cout << endl << obj.getPlayerName() << ", which country do you wish to attack from? "; obj.showList(); cin >> countryToAttackFrom; if(obj.checkIfInList(countryToAttackFrom) == false) { cout << "You must attack from your own country.\n"; return 0; } if(countryPopulationArray[countryToAttackFrom] < 2) { cout << "You are unable to attack from that country, the army is too small.\n"; return 0; } cout << "Now, which country do you wish to attack? The only eligable countries to\n" << "attack are: "; } int fortifyFunction(humanPlayer & obj) { } void worldAffairsFunction() { cout << endl << "This is the current state of the game, player by player: \n"; renderBoard(); for(iter = jailHouse.begin(); iter != jailHouse.end(); ++iter) { cout << (*iter).getPlayerName() << " has " << (*iter).listSize() << " countries in their possesion." << "\nAnd those countries are as follows: "; (*iter).showList(); } }
Last edited by Matt Tacular; Jun 12th, 2007 at 9:49 am.
>I was thinking maybe an array of arrays
You were thinking correctly. Something like this perhaps?
The only problem here is that each sub-array has to have the same number of cells (5 in the previous code). So if you want a ragged array you either need to do some dynamic allocation (which I don't recommend just yet) or pad the shorter arrays with a sentinel value like -1.
You were thinking correctly. Something like this perhaps?
C++ Syntax (Toggle Plain Text)
#include <iostream> #include <ios> #include <limits> int main() { int a[][5] = { {1,2,3,4,5}, {5,4,3,2,1}, }; int index; std::cout<<"Enter 1 for ascending or 2 for descending: "; while ( !( std::cin>> index ) || !( index == 1 || index == 2 ) ) { std::cerr<<"Invalid input\n"; std::cin.clear(); std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' ); std::cout<<"Enter 1 for ascending or 2 for descending: "; } for ( int i = 0; i < 5; i++ ) std::cout<< a[index - 1][i] <<' '; std::cout<<'\n'; }
I'm here to prove you wrong.
what about doing it with a struct? this way every array is independent from the other, so you can create an array of structs...
now, what i would find complicated is instructing the structs the size of the array of ints... maybe creating an int variable in the struct that indicates the size of the array...
now, what i would find complicated is instructing the structs the size of the array of ints... maybe creating an int variable in the struct that indicates the size of the array...
-->sometimes i wanna take my toaster in a bath<-- >Is there a way I can do an actual array of arrays? Not a multidimensional one.
There's no such thing as a multidimensional array in C++. It's always an array of arrays. What you want is a ragged array, and the only way to do it is to manually simulate the arrays:
That's a lot harder and a lot easier to screw up. Alternatively, and this is your best option, use a vector of vectors:
There's no such thing as a multidimensional array in C++. It's always an array of arrays. What you want is a ragged array, and the only way to do it is to manually simulate the arrays:
C++ Syntax (Toggle Plain Text)
#include <iostream> #include <ios> #include <limits> int main() { int **a = new int*[2]; a[0] = new int[5]; a[1] = new int[3]; for ( int i = 0; i < 5; i++ ) a[0][i] = i + 1; for ( int i = 0; i < 3; i++ ) a[1][i] = 3 - i; int index; std::cout<<"Enter 1 for ascending or 2 for descending: "; while ( !( std::cin>> index ) || !( index == 1 || index == 2 ) ) { std::cerr<<"Invalid input\n"; std::cin.clear(); std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' ); std::cout<<"Enter 1 for ascending or 2 for descending: "; } int limit = 5; if ( index != 1 ) limit = 3; for ( int i = 0; i < limit; i++ ) std::cout<< a[index - 1][i] <<' '; std::cout<<'\n'; delete[] a[1]; delete[] a[0]; delete[] a; }
C++ Syntax (Toggle Plain Text)
#include <iostream> #include <ios> #include <limits> #include <vector> int main() { std::vector< std::vector<int> > v; v.push_back ( std::vector<int> ( 5 ) ); v.push_back ( std::vector<int> ( 3 ) ); for ( int i = 0; i < 5; i++ ) v[0][i] = i + 1; for ( int i = 0; i < 3; i++ ) v[1][i] = 3 - i; std::vector<int>::size_type index; std::cout<<"Enter 1 for ascending or 2 for descending: "; while ( !( std::cin>> index ) || !( index == 1 || index == 2 ) ) { std::cerr<<"Invalid input\n"; std::cin.clear(); std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' ); std::cout<<"Enter 1 for ascending or 2 for descending: "; } for ( std::vector<int>::size_type i = 0; i < v[index - 1].size(); i++ ) std::cout<< v[index - 1][i] <<' '; std::cout<<'\n'; }
I'm here to prove you wrong.
the problem is that in arrays of arrays all arrays have the same length, meaning the same quantity of elements, in this case, ints...
that's why i proposed the idea of using a struct with an int and an array of ints, where the int specifies the length of the array...
that's why i proposed the idea of using a struct with an int and an array of ints, where the int specifies the length of the array...
-->sometimes i wanna take my toaster in a bath<-- >that's why i proposed the idea of using a struct with an int and an array
>of ints, where the int specifies the length of the array...
And that's different from a ragged array, how? You still have to dynamically allocate the memory for each instance of the structure. The only real benefit to an array of structures is you can easily store the size of each array. And of course, it's still inferior to using a vector of vectors.
>of ints, where the int specifies the length of the array...
And that's different from a ragged array, how? You still have to dynamically allocate the memory for each instance of the structure. The only real benefit to an array of structures is you can easily store the size of each array. And of course, it's still inferior to using a vector of vectors.
I'm here to prove you wrong.
![]() |
Similar Threads
- Highest and Lowest (C++)
- New Programmer (aspiring) (C++)
- Memory reallocation (C)
- Dynamic Array of Structures, Loop problem! (C++)
- encapsulating an array in a class? (C#)
- Why Data Structures???...QUESTIONS INSIDE (C++)
Other Threads in the C++ Forum
- Previous Thread: convert char* to double
- Next Thread: processing/modifying a string
| Thread Tools | Search this Thread |
api array arrays beginner binary bitmap c++ c/c++ calculator char class classes code coding compile compiler console conversion convert count data database delete desktop developer directshow dll download dynamic email encryption error file forms fstream function functions game getline givemetehcodez google graph gui homeworkhelper iamthwee ifstream input int integer java lib linkedlist linker linux loop looping loops map math matrix memory multiple news node number output parameter pointer problem program programming project proxy python read recursion recursive return string strings struct temperature template templates test text text-file tree unix url variable vector video visualstudio win32 windows winsock word wordfrequency wxwidgets






