How to use vector acsess element through function - visual-c++

This code is made for the multiplication of two arrays given by the user
typedef vector<vector<int> > arr ;
void multiply (arr &arr1 ,arr &arr2 )
{
arr res ;
unsigned new_row = arr1.size() ;
unsigned new_col = arr2.at(0).size();
for(int i = 0 ; i < new_row ; i++)
{
vector <int> vec ;
res.push_back(vec ) ;
for(int j = 0 ; j<new_col ;j++)
{
int x = 0 ;
res.at(i).push_back(x);
for(unsigned k =0 ; k <arr2.size();k++)
{
res.at(i).at(j) += arr1.at(i).at(k)*arr2.at(k).at(j);
}
cout<< res.at(i).at(j) ;
}
}
}
int main()
{
unsigned rows_number1 = 0 , columns_number1 = 0 ;
arr arr1 ;
cout<<"MATRIX A "<<endl<<endl ;
cout << "The Rows : " ;
cin >> rows_number1 ;
cout << "The Columns :" ;
cin>> columns_number1 ;
for(int i = 0 ; i<rows_number1;i++)
{
vector<int> newr ;
arr1.push_back(newr);
for(int j = 0; j<columns_number1 ;j++)
{
int x ;
cout<<"The Member ("<<i+1<<","<<j+1 <<") :" ;
cin>>x ;
arr1.at(i).push_back(x);
}
}
unsigned rows_number2 = 0 , columns_number2 = 0 ;
arr arr2 ;
cout<<"MATRIX B "<<endl<<endl ;
cout << "The Rows : " ;
cin >> rows_number2 ;
cout << "The Columns :" ;
cin>> columns_number2 ;
for(int i = 0 ; i<rows_number2;i++)
{
vector<int> newr ;
arr1.push_back(newr);
for(int j = 0; j<columns_number2 ;j++)
{
int x ;
cout<<"The Member ("<<i+1<<","<<j+1 <<") :" ;
cin>>x ;
arr1.at(i).push_back(x);
}
}
system("cls");
if(columns_number1!=rows_number2)
{
cout<<"Error Multiplication Dimensions" <<endl ;
}
else
{
cout << "A * B ="<<endl;
multiply(arr1,arr2);
}
}
why there is an error and what is the other way ??
how i can improve the code to multiplicate two arrays
Edited : i tried with two 2*2 arrays using console input and output and this is my full code
The problem is out_of_range exception but i don't know why

When you mulitply to matrices, there are strict constraints on the input.
The number of columns of the first matrix must be the same as the number of rows of the second matrix.
When your matrix is represented by a std::vector<std::vector<int>>, you'll have to make sure that ALL the nested std::vectors are of the same size.
Also, don't assume that arr2 is non-empty. When it is empty, arr2.at(0) will thrown an exception.
Here's a more robust version of your function.
void multiply (arr &arr1 ,arr &arr2 )
{
arr res;
unsigned num_rows1 = arr1.size();
if ( num_rows1 == 0 )
{
// Can't do much.
// Return.
return res;
}
unsigned num_cols1 = arr1[0].size();
if ( num_cols1 == 0 )
{
// Can't do much.
// Return.
return res;
}
// Inner vector size check of arr1.
for(unsigned int i = 1 ; i < num_rows1 ; i++)
{
if ( num_cols1 != arr1[i].size() )
{
throw std::runtime_error("Bad input");
}
}
// Make sure the number of columns in arr1 is the same as
// number of rows in arr2.
unsigned num_rows2 = arr2.size();
if ( num_cols1 != num_rows2 )
{
throw std::runtime_error("Bad input");
}
unsigned num_cols2 = arr2[0].size();
if ( num_cols2 == 0 )
{
// Can't do much.
// Return.
return res;
}
// Inner vector size check of arr2.
for(unsigned int i = 1 ; i < num_rows2 ; i++)
{
if ( num_cols2 != arr2[i].size() )
{
throw std::runtime_error("Bad input");
}
}
// All inputs appear to be valid.
// Now, do the multiplication.
unsigned new_row = num_rows1;
unsigned new_col = num_cols2;
res.resize(num_rows1);
for(unsigned i = 0 ; i < new_row ; i++)
{
for(unsigned j = 0 ; j<new_col ;j++)
{
int x = 0 ;
res.at(i).push_back(x);
for(unsigned k =0 ; k < num_cols1; k++)
{
res.at(i).at(j) += arr1.at(i).at(k)*arr2.at(k).at(j);
}
cout<< res.at(i).at(j) ;
}
}
}

Related

Roman Numeral to Integers

I need help solving this issue, I am expecting a number to come out but get this error instead
Line 65: Char 5: error: conflicting types for 'main' int main(int argc, char *argv[]) { ^ Line 47: Char 5: note: previous definition is here int main() ^ 1 error generated.
here is some of my code
class Solution {
public:
int value(char r){
if (r == 'I')
return 1;
if (r == 'V')
return 5;
if (r == 'X')
return 10;
if (r == 'L')
return 50;
if (r == 'C')
return 100;
if (r == 'D')
return 500;
if (r == 'M')
return 1000;
return -1;
}
int romanToInt(string& s) {
int ret = 0;
for (int i = 0; i < s.length(); i++) {
int s1 = value(s[i]);
if (i + 1 < s.length()) {
int s2 = value(s[i + 1]);
if (s1 >= s2) {
ret = ret + s1;
}
else {
ret = ret + s2 - s1;
i++;
}
}
else {
ret = ret + s1;
}
}
return ret;
}
};
int main()
{
Solution m;
string str = "III";
cout << "Integer form of Roman Numeral is " << m.romanToInt(str) << endl;
return 0;
}
I am trying to use a pointer array where it reads the line letter by letter and recognizing the value of the letter in the function value(), I think I understand that my main needs to be formatted differently in order to do this task but I am a little stuck on how to do so.
You have probably defined int main twice. Considering you have an error on line 65 while your code is less than 60 lines long I would assume there is more code than what was copied here.

CS50 pset4 filter reflection

#include "helpers.h"
#include <math.h>
// Convert image to grayscale
void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
for ( int h=0 ; h<height ; h++)
{
for (int w=0 ; w<width ; w++)
{
int i = image[h][w].rgbtBlue + image[h][w].rgbtGreen + image[h][w].rgbtRed ;
float j = i/3 ;
int n = round(j) ;
image[h][w].rgbtBlue = n ;
image[h][w].rgbtGreen = n ;
image[h][w].rgbtRed = n ;
}
}
return;
}
// Convert image to sepia
void sepia(int height, int width, RGBTRIPLE image[height][width])
{
for ( int h=0 ; h<height ; h++)
{
for (int w=0 ; w<width ; w++)
{
float sr = .393 * image[h][w].rgbtRed + .769 * image[h][w].rgbtGreen + .189 * image[h][w].rgbtBlue ;
float sg = .349 * image[h][w].rgbtRed + .686 * image[h][w].rgbtGreen + .168 * image[h][w].rgbtBlue ;
float sb = .272 * image[h][w].rgbtRed + .534 * image[h][w].rgbtGreen + .131 * image[h][w].rgbtBlue ;
int SR = round(sr);
int SG = round(sg);
int SB = round(sb);
if ( SR>255)
{
SR = 255 ;
}
if (SG>255)
{
SG = 255 ;
}
if (SB>255)
{
SB = 255 ;
}
image[h][w].rgbtBlue = SB ;
image[h][w].rgbtGreen = SG ;
image[h][w].rgbtRed = SR ;
}
}
return;
}
// Reflect image horizontally
void swap (int *a , int *b) ;
void reflect(int height, int width, RGBTRIPLE image[height][width])
{
for (int h=0 ; h<height ; h++)
{
for (int w=0 ; w<width/2 ; w++)
{
for (int p=width-1 ; p>=round(width/2) ; p--)
{
int blue = image[h][w].rgbtBlue ;
int B = image[h][p].rgbtBlue ;
swap(&blue , &B);
int g = image[h][w].rgbtGreen ;
int G = image[h][p].rgbtGreen ;
swap(&g , &G);
int r = image[h][w].rgbtRed ;
int R = image[h][p].rgbtRed ;
swap(&r , &R );
}
}
}
return;
}
void swap (int *a , int *b)
{
int tmp = *a ;
*a = *b ;
*b = tmp ;
}
// Blur image
void blur(int height, int width, RGBTRIPLE image[height][width])
{
return;
}
I have written this code for helper.c. It compiles ok and works for grayscale and sepia but fails to reflect the image.
I am stuck in it . Please tell me where have i made the mistake.
// Reflect image horizontally
void reflect(int height, int width, RGBTRIPLE image[height][width])
{
int tmp[3];
for (int h = 0; h < height; h++)
{
for (int w = 0; w < width / 2; w++)
{
// Place the first pixel in a temporary variable
tmp[0] = image[h][w].rgbtRed;
tmp[1] = image[h][w].rgbtGreen;
tmp[2] = image[h][w].rgbtBlue;
// Place the opposite pixel one into the first pixel
image[h][w].rgbtRed = image[h][width - w - 1].rgbtRed;
image[h][w].rgbtGreen = image[h][width - w - 1].rgbtGreen;
image[h][w].rgbtBlue = image[h][width - w - 1].rgbtBlue;
// From the temporary variable extract the first pixel and place it into
the opposite pixel
image[h][width - w - 1].rgbtRed = tmp[0];
image[h][width - w - 1].rgbtGreen = tmp[1];
image[h][width - w - 1].rgbtBlue = tmp[2];
}
}
return;
}
You don't need the third for loop
for (int p=width-1 ; p>=round(width/2) ; p--)
instead, you can assign the opposite pixel inside the second loop as follows:
for (int w=0 ; w<width/2 ; w++)
{
p = width - w - 1;
...
}

Stack around the variable A (array) or n (size of the array) was corrupted

This program checks distinctness in an array. (no repeated values in an array I.e if 1 2 3 3 4 is an array it is not distinct). this code Won't compile although (I believe that) index of array did not go out of range in for loop.
theRun-Time Check Failure says stack around variable 'n' was corrupted when I enter n =12. BUT says stack around variable 'A' was corrupted when I enter n = 10. with exactly the same variables entered in the array in the second step. (the error shows up after entering the fourth integer)
#include <iostream>
using namespace std;
int main()
{
int n;
int A[] = {0};
int integer;
cout<<"Enter the size of the array\n";
cin>>n;
cout<<"enter "<<n<<" integers\n";
for (int i = 0 ; i < n ; i++)
{
cin>>A[i];
}
for (int i = 0 ; i < n ; i++)
{
for (int j = 0 ; j < n - i; j++)
{
if(A[j+1] > A[j])
{
int temp;
temp = A[j];
A[j+1] = A[j];
A[j+1] = temp;
}
}
}
for (int i = 0 ; i < n; i++)
{
if (A[i] - A[i+1] ==0 ){
cout<<"\nThe Array Is Not Distinct !\n";
break;
}
else
{
cout<<"\nThe Array Is Distinct !\n";
}
}
system("pause");
return 0;
}

How to grow 2d dynamically allocated string array in C++11 ?

So, I have been doing this question :
Q. Write a program that lets users keep track of the last time they talked to each of their friends. Users should be able to add new friends (as many as they want!) and store the number of days ago that they last talked to each friend. Let users update this value as well.
I have created pointer to pointer user_friends to store the 2D string array for names of friends and no. of days since last talked. It's a 3x2 array initially for 3 friends. The 2 columns store friend's name and no. of days ( both in string type pointer array ).
My main has this :
int tsize = 3;
string **user_friends = new string*[tsize];
for ( int i = 0; i < tsize; i++ )
{
user_friends[i] = new string[2];
}
Here is the addFriends function to add friends in array.
void addFriends( string **user_f , int tsize )
{
static int next_friend = 0;
int index = 0;
string days;
if ( next_friend >= tsize )
{
cout << "\nGrowing array now...";
user_f = growArray ( user_f, tsize );
}
cout << "\n\nEnter index : ";
cin >> index;
cin.ignore();
cout << "\nEnter friend's name : ";
getline( cin, user_f[index][0] );
cout << "\nEnter days since last talked with this friend : ";
getline (cin, days);
user_f[index][1] = days;
next_friend++;
}
Then there is this growArray function to expand the memory allocated to string array :
string **growArray ( string **ptr, int cur_size )
{
string **new_ptr = new string*[ cur_size*2 ];
for ( int i = 0; i < cur_size; ++i )
{
new_ptr[i] = new string[2];
}
for( int i = 0; i < cur_size; ++i )
{
new_ptr[i] = ptr[i];
}
for ( int i = 0; i < cur_size; ++i )
{
for ( int j = 0; j < 2; ++j)
{
new_ptr[i][j] = ptr[i][j];
}
}
for ( int i = 0; i < cur_size; ++i )
{
delete ptr[i];
}
delete[] ptr;
return new_ptr;
}
Then this display function to print the array.
void displayFriends( string **user_f, int tsize )
{
for ( int i = 0; i < tsize; ++i )
{
for( int j = 0; j < 2; ++j )
{
cout << user_f[i][j] << "\t";
}
cout << endl;
}
}
Now, when I have entered upto 3 friends details, the program runs fine.
When I start to enter the details of friend 4 ( i.e. When I type in index as 3 ) the program crashes. Is there any problem with the growArray function ?
Also, is the display function alright ?
In the growArray function the first for loop should iterate from 0 to 2 * cur_size instead of 0 to cur_size.
for(int i = 0; i< 2 * cur_size; i++)
new_ptr[i] = new string[2]

how do i avoid using pointer variables and pointer-based pass-by-reference in this program?

how do i avoid using pointer variables and pointer-based pass-by-reference in this program? as my instructor said there is no need to use pointers. This is a the tortoise and the hare simulator , you will use number generation to develop a simulation of this memorable event.
#include <iostream>
using std::cout;
using std::endl;
#include <cstdlib>
using std::rand;
using std::srand;
#include <ctime>
using std::time;
#include <iomanip>
using std::setw;
const int RACE_END = 70;
// prototypes
void moveTortoise( int *const );
void moveHare( int *const );
void printCurrentPositions( const int *const, const int *const );
int main()
{
int tortoise = 1;
int hare = 1;
int timer = 0;
srand( time( 0 ) );
cout << "ON YOUR MARK, GET SET\nBANG !!!!"
<< "\nAND THEY'RE OFF !!!!\n";
// loop through the events
while ( tortoise != RACE_END && hare != RACE_END )
{
moveTortoise( &tortoise );
moveHare( &hare );
printCurrentPositions( &tortoise, &hare );
timer++;
} // end loop
if ( tortoise >= hare )
cout << "\nTORTOISE WINS!!! YAY!!!\n";
else
cout << "\nHare wins. Yuch.\n";
cout << "\nTIME ELAPSED = " << timer << " seconds" << "\n" << endl;
system("pause");
return 0; // indicates successful termination
} // end main
// progress for the tortoise
void moveTortoise( int * const turtlePtr )
{
int x = 1 + rand() % 10; // random number 1-10
if ( x >= 1 && x <= 5 ) // fast plod
*turtlePtr += 3;
else if ( x == 6 || x == 7 ) // slip
*turtlePtr -= 6;
else // slow plod
++( *turtlePtr );
if ( *turtlePtr < 1 )
*turtlePtr = 1;
else if ( *turtlePtr > RACE_END )
*turtlePtr = RACE_END;
} // end function moveTortoise
// progress for the hare
void moveHare( int * const rabbitPtr )
{
int y = 1 + rand() % 10; // random number 1-10
if ( y == 3 || y == 4 ) // big hop
*rabbitPtr += 9;
else if ( y == 5 ) // big slip
*rabbitPtr -= 12;
else if ( y >= 6 && y <= 8 ) // small hop
++( *rabbitPtr );
else if ( y > 8 ) // small slip
*rabbitPtr -= 2;
if ( *rabbitPtr < 1 )
*rabbitPtr = 1;
else if ( *rabbitPtr > RACE_END )
*rabbitPtr = RACE_END;
} // end function moveHare
// display new position
void printCurrentPositions( const int * const snapperPtr,
const int * const bunnyPtr )
{
if ( *bunnyPtr == *snapperPtr )
cout << setw( *bunnyPtr ) << "OUCH!!!";
else if ( *bunnyPtr < *snapperPtr )
cout << setw( *bunnyPtr ) << 'H'
<< setw( *snapperPtr - *bunnyPtr ) << 'T';
else
cout << setw( *snapperPtr ) << 'T'
<< setw( *bunnyPtr - *snapperPtr ) << 'H';
cout << '\n';
} // end function printCurrentPositions
In C++ you can use references instead of pointers. For example, instead of
void foo(int *x) {
*x = *x + 1;
}
int main() {
int a = 0;
foo(&a);
return 0;
}
you can pass x by reference, like so:
void foo(int &x) {
x = x + 1;
}
int main() {
int a = 0;
foo(a);
return 0;
}
Passing a reference is sort of like passing a pointer, except you don't need to dereference the pointer every time you want to access the value it points to.
You can google "C++ pass by reference" for more information, such as this tutorial: http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/
Alternatively, in your program, you could simply pass int arguments and return the new value:
int moveTortoise(int turtle) {
...
turtle = turtle + 3;
...
return turtle;
}
tortoise = moveTortoise(tortoise)
References& and pointers* are usefull when:
1. you deal with instances of complex classes that passing by reference is resource(CPU time & main memory) consuming operation;
2. when you want to change arguments what are passed(as any function in C++ can return only one value, opposit for ex. to python where multiply values can be returned, you can cope with that restriction by passing using & or *);
3. Other cases...
Built-in(atomic) types can be passed by value (which is you case) without decrease in efficiency.

Resources