I'm trying to fill 2D vector in C++ with characters, but when I run this code it ends with one line characters (*..).
How can I fill 2D vector like this:
*.*
.**
#include <iostream>
#include <vector>
int main()
{
std::vector<std::vector<char> > vec2D;
std::vector<char> rowV;
unsigned int row=2;
unsigned int col=3;
char c;
unsigned int temp=0;
while(temp!=col)
{
while(rowV.size()!=row)
{
std::cin>>c;
rowV.push_back(c);
}
vec2D.push_back(rowV);
++temp;
}
return 0;
}
You should clear rowV after each insertion, otherwise it will be full and no other characters will be added. Also, row should be swapped by col and vice-versa, otherwise you will get a 3x2 (and not 2x3) 2D vector.
while(temp!=row)
{
while(rowV.size()!=col)
{
std::cin>>c;
rowV.push_back(c);
}
vec2D.push_back(rowV);
rowV.clear(); // clear after inserting
++temp;
}
It helps to know what [pushing back a 2DVector with an empty 1D vector] looks like.
See the example below.
#include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>
using namespace std;
//-v-----A FUNCTION TO PRINT 2D VECTORS
template<typename T> //We don't know what type the elements are yet, so we use a template
void printVec2D(vector<vector<T>> a) // a is the name of our input 2Dvector of type (T)
{
for (int i = 0; i < a.size(); i++) {// a.size() will equal the number of rows (i suppose rows/columns can depend on how you look at it)
for (int j = 0; j < a[i].size(); j++) {// a[i].size() is the size of the i'th row (which equals the number of columns, foro a square array)
std::cout << a[i][j] << "\t";
}
std::cout << "\n";
}
return;
}
//-^--------
int main()
{
int X = 3; int Y = 3;
int VectorAsArray[3][3] = {{1,2,3},
{14,15,16},
{107,108,109}};
vector<vector<int>> T;
for (int i = 0; i < X; i++)
{
T.push_back({});// We insert a blank row until there are X rows
for (int j = 0; j < Y; j++)
{
T[i].push_back(VectorAsArray[i][j]); //Within the j'th row, we insert the element corresponding to the i'th column
}
}
printVec2D(T);
//system("pause"); //<- I know that this command works on Windows, but unsure otherwise( it is just a way to pause the program)
return 0;
}
Related
So, I need to make a function that is going to return the chromatic number of a graph. The graph is given through an adjecency matrix that the function finds using a file name. I have a function that should in theory work and which the compiler is throwing no issues for, yet when I run it, it simply prints out an empty line and ends the program.
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int Find_Chromatic_Number (vector <vector <int>> matg, int matc[], int n) {
if (n == 0) {
return 0;
}
int result, i, j;
result = 0;
for (i = 0; i < n; i++) {
for (j = i; j < n; j++) {
if (matg[i][j] == 1) {
if (matc[i] == matc[j]) {
matc[j]++;
}
}
}
}
for (i = 0; i < n; i++) {
if (result < matc[i]) {
result = matc[i];
}
}
return result;
}
int main() {
string file;
int n, i, j, m;
cout << "unesite ime datoteke: " << endl;
cin >> file;
ifstream reader;
reader.open(file.c_str());
reader >> n;
vector<vector<int>> matg(n, vector<int>(0));
int matc[n];
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
reader >> matg[i][j];
}
matc[i] = 1;
}
int result = Find_Chromatic_Number(matg, matc, n);
cout << result << endl;
return 0;
}
The program is supposed to use an freader to convert the file into a 2D vector which represents the adjecency matrix (matg). I also made an array (matc) which represents the value of each vertice, with different numbers corresponding to different colors.
The function should go through the vector and every time there is an edge between two vertices it should check if their color value in matc is the same. If it is, it ups the second vale (j) by one. After the function has passed through the vector, the matc array should contain n different number with the highest number being the chromatic number I am looking for.
I hope I have explained enough of what I am trying to accomplish, if not just ask and I will add any further explanations.
Try to make it like that.
Don't choose a size for your vector
vector<vector<int> > matg;
And instead of using reader >> matg[i][j];
use:
int tmp;
reader >> tmp;
matg[i].push_back(tmp);
I am trying to convert a 2D Vectors of randomly generated chars to int. For example, if the chars are 'abc' then I want my int vector to be '97,98,99' etc.
I tried looking on here and for the most part, people are asking about char to sting, string to char, etc.
This is what I have so far.
#include <vector>
#include <cstdlib>
#include <string>
#include <iostream>
using namespace std;
int main()
{
vector<vector<char> > vec(100, vector<char>(10));
vector<vector<int> > intVec(100, vector<int>(10));
srand(time(NULL));
int intAscii = 0;
// Fill 2D vector with random chars
for(int i = 0; i < 1; i++)
{
rand_num = (rand() % 8 + 3);
for(int j = 0; j < rand_num; j++)
{
//logic here... randomly gen a char and place it in the same position, but this time in the int vector as an int.
vec.at(i).push_back((rand() % 26 + 97));
intAscii = int(vec.at(i).at(j));
intVec.at(i).push_back(intAscii);
}
// Print Contents & print out the int vector.
for(int i = 0; i < vec.size(); i++)
{
for(int j = 0; j < vec.at(i).size(); j++)
{
cout << vec.at(i).at(j);
cout << intVec.at(i).at(j);
}
}
}
The problem that I am running into is that when it prints out both vectors, chars is fine, for int I am getting a whole bunch of zeros. Which doesn't seem right because the int(vec.at(i).at(j)) works i.e if char vector was a then the int vector would be 97 and so on.
At this point, my guess is that the syntax for the int vector might be wrong.
You may try this:
intAscii = (int)vec.at(i).at(j);
In addition, to access the elements it could be better to use indices instead of push_back, like:
intVec.at(i).at(j) = intAscii;
This should work because you already allocate memory for your vector at the very beginning.
I am making a program to identify whether a 5 card ( user input ) array is a certain hand value. Pair, two pair, three of a kind, straight, full house, four of a kind ( all card values are ranked 2-9, no face cards, no suit ). I am trying to do this without sorting the array. I am currently using this to look through the array and identify if two elements are equal to each other
bool pair(const int array[])
{
for (int i = 0; i < array; i++)
{
if (array[i]==aray[i+1])
{
return true;
}
else
return false;
}
Does this section of code only evaluate whether the first two elements are the same, or will it return true if any two elements are the same? I.E if the hand entered were 2,3,2,4,5 would this return false, where 2,2,3,4,5 would return true? If so, how do I see if any two elements are equal, regardless of order, without sorting the array?
edit: please forgive the typos, I'm leaving the original post intact, so as not to create confusion.
I was not trying to compile the code, for the record.
It will do neither:
i < array will not work, array is an array not an int. You need something like int arraySize as a second argument to the function.
Even if you fix that then this; array[i]==aray[i+1] will cause undefined behaviour because you will access 1 past the end of the array. Use the for loop condition i < arraySize - 1.
If you fix both of those things then what you are checking is if 2 consecutive cards are equal which will only work if the array is sorted.
If you really cant sort the array (which would be so easy with std::sort) then you can do this:
const int NumCards = 9; // If this is a constant, this definition should occur somewhere.
bool hasPair(const int array[], const int arraySize) {
int possibleCards[NumCards] = {0}; // Initialize an array to represent the cards. Set
// the array elements to 0.
// Iterate over all of the cards in your hand.
for (int i = 0; i < arraySize; i++) {
int myCurrentCard = array[i]; // Get the current card number.
// Increment it in the array.
possibleCards[myCurrentCard] = possibleCards[myCurrentCard] + 1;
// Or the equivalent to the above in a single line.
possibleCards[array[i]]++; // Increment the card so that you
// count how many of each card is in your hand.
}
for (int i = 0; i < NumCards; ++i) {
// If you want to check for a pair or above.
if (possibleCards[i] >= 2) { return true; }
// If you want to check for exactly a pair.
if (possibleCards[i] == 2) { return true; }
}
return false;
}
This algorithm is actually called the Bucket Sort and is really still sorting the array, its just not doing it in place.
do you know the meaning of return keyword? return means reaching the end of function, so in your code if two adjacent values are equal it immediately exits the function; if you want to continue checking for other equality possibilities then don't use return but you can store indexes of equal values in an array
#include <iostream>
using namespace std;
int* CheckForPairs(int[], int, int&);
int main()
{
int array[ ]= {2, 5, 5, 7, 7};
int nPairsFound = 0;
int* ptrPairs = CheckForPairs(array, 5, nPairsFound);
for(int i(0); i < nPairsFound; i++)
{
cout << ptrPairs[i] << endl;
}
if(ptrPairs)
{
delete[] ptrPairs;
ptrPairs = NULL;
}
return 0;
}
int* CheckForPairs(int array[] , int size, int& nPairsFound)
{
int *temp = NULL;
nPairsFound = 0;
int j = 0;
for(int i(0); i < size; i++)
{
if(array[i] == array[i + 1])
nPairsFound++;
}
temp = new int[nPairsFound];
for(int i(0); i < size; i++)
{
if(array[i] == array[i + 1])
{
temp[j] = i;
j++;
}
}
return temp;
}
You could use a std::unordered_set for a O(n) solution:
#include <unordered_set>
using namespace std;
bool hasMatchingElements(const int array[], int arraySize) {
unordered_set<int> seen;
for (int i = 0; i < arraySize; i++) {
int t = array[i];
if (seen.count(t)) {
return true;
} else {
seen.insert(t);
}
}
return false;
}
for (int i = 0; i < array; i++)
{
if (array[i]==aray[i+1])
{
return true;
}
else
return false;
This loop will only compare two adjacent values so the loop will return false for array[] = {2,3,2,4,5}.
You need a nested for loop:
#include <stdio.h>
#include <stdbool.h>
int main()
{
int unsortedArray[] = {2,3,2,4,5};
int size = 5;
for(int i=0;i<size-1;i++)
{ for(int j=i+1;j<size;j++)
{ if(unsortedArray[i]==unsortedArray[j])
{ printf("matching cards found\n");
return 0;
}
}
}
printf("matching cards not found\n");
return 0;
}
----EDIT------
Like Ben said, I should mention the function above will only find the first instance of 2 matching cards but it can't count how many cards match or if there are different cards matching. You could do something like below to count all the number of matching cards in the unsortedArray and save those values into a separate array. It's messier than the implementation above:
#include <iostream>
#include <stdio.h>
#include <stdbool.h>
#defin NUM_CARDS 52;
using namespace std;
int main()
{
int T;
cin>>T;
while(T--)
{
int N,i,j;
cin>>N;
int unsortedArray[N];
for(int i=0;i<N;i++)
cin>>unsortedArray[i];
int count[NUM_CARDS]={0};
int cnt = 0;
for( i=0;i<N-1;i++)
{
for( j=i+1;j<N;j++)
{ if(unsortedArray[i]==-1)
break;
if(unsortedArray[i]==unsortedArray[j])
{
unsortedArray[j]=-1;
cnt++;
}
}
if(unsortedArray[i]!=-1)
{
count[unsortedArray[i]]=cnt; //in case you need to store the number of each cards to
// determine the poker hand.
if(cnt==1)
cout<<" 2 matching cards of "<<unsortedArray[i]<<" was found"<<endl;
else if(cnt>=2)
cout<<" more than 2 matching cards of "<<unsortedArray[i]<<" was found"<<endl;
else
cout<<" no matching cards of "<<unsortedArray[i]<<" was found"<<endl;
cnt = 0;
}
}
I have a bit of a problem, I am writing a program to ask the user to enter numbers for a Sudoku grid, and then store them in a 2-d array. I know how to print out the array to show the Sudoku grid, But I am having trouble getting the array elements set to the numbers that the user enters, can anyone help?
This is all that I have, which I know is not much but I have only ever done this with 1-d arrays before.
Code:
#include <iostream>
using namespace std;
void fillGrid1(int grid1, int sizeOfArray) {
for(int x = 0; x < sizeOfArray; x++) {
grid1[x][9] = x;
}
}
int main()
{
int grid1[9][9];
fillGrid1(grid1, 9);
for(int row = 0; row < 9; row++) {
for(int column = 0; column < 9; column++) {
cout << grid1[row][column] << " ";
}
cout << endl;
}
}
Here you have two functions, one to interactively fill the hole sudoku by getting the user input. The other for printing the sudoku. With the little information you gave it's what I think you seek:
#include <iostream>
#include <stdio.h>
#include<stdlib.h>
using namespace std;
void interactiveSudokuFill(int grid1[9][9]){
for(int y=0;y<9;y++){
for(int x=0;x<9;x++){
string theString;
cout<<"Write the value to prace in Sudoku["<<y<<"]["<<x<<"] :"<<endl;
std::getline(cin,theString);
int nr=atoi(theString.c_str());
grid1[y][x]=nr;
}
}
}
void printSudoku(int grid[9][9]){
for(int y=0;y<9;y++){
for(int x=0;x<9;x++){
cout<<"["<<grid[y][x]<<"]";
}
cout<<endl;
}
}
int main()
{
int grid1[9][9];
interactiveSudokuFill(grid1);
printSudoku(grid1);
}
There are other more safe/elegant ways of doing this(for example user input should have been checked before delievering it to atoi()), but this way is the simpler I can think of.
Firstly, you're taking in an int where you expect an array:
void fillGrid1(int grid1, int sizeOfArray)
// ^^^^^^^^^
This should be something of the form,
void fillGrid1(int grid1[9][9], int sizeOfArray)
Next is that you should use a nested loop to access the elements of the multidimensional array:
void fillGrid1(int grid1[9][9], int sizeOfArray)
{
for (int i = 0; i < sizeOfArray; ++i)
{
for (int k = 0; k < sizeOfArray; ++k)
{
grid1[i][k] = x; // shouldn't x be the number the user entered?
}
}
}
You should also zero-fill your array:
int grid1[9][9] = {0};
I have this array:
array[0] = 18;
array[1] = -10;
array[2] = 2;
array[3] = 4;
array[4] = 6;
array[5] = -12;
array[6] = -8;
array[7] = -6;
array[8] = 4;
array[9] = 13;
how do I sort the array in asc/desc mode in C++?
To sort an array in ascending, use:
#include <algorithm>
int main()
{
// ...
std::sort(array, array+n); // where n is the number of elements you want to sort
}
To sort it in descending, use
#include <algorithm>
#include <functional>
int main()
{
// ...
std::sort(array, array+n, std::greater<int>());
}
You can pass custom comparison functor to the std::sort function.
Well first I'm hoping your array assignment was just an error when posting but all your numbers are being assigned to the same memory location. There's nothing to sort.
After that, you can use the sort() function. The example linked shows an easy method for using it. Note that there is a third parameter that's not being used that will specify how to compare the elements. By default if you don't specify the parameter it uses 'less-than' so you get an ascending order sort. Change this to specify 'greater-than' comparator to get a descending order sort.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main (int argc, char *argv[])
{
int num[10]={18,-10,2,4,6,-12,-8,-6,13,-1};
int temp;
cout << "Ascending Sort : \n\n";
for(int i=0; i<=10; i++)
{
for(int j=i+1; j<=10; j++)
{
if(num[i]>num[j])
{
temp=num[i];
num[i]=num[j];
num[j]=temp;
}
}
cout << num[i] << "\n";
}
cout << "\nDescending Sort : \n\n";
for(int i=0; i<=10; i++)
{
for(int j=i+1; j<=10; j++)
{
if(num[i]<num[j])
{
temp=num[j];
num[j]=num[i];
num[i]=temp;
}
}
cout << num[i] << "\n";
}
return 0;
}
Generally, you can just swap the two variables in
http://www.cplusplus.com/reference/algorithm/sort/
Change
bool myfunction (int i,int j) { return (i<j); }
to
bool myfunction (int i,int j) { return (j<i); }
you can rename it to something else so that you have two comparison functions to use when the result needs to be ascending or descending.
If the function body has complicated expressions and involves i and j multiple times, then it is easier to swap the i and j in the parameter list instead of every i and j in the body:
bool myfunction (int j,int i) { return (i<j); }
The same goes for
http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/