Left rotating array by d elements in C++ using vectors - c++

The C++ function code I wrote:-
values of n=5(no. of elements in array) and d=4(no. of elements by which array is to left rotated)
vector<int> rotateLeft(int d, vector<int> arr)
{
int n=arr.size();
vector<int> temp;
for(int i=0;i<d;i++)
{ temp[i]=arr[i]; }
for(int j=d;j<n;j++)
{ arr[j-d]=arr[j]; }
for(int k=0;k<d;k++)
{ arr[n-d-k]=temp[k];
}
return arr;
}
input given arr[]= 1 2 3 4 5
output required arr[]=5 1 2 3 4

You get Segmentation fault for two reasons:
You have to resize temp to match arr before accessing the elements with the square brackets either with std::vector<int> temp(n); or calling temp.resize(n) afterwards.
You have made an indexing error which results in an access that is out of bounds: arr[n-d-k]=temp[k] should actually be arr[n-d+k]=temp[k]. In order to avoid this you might try using the .at(i) operator instead: It performs an out-of-bound check.
Try it here.
There is also a function in the standard library for that called std::rotate.
std::rotate(arr.begin(), arr.begin() + d, arr.end());
Try it here.
If I had to write my own version quickly I would actually do something like
template <typename T>
std::vector<T> rotateLeft(std::vector<T> const& vec, int const d) {
std::size_t const N = vec.size();
std::vector<T> temp;
temp.resize(N);
for (std::size_t i = 0; i < N; ++i) {
std::size_t const new_i = (N + i - d)%N;
temp.at(new_i) = vec.at(i);
}
return temp;
}
Try it here.

arr[n-d-k]=temp[k];
should have been
arr[n-d+k]=temp[k];

Related

Segmentation fault C++ Program

I want to write a program to construct a n*n matrix and fill it with 1 to n^2. but I‌ get a segmentation fault( core dumped).
I‌ have no clue why this happens. Any help will be appreciated.
int array[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
array[i][j] = t;
t++;
}
I want to write a program to construct a n*n matrix and fill it with 1 to n^2
You can either use a nested standard container or write your own user-defined class modelling a matrix data structure. Also note that there are plenty of linear algebra libraries providing well designed and tested matrix classes.
If you decide to implement one, this may a basic starting point
class Matrix
{
size_t rows_, cols_;
std::vector<int> m_; // Note that this is ONE vector
public:
Matrix() = default;
Matrix(size_t r, size_t c)
: rows_{r}, cols_{c}, m_(r * c)
{}
size_t n_rows() const noexcept {
return rows_;
}
size_t n_columns() const noexcept {
return cols_;
}
// I prefer to overload operator() for matrices, instead of operator[]. We need a little
// formula to calculate the 1D index, given the 2D indices.
auto operator() (size_t r, size_t c) const {
return m_[r * cols_ + c];
}
auto& operator() (size_t r, size_t c) {
return m_[r * cols_ + c];
}
auto begin() {
return m_.begin();
}
auto end() {
return m_.end();
}
// You may want the const version and cbegin(), cend(), too.
// ...
};
Having that, you can complete your task in a couple of ways
// Using a nested loop
Matrix a(n, n);
for (size_t i{}, k{}; i < a.n_rows(); ++i) {
for (size_t j{}; j < a.n_columns(); ++j) {
a(i, j) = ++k;
}
}
// Using std::iota from <numeric> header
Matrix b(n, n);
std::iota(b.begin(), b.end(), 1);
I‌ get a segmentation fault (core dumped). I‌ have no clue why this happens.
Those lines
int n;
cin >> n;
int array[n][n];
Declare a Variable Length Array, which is not a standard compliant container. Some compilers provide theese as an extension. In particular, gcc also has the following documentation (emphasis mine).
6.20 Arrays of Variable Length
Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits.
Note the use of the automatic term.
In the comments, you say that you are testing the program with a size of 2000, which is probably too big for your environment. See e.g. why is stack memory size so limited?.
Some problems to be solved in your code:
The variable length array (VLAs) are not a part of C++ standard. Thus, using syntax like:
int n = 10; // non-const value
int incorrect_array[n][n]; // invalid
The array size must be known to compile time.
Since the size of the array provided by you in the question is yet unclear, stack overflow may be another reason of the segfault in case you are overflowing the array size a gigantic number.
Revised edition of the same code:
#include <iostream>
#include <vector>
// Using this syntax just to avoid 'std::' prefix everywhere
// in this program.
using namespace std;
int main(void) {
// Initializing multidimensional vector which will work as an array
vector<vector<int>> multiDim;
int size;
int a = 1;
cout << "The NxN size: ";
cin >> size;
// Providing a size of the multi-dim array
multiDim.resize(size, vector<int>(size));
// Initializing 1 to n^2
for (int i{}; i < size; i++)
for (int j{}; j < size; j++)
multiDim[i][j] = a++;
// Uncomment the next lines 5 lines to see output preview
// for (const auto& it : multiDim) {
// for (const auto& subIt : it)
// cout << subIt << '\t';
// cout << endl;
// }
return 0;
}
The output would be:
The NxN size: 5
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
You can ask further in the comments if you have any confusion yet.

deleting duplicates from a sorted vector

26. Remove Duplicates from Sorted Array
Given a sorted array nums, remove the duplicates in-place such that
each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by
modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of
nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the returned length. Example
2:
Given `nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5, with the first five elements
of nums being modified to 0, 1, 2, 3, and 4 respectively.
It doesn't matter what values are set beyond the returned length.
Clarification:
Confused why the returned value is an integer but your answer is an
array?
Note that the input array is passed in by reference, which means
modification to the input array will be known to the caller as well.
Internally you can think of this:
// nums is passed in by
reference. (i.e., without making a copy) int len =
removeDuplicates(nums);
// any modification to nums in your function would be known by the
caller. // using the length returned by your function, it prints the
first len elements. for (int i = 0; i < len; i++) {
print(nums[i]); }
i am getting this runtime error while submitting it on leetcode it works fine on coding blocks but shows this error in leetcode compilor
Line 924: Char 9: runtime error: reference binding to null pointer of type 'int' (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/stl_vector.h:933:9
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int k=nums[0];
for(auto i=nums.begin()+1;i<nums.end();i++)
{
if(*i==k) nums.erase(i) , i--;
else k=*i;
}
return nums.size();
}
};
Can anybody help me in finding the cause of error?
Your code works just fine, missing one edge case (an empty nums):
if (nums.empty()) {
return 0;
}
Updated Code:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.empty()) {
return 0;
}
int k = nums[0];
for (auto i = nums.begin() + 1; i < nums.end(); i++) {
if (*i == k) {
nums.erase(i) , i--;
}
else {
k = *i;
}
}
return nums.size();
}
};
Maybe we could just write a simple loop using size(). This'd pass on LeetCode:
// Most of headers are already included;
// Can be removed;
#include <cstdint>
#include <vector>
// Start
static const struct Solution {
using SizeType = std::uint_fast16_t;
static const int removeDuplicates(
std::vector<int>& nums
) {
const SizeType len = std::size(nums);
SizeType count = 0;
for (SizeType i = 1; i < len; ++i) {
if (nums[i] == nums[i - 1]) {
++count;
} else {
nums[i - count] = nums[i];
}
}
return len - count;
}
};

How to define a two dimensional array during run time in Visual Studio C++ 11?

I am trying to compile ORBSLAM2 on Windows with Visual Studio 2015 vc14 x64 compiler. The project was originally developed for GNU GCC. I now have the following issue:
// Compute distances between them
const size_t N = vDescriptors.size();
float aDistances[N][N];
for(size_t i=0;i<N;i++) {
aDistances[i][i]=0;
for(size_t j=i+1;j<N;j++) {
int distij = ORBmatcher::DescriptorDistance(vDescriptors[i],vDescriptors[j]);
aDistances[i][j]=distij;
aDistances[j][i]=distij;
}
}
I get the this error while compiling:
C2131 expression did not evaluate to a constant
... on this line of code:
const size_t N = vDescriptors.size();
Subsequently the two dimensional array definition fails too (float Distances[N][N];).
What's the best way to solve this in Visual-C++ ?
UPDATE: Here's the complete function code:
void MapPoint::ComputeDistinctiveDescriptors() {
// Retrieve all observed descriptors
vector<cv::Mat> vDescriptors;
map<KeyFrame*,size_t> observations;
{
unique_lock<mutex> lock1(mMutexFeatures);
if(mbBad)
return;
observations=mObservations;
}
if(observations.empty())
return;
vDescriptors.reserve(observations.size());
for(map<KeyFrame*,size_t>::iterator mit=observations.begin(), mend=observations.end(); mit!=mend; mit++) {
KeyFrame* pKF = mit->first;
if(!pKF->isBad())
vDescriptors.push_back(pKF->mDescriptors.row(mit->second));
}
if(vDescriptors.empty())
return;
// Compute distances between them
const size_t N = vDescriptors.size();
float aDistances[N][N];
for(size_t i=0;i<N;i++) {
aDistances[i][i]=0;
for(size_t j=i+1;j<N;j++) {
int distij = ORBmatcher::DescriptorDistance(vDescriptors[i],vDescriptors[j]);
aDistances[i][j]=distij;
aDistances[j][i]=distij;
}
}
// Take the descriptor with least median distance to the rest
int BestMedian = INT_MAX;
int BestIdx = 0;
for(size_t i=0;i<N;i++) {
vector<int> vDists(aDistances[i], aDistances[i]+N);
sort(vDists.begin(),vDists.end());
int median = vDists[0.5*(N-1)];
if(median<BestMedian) {
BestMedian = median;
BestIdx = i;
}
}
{
unique_lock<mutex> lock(mMutexFeatures);
mDescriptor = vDescriptors[BestIdx].clone();
}
}
Your Problem
You tried to create a 2D array on the stack (this is not standard C++, even though it might work on some compilers). For this the size needs to be know at compile time, which is not the case as you call size() on an object which likely is not a constexpr.
QUICK FIX
A quick fix that works out of the box is to just allocate the memory on the heap (do not forget to delete array later on) by doing
float** aDistances = new float[N][N];
The deletion can be done in a function which looks like this
template <typename T>
void delete2DArray(T** ptr, size_t NumRows)
{
for (size_t i = 0; i < NumRows; i++)
{
delete[] ptr[i];
}
delete[] ptr;
}
FIX
You will haveto use dynamic memory allocation. For this you can try the following approach by adding a wrapper class around std::vector (this should be possible as you said the scope is very manageable)
template <typename T>
class Array2D
{
public:
Array2D(size_t numrows, size_t numcols) :
rows(numrows), columns(numcols), array2d(rows * columns)
{}
T& operator()(size_t row, size_t column)
{
return array2d[row * columns + column];
}
const T& operator()(size_t row, size_t column) const
{
return array2d[row * columns + column];
}
T* getRow(size_t row)
{
return &array2d[row * columns];
}
private:
size_t rows;
size_t columns;
std::vector<T> array2d;
};
Than you have to modify your code like this:
// Compute distances between them
const size_t N = vDescriptors.size();
Array2D<float> aDistances(N,N);
for (size_t i = 0; i < N; i++) {
aDistances(i,i) = 0;
for (size_t j = i + 1; j < N; j++) {
int distij = ORBmatcher::DescriptorDistance(vDescriptors[i], vDescriptors[j]);
aDistances(i,j) = distij ;
aDistances(j,i) = distij ;
}
}
As you can see the syntax to access elements has slightly changed [x][y] -> (x,y).
EDIT
As the OP has modified the question, I have noticed that the Distances is used a second time which needs attention as well. For this you will have to add a getColumn method (see above) to the Array2D class. Than you further have to modify
// Take the descriptor with least median distance to the rest
int BestMedian = INT_MAX;
int BestIdx = 0;
for(size_t i=0;i<N;i++) {
vector<int> vDists(aDistances.getRow()[i], aDistances.getRow()[i]+N);
sort(vDists.begin(),vDists.end());
int median = vDists[0.5*(N-1)];
if(median<BestMedian) {
BestMedian = median;
BestIdx = i;
}
}
NOTE: I am not perfectly sure if I got it right -- maybe you have to get a
columns instead of a rows (too late to think straight). If this is the case you should also change the memory layout of the Array2D class, i.e. sorting the elements differently in the underlaying 1D-Vector.

cannot use push_back to insert an integer to a 1D/2D vector

I am trying to write a function to extract a slice from a given matrix, where the input is 1D and the slice can be 1D or 2D.
I am trying to use the push_back function for this purpose but for some reasons the push_back does not work.
I receive an error in my line OutPut.push_back(DumyValue);
Can anyone help me why I am receiving this error?
Also, it would be appreciated if you can tell me how to solve this issue.
Also, if the first part becomes clear, can anyone tell me how I should use the push_back for inserting an integer in a specific location so I can use it for extracting a 2D slice?
If you remove the line OutPut.push_back(DumyValue); the code should work.
#include<iostream>
#include<vector>
using namespace std;
int MatrixSlice(vector<vector<int>> Input, int Row1, int Row2, int Col1, int Col2) {
//define the slice size, if it is iD or 2D
if (abs(Row1-Row2)>1 && abs(Col1-Col2)>1){
vector<vector<int>> OutPut;
}else{
vector<int> OutPut;
}
int i2;
int j2;
for (int i = Row1; i <= Row2; i++) {
i2=0;
for (int j = Col1; j <= Col2; j++) {
int DumyValue=Input[i][j];
OutPut.push_back(DumyValue);
i2++;
//cout << Input[i][j] << endl;
}
j2++;
}
return 0;
}
int main() {
//Define a matrix for test:
vector<vector<int>> Matrix2(4, vector<int>(5, 1));
int R = 4;
int C = 4;
vector<vector<int>> MatrixInput(R, vector<int>(C, 1));;
for (int i = 0; i < MatrixInput.size(); i++) {
for (int j = 0; j < MatrixInput[0].size(); j++) {
int temp;
temp = i^2+j^2;
MatrixInput[i][j] = temp;
}
}
MatrixSlice(MatrixInput, 0, 3, 1, 1);
printf("\n");
return 0;
}
Matrix slice has a couple problems:
It is impossible define a variable with two possible types and have both active in the same scope.
The return type of int makes little sense. The matrix is sliced up, but then what? It can't be handed back to the caller to do anything with it.
This can be fixed with a union, but yikes! The bookkeeping on that will be a Smurfing nightmare. Don't do it!
The next is to always use a vector of vectors, but I don't like that idea for a couple reasons I'll get into below.
Instead I pitch a simple wrapper object around a single vector. This is done for two reasons:
It preserves the ability to back a 1 dimensional matrix with a 1 dimensional container. If you have many rows of one column, all of the row data remains contiguous and cache friendly.
It tends to be much faster. The data of one vector is contiguous in memory and reaps the rewards of cache friendliness. A vector of vectors is basically a list of pointers to arrays of data, sending the poor CPU on an odyssey of pointer-chasing through memory to find the columns. If the columns are short, this can really, really hurt performance.
Here we go:
template<class TYPE>
class Matrix
{
private:
size_t mNrRows; // note size_t. This is unsigned because there is no reason
// for a matrix with a negative size. size_t is also guaranteed
// to fit anything you can throw at it.
size_t mNrColumns;
std::vector<TYPE> mVec;
public:
// make a default-initialized matrix
Matrix(size_t nrRows, size_t nrColumns) :
mNrRows(nrRows), mNrColumns(nrColumns), mVec(mNrRows * mNrColumns)
{
}
// make a def-initialized matrix
Matrix(size_t nrRows, size_t nrColumns, TYPE def) :
mNrRows(nrRows), mNrColumns(nrColumns), mVec(mNrRows * mNrColumns,
def)
{
}
// gimme a value and allow it to be changed
TYPE & operator()(size_t row, size_t column)
{
// could check for out of bounds and throw an exception here
return mVec[row * mNrColumns + column];
}
//gimme a value and do not allow it to be changed
TYPE operator()(size_t row, size_t column) const
{
return mVec[row * mNrColumns + column];
}
// gimme the number of rows
size_t getRows() const
{
return mNrRows;
}
// gimmie the number of columns.
size_t getColumns() const
{
return mNrColumns;
}
// printing convenience
friend std::ostream & operator<<(std::ostream & out, const Matrix & mat)
{
int count = 0;
for (TYPE val: mat.mVec)
{
out << val;
if (++count == mat.mNrColumns)
{
out << '\n';
count = 0;
}
else
{
out << ' ';
}
}
return out;
}
};
The vector member handles all of the heavy lifting so the Rule of Zero recommends leaving the copy and move constructors, assignment operators, and destructor up to the compiler.
What does this do to MatrixSlice? Well, first it now received and returns a Matrix instead of vector<vector> and int. The insides use Matrix and the confusion about 1D or 2D is just plain gone, resulting in a simpler function.
Matrix<int> MatrixSlice(const Matrix<int> & Input,
int Row1,
int Row2,
int Col1,
int Col2)
{
Matrix<int> OutPut(Row2-Row1 + 1,
Col2-Col1 + 1); // but what if Row1 > Row2?
int i2;
int j2= 0; // definitely need to initialize this sucker.
for (int i = Row1; i <= Row2; i++) // logical problem here: What if Row2 >= input.getRows()?
{
i2 = 0;
for (int j = Col1; j <= Col2; j++) // similar problem here
{
int DumyValue = Input(i, j);
OutPut(j2, i2) = DumyValue;
i2++;
}
j2++;
}
return OutPut;
}
Not that this completely ignores the very logical option of making slice a Matrix method. While it makes sense, it doesn't need to be a method and the stock recommendation is to prefer a free function. One good improvement is to make the function a template so that it can handle all sorts of Matrix in addition to Matrix<int>.
And finally, what happens to main?
int main()
{
//Define a matrix for test:
Matrix<int> Matrix2(4, 5, 1); // initialize matrix to all 1s
int R = 4;
int C = 4;
Matrix<int> MatrixInput(R, C); // default initialize the matrix
for (int i = 0; i < MatrixInput.getRows(); i++)
{
for (int j = 0; j < MatrixInput.getColumns(); j++)
{
int temp;
temp = i ^ 2 + j ^ 2;
// WARNING: ^ is XOR, not exponent. Maybe OP wants i XOR 2, but not
// likely. But if XOR is the desired operation, there is a lurking
// order of operation bug that needs to be addressed
MatrixInput(i, j) = temp;
}
}
std::cout << MatrixInput << '\n';
std::cout << MatrixSlice(MatrixInput, 0, 3, 1, 1);
return 0;
}
In your code
if (abs(Row1-Row2)>1 && abs(Col1-Col2)>1){
vector<vector<int> > OutPut;
// OutPut dies here
}else{
vector<int> OutPut;
// OutPut dies here
}
// here is no OutPut
OutPut lives only to the end of IF statement.
You either use it without the if statement or you add all code that uses it to the if statement.

Finding the Intersect of 'n' Generic Arrays

EDIT : Added far more detail.
I'm trying to write an algorithm that finds the intersection (points common to all) of n arrays. My program takes these arrays and stores them in a two dimensional array on which the operations take place. For example, here is a sample main method:
int a[] = { 12, 54, 42 };
int b[] = { 54, 3, 42, 7 };
int c[] = { 3, 42, 54, 57, 3 };
IntersectionTableau<int> x(3); // Where 3 is the max number of arrays allowed
// to be stored.
x.addArray(a, 3);
x.addArray(b, 4);
x.addArray(c, 9);
x.run(); // Finds the intersection.
These added arrays will be stored in T** arrays and their sizes in int* sizes. T is a generic type. What is an efficient algorithm that will let me do this on a variable number of arrays of generic types?
Here is what I'm currently attempting to do:
template <class T>
inline
void IntersectionTableau<T>::run() {
T* commonElements = d_arrays[0];
for (int i = 1; i < d_currentNumberOfArrays; ++i) {
commonElements = getIntersection(commonElements, d_arrays[i], d_sizes[i - 1], d_sizes[i]);
}
d_results = commonElements;
}
template <class T>
inline
T* IntersectionTableau<T>::getIntersection(T* first, T* second, int sizeOfFirst, int sizeOfSecond) {
T* commonElements;
if (sizeOfFirst > sizeOfSecond) {
commonElements = new T[sizeOfFirst];
} else {
commonElements = new T[sizeOfSecond];
}
for (int i = 0; i < sizeOfFirst; ++i) {
for (int j = 0; j < sizeOfSecond; ++j) {
if (first[i] == second[i]) {
commonElements[i] = first[i];
}
}
}
return commonElements;
}
The first function takes the first two arrays and sends them to the second function, which returns an array of the intersections between those two arrays. Then, the first function compares the intersection array with the next array in d_arrays and so on. My problem is when I go to print out an element from d_results a garbage value is produced, and I'm unsure why. Could someone tell me what I'm doing wrong, or alternatively, a better way to accomplish this?
There are at least two problems in the code:
if (first[i] == second[i])
This should be if (first[i] == second[j]).
commonElements[i] = first[i];
This is trickier to fix. I think you want to have another variable (neither i nor j); let's call it k:
commonElements[k++] = first[i];
Anyway, since you can use C++, you can use a std::vector instead. It stores its size inside; this will reduce confusion:
template <class T>
std::vector<T> // note: adjusted the return type!
IntersectionTableau<T>::getIntersection(...)
{
std::vector<T> commonElements;
for (int i = 0; i < sizeOfFirst; ++i) {
for (int j = 0; j < sizeOfSecond; ++j) {
if (first[i] == second[j]) {
commonElements.push_back(first[i]);
}
}
}
return commonElements;
}
You can turn first and second into vectors too (though you won't benefit much from it right now).
Here are some points to note:
I changed the return type to vector<T>
The old version, which returns an array, requires additional code to specify the length of its result; this version returns the length inside the vector<T> object
The old version, which returns an array, requires delete[] array somewhere later, to prevent a memory leak
The vector-to-pointer hack &commonElements[0] will not work for an empty vector
If your other code works with an array/pointer, you can use the vector-to-pointer hack &commonElements[0], but outside the function, in order to respect the lifetime rules:
T* commonElements = NULL;
for (int whatever = 0; whatever < 10; ++whatever)
{
std::vector<T> elements = xxx.getIntersection(...); // will work
commonElements = &elements[0]; // can pass this pointer to a function receiving T*
print(commonElements); // will work
}
print(commonElements); // cannot possibly work, will probably segfault
print(elements); // cannot possibly work, and compiler will reject this