I am not able to use vector header file - visual-studio-2010

I want to use vector header file but I guess there is an error in it. I have attached the image file containing the error. When ever I run this code I get the error shown in the image. Please tell me how to resolve it.
#include <iostream>
#include <conio.h>
#include <vector>
using namespace std;
int main()
{
vector<vector<int>> rmat;
vector<int> r = { 1, 2, 3, 4, 5 };
for (int i = 0; i < 3; i++)
for (int j = 0; j < 5; j++)
{
rmat[i][j] = r[j];
}
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 5; j++)
cout << rmat[i][j] << "\t";
cout << "\n";
}
_getch();
return 0;
}

Read the error message:
vector subscript out of range
You have created an empty vector,
vector<vector<int>> rmat;
and then access its nonexisting elements,
rmat[i][j] = r[j];
which results in this undefined behaviour which in you case resulted in a helpful exception being thrown.
Grab a good book on C++ and learn the basics first.

Related

How to use unique pointers to create matrix?

I have to create a matrix using unique poiters that permit operations: Matrix a,b; Matrix c(b) and Matrix d=a;
So far I did the simple implementing of a matrix
class Matrix
{
public:vector<vector<int>> data;
Matrix() {}
Matrix(vector<vector<int>> matrix)
{
this->data=matrix;
}
Matrix (const Matrix& m2)
{
this->data=m2.data;
}
Matrix& operator= (const Matrix &m2)
{
this->data = m2.data;
return *this;
}
}
It's first time for me facing unique_ptr vectors, I found a plenty of informations about unique_ptr vectors creating arrays, but not much for matrix, it's so unclear.
How can I use unique_ptr vectors(I must use them) instread of simple vector?
Any help is welcome, thank you!
Try this for init matrix only with std::unique_ptr [1]:
const int rowCount = 3;
const int clmnCount = 6;
std::unique_ptr<std::unique_ptr<int[]>[]> matrix(new std::unique_ptr<int[]>[rowCount]());
// or
// auto matrix = new std::unique_ptr<int[]>[rowCount]();
for (int i = 0; i < rowCount; i++)
matrix[i] = std::make_unique<int[]>(clmnCount);
Example of use [1]:
#include <iostream>
#include <iomanip>
#include <memory>
int main() {
const int rowCount = 3;
const int clmnCount = 6;
std::unique_ptr<std::unique_ptr<int[]>[]> matrix(new std::unique_ptr<int[]>[rowCount]());
for (int i = 0; i < rowCount; i++)
{
matrix[i] = std::make_unique<int[]>(clmnCount);
for (int j = 0; j < clmnCount; j++) {
matrix[i][j] = j;
std::cout << std::setw(3) << matrix[i][j];
}
std::cout << std::endl;
}
}
Or if u want use std::vector of std::unique_ptr try this [2]:
const int rowCount = 3;
const int clmnCount = 6;
std::vector<std::unique_ptr<int[]>> matrix;
for (int i = 0; i < rowCount; i++)
matrix.push_back(std::make_unique<int[]>(clmnCount));
Example of use [2]:
#include <iostream>
#include <iomanip>
#include <memory>
#include <vector>
int main() {
const int rowCount = 3;
const int clmnCount = 6;
std::vector<std::unique_ptr<int[]>> matrix;
for (int i = 0; i < rowCount; i++)
{
matrix.push_back(std::make_unique<int[]>(clmnCount));
for (int j = 0; j < clmnCount; j++) {
matrix[i][j] = j;
std::cout << std::setw(3) << matrix[i][j];
}
std::cout << std::endl;
}
}

Value of sum from thrust::reduce not correct

I have been trying to implement some code requiring to call reduce on thrust::device_ptr, and the results are not consistent with CPU implementation while dealing with large values. I have to deal with large values. So is there a way around:
My code:
#include <cuda_runtime_api.h>
#include <stdio.h>
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <iostream>
#define NZ 412//
#define NX 402//
using namespace std;
using real =double;
void allocate_array_2d(real**& preal, const int dim1, const int dim2) {
// Contiguous allocation of 2D arrays
preal = new real * [dim1];
preal[0] = new real[dim1 * dim2];
for (int i = 1; i < dim1; i++) preal[i] = preal[i - 1] + dim2;
for (int i = 0; i < dim1; i++) {
for (int j = 0; j < dim2; j++) {
preal[i][j] = 0;
}
}
}
#define cudaCheckError(code) \
{ \
if ((code) != cudaSuccess) { \
fprintf(stderr, "Cuda failure %s:%d: '%s' \n", __FILE__, __LINE__, \
cudaGetErrorString(code)); \
} \
}
int main()
{
real** a;
std::cout.precision(30);
allocate_array_2d(a, NZ, NX);//input array
for (int i = 0; i < NZ; i++) {
for (int j = 0; j < NX; j++) {
a[i][j] = 2.14748e+09;
}
}
real* da;
cudaCheckError(cudaMalloc(&da, NZ * NX * sizeof(real)));
cudaCheckError(cudaMemcpy(da,a[0], NZ * NX * sizeof(real),cudaMemcpyHostToDevice));
///************************
//CUDA KERNELS ARE HERE
// REMOVED FOR CLEAR QUESTION
///*************************
real sum1=0;
thrust::device_ptr<real> dev_ptr = thrust::device_pointer_cast(da);
sum1 = thrust::reduce(dev_ptr, dev_ptr+NZ*NX, 0, thrust::plus<real>());
cout<<" \nsum gpu "<< sum1<<"\n";
real sum2=0;
////////CPU PART DOING SAME THING//////
for (int i = 0; i < NZ; i++) {
for (int j = 0; j < NX; j++) {
sum2 += a[i][j];
}
}
cout<<"\nsum cpu "<< sum2<<"\n";
if((sum2-sum1)<0.001)
std::cout << "\nSUCESS "<< "\n";
else
std::cout << "\nFailure & by "<<sum2-sum1<< "\n";
}
The compiler that I am using is nvcc and my graphics card is nvidia 1650 with compute capability 7.5.
According to the documentation, thrust expects the type for summation to be reflected in the init value:
sum1 = thrust::reduce(dev_ptr, dev_ptr+NZ*NX, 0, thrust::plus<real>());
^
The type of that constant you have is an integral type. If you change that to a double-precision constant:
sum1 = thrust::reduce(dev_ptr, dev_ptr+NZ*NX, 0.0, thrust::plus<real>());
you get matching results, between CPU and GPU, according to my testing. (You could alternatively cast your constant to real type: (real)0 and use that, and there are other ways to address this as well, such as dropping the use of the init value and the binary op.)

Finding maximum difference b/w index in an array, with constraint a[i]<=a[j] where i<j

Here is my code, showing the wrong answer on a few test cases, can anyone tell me where it's failing.
I am not able to figure it out even after multiple attempts.
#include <iostream>
using namespace std;
int main() {
//code
int t,n;
cin >> t;
while(t--)
{
cin >> n;
long long int a[n],max=0;
for(int i=0;i<n;i++)
cin >> a[i];
int i=0,j=n-1;
while(i<=j)
{
if(a[j]>=a[i]){
max=j-i; break;}
else if(a[j-1]>=a[i] || a[j]>=a[i+1])
{ max=j-i-1; break;}
else
i++;
j--;
}
cout << max<<"\n";
}
return 0;
}
There is a solution in O(n log n):
Create a vector of index = 0 1 2 ... n-1
Sort (in a stable way) the indices i, j such that a[i] < a[i]
Determine the max_index values
max_index[i]= max (index[j], j >= i)
This can be calculated in a recursive way O(n)
For each index[i], determine index_max[i+1] - ind[i]); and determine the max of them
The maximum we obtained is the value we are looking for.
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
int diff_max (const std::vector<long long int> &a) {
int n = a.size();
std::vector<int> index(n), index_max(n);
int dmax = 0;
std::iota (index.begin(), index.end(), 0);
std::stable_sort (index.begin(), index.end(), [&a] (int i, int j) {return a[i] < a[j];});
index_max[n-1] = index[n-1];
for (int i = n-2; i >= 0; --i) {
index_max[i] = std::max (index_max[i+1], index[i]);
}
for (int i = 0; i < n-1; ++i) {
dmax = std::max (dmax, index_max[i+1] - index[i]);
}
return dmax;
}
int main() {
int t, n;
std::cin >> t;
while(t--) {
std::cin >> n;
std::vector<long long int> a(n);
for (int i = 0; i < n; ++i)
std::cin >> a[i];
auto max = diff_max (a);
std::cout << max << "\n";
}
return 0;
}
One known case where the algorithm fails:
1
5
5 7 6 2 3
The output, in this case, is 0, but it should be 2.
If the first two if conditions are not satisfied then you are incrementing i, here you are only comparing i with j and j-1, but there can be some other value of k such that k < j-1 and (i,j) is the answer.

How do I read two matrices from two text files then multiply them?

I want to read two matrices from two separate text files and multiply them. The matrices are 3x3 and 3x1 respectively, but I want to write the code that works for up to 10x10 matrices multiplication (so 10x10 matrix times 10x10 matrix). Below is my code, please help me! What I'm trying to do is to use for loops for rows and columns to read the files.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
int i, j;
int A[10][10], B[10][10], C[10][10];
ifstream inFile1("matrix(1).txt");
ifstream inFile2("vector(1).txt");
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
inFile1 >> A[i][j];
inFile2 >> B[i][j];
}
}
while (!inFile1.eof()) {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
inFile1 >> A[i][j];
inFile2 >> B[i][j];
}
}
}
}

Getting potential memory errors I guess - "double free or corruption"

I get the error only with negative numbers while it works for all positive numbers. Not really sure what is wrong here. Any help/guidance much appreciated.
#include <vector>
#include <iostream>
#include <algorithm>
int insertionSort(std::vector<int> &array){
// Count the number of shifts needed to sort the array
int shifts = 0;
for(int i = 1; i < array.size(); i++){
if(array[i] < array[i - 1]){
int j = i;
while(array[i] < array[i - 1] && i >= 0){
shifts++;
std::swap(array[i], array[i - 1]);
i--;
}
i = j;
}
}
return shifts;
}
int main(){
std::vector<int> array = {-1, -2}; // This won't work
//std::vector<int> array = {1, 2}; // This works
int shifts = insertionSort(array);
std::cout << shifts;
return 0;
}

Resources