C++, vector: getting incorrect output containing 0's - c++

Why is the vector 'r' giving the output as follows? Instead, it should not have zero in the list.
Can someone help?
output: 0 0 0 0 0 5 1 2 3 4
vector <int> leftRotation(vector <int> a, int d) {
vector<int> r(a.size());
// int j=0;
for(int i=d; i<a.size(); i++)
r.push_back(a[i]);
for(int i=0; i<d; i++)
r.push_back(a[i]);
return r;
}

You are initializing r with a.size() copies of 0 at the start of your code:
vector<int> r(a.size());
At this point, the vector r contains values 0 0 0 0 0 (as many zeroes as there are elements in a).
Then, you push values onto the back of this vector of zeroes. At each step of your loops:
0 0 0 0 0 5
0 0 0 0 0 5 1
0 0 0 0 0 5 1 2
0 0 0 0 0 5 1 2 3
0 0 0 0 0 5 1 2 3 4
Instead, initialize with an empty vector:
vector<int> r;

The local variable of vector<int> r(a.size()) uses a vector's constructor overload that accepts (size_type count) argument and is initialized (or rather zeroed out) to contain a.size() number of 0s. For clarification check out the std::vector constructor overload no. 3:
The overload (3) zeroes out elements of non-class types such as int
Use a default constructor to create an empty container instead:
std::vector<int> r;
or:
std::vector<int> r{};

vector<int> r(a.size());
With this line, you create a vector of initial size a.size(); the initial elements in the vector are set to 0.
Probably your a vector has size 5, so this is where the five zeros in your output come from:
0 0 0 0 0
Then, you invoke the push_back() method on r, and this appends other elements at the end of the r vector.
To get a better help, please clarify your goal.

Related

Insert a vector into a specific location in 2d vector in c++

I just started using c++, so I am still new to vectors and data structures. I'm wondering how to I add a int value into a specific index location of 2d vector. For example, I have a multidimensional vector "chessboard" initialized like:
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
How do I use the insert() method to insert a integer value 1 into say the x,y index [4,3] so It looks like this:
0 0 0 0 0
0 0 0 0 0
0 0 0 1 0
0 0 0 0 0
This Is my code so far:
vector<vector<int>> board(boardsize, vector<int> (boardsize, 0));
int x = 4; // x position for value to be inserted
int y = 3; // y position for value to be inserted
In order to change a value of an element of a std::vector, you can use std::vector::operator[].
For example in your case of a vector containing vectors:
board[x][y] = 1;
Note that std::vector::insert does not modify an existing element, but rather adds a new element (or elements) to the vector. This is not what you want since you set the final desired size of the vector upon construction.
A side note: better to avoid using namespace std; - see here: Why is "using namespace std;" considered bad practice?.

How to resize 2d vector

#include <iostream>
#include <vector>
using namespace std;
int main(void)
{
vector<vector<int> > matrix;
matrix.resize(3, vector<int>(4, 1));
for (size_t i = 0; i < 3; i++)
{
for (size_t j = 0; j < 4; j++)
{
cout << matrix[i][j];
}
cout << endl;
}
matrix.resize(5, vector<int>(7, 0));
for (size_t i = 0; i < 5; i++)
{
for (size_t j = 0; j < 7; j++)
{
cout << matrix[i][j];
}
cout << endl;
}
return 0;
}
'''
As far as I know, when we are resizing a vector using "resize()" over than original capacity, values in original space will remain and new values are assigned to new space.
In the line matrix.resize(5, vector(7, 0)); If we execute that line I thought matrix would be like
1111000
1111000
1111000
0000000
0000000
something like this.
But the programs stops,
I want to know why it won't working.
matrix.resize(5, vector<int>(7, 0));
only add new vector of size 7 not modifying actual vector.
Just resize actual vectors to 7 with:
for (auto &row: matrix) row.resize(7);
so now is working:
1111000
1111000
1111000
0000000
0000000
i tested your codes using an online compiler https://onlinegdb.com/BkwcGuAAD
your columns are not resized (only the rows are resized). running your current code yields
1 1 1 1 0 0 33
1 1 1 1 0 0 33
1 1 1 1 0 0 49 << notice some columns have random numbers?
0 0 0 0 0 0 0
0 0 0 0 0 0 0
try resizing the columns too
matrix[0].resize(7,0);
matrix[1].resize(7,0);
matrix[2].resize(7,0);
matrix.resize(5, vector<int>(7, 0));
you should get something like the following
1 1 1 1 0 0 0
1 1 1 1 0 0 0
1 1 1 1 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
By the C++ Reference
(http://www.cplusplus.com/reference/vector/vector/resize/)
void resize (size_type n);
void resize (size_type n, const value_type& val);
Resizes the container so that it contains n elements.
If n is smaller than the current container size, the content is reduced to its first n elements, removing those beyond (and destroying them).
If n is greater than the current container size, the content is expanded by inserting at the end as many elements as needed to reach a size of n. If val is specified, the new elements are initialized as copies of val, otherwise, they are value-initialized.
If n is also greater than the current container capacity, an automatic reallocation of the allocated storage space takes place.
Notice that this function changes the actual content of the container by inserting or erasing elements from it.
I thought Compiler will understand if I put more longer vector inside of "val".
That is, I thought it would understand this kind of increased "n".
But Compiler will only watch whether "n" parameter itself is changed or not.
Because of this reason, my code wouldn't work properly.
if you want to increase size of vector using size() function, note that you should resize original row values on your hand.

Creating 2-D Boolean Vector with False value

i want too create a 2-D vector of Boolean type with Size n x n . but i don't want to use two for loop to assign false to every index instead of assign directly while creating this vector.
syntax is:- vector<vector<bool>> V(n,false)
but it gives me error
There is a constructor that takes a count and an element, but false is not a std::vector<bool>. You want
std::vector<std::vector<bool>> V(n, std::vector<bool>(n,false) );
// |---- inner vectors ----|
Two disclaimer:
Use std::vector<bool> with caution. It is not like other std::vectors (see eg Alternative to vector<bool>).
A vector of vectors is rarely the best data structure. The power of a std::vector is its data locality, however a std::vector<std::vector<T>> does not have this feature (only elements of the inner vectors are contiguous).
vector<vector> V(n,false) this gives an error because you are not declaring size of each v[i] thus, it can not assign each of v[i][j] to false.
you can use vector<vector> v(n, vector (n, false));
Code:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
vector<vector<bool>> v(n, vector<bool> (n, false));
for(int i=0;i<n;i++)
{
for(int j=0;j<v[i].size();j++)
{
cout<<v[i][j]<<" ";
}
cout<<'\n';
}
}
Ans:
n=5
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

how to sort a triple in C++?

I want to know how to sort the triple below based on the first column using C++?
Can I use std::map?
0 0 1
1 2 0
2 0 3
0 1 4
the wanted result is
0 0 1
0 1 4
1 2 0
2 0 3
You could just use std::sort on, for example, a vector of std::tuple - the default comparison is lexicographic, so first column counts most.
Assuming you are sorting a std::vector<std::vector<int>>
C++11:
std::sort(begin(vec), end(vec), [](const std::vector<int>& a,
const std::vector<int>& b){
return a[0] < b[0]; // sorting on the first column only
});
Assuming you want lexical order:
std::sort(begin(vec), end(vec));

Copying data file into an array

I have a project for school. They gave me a data file that needs to be in an array of 10*10. This array needs to be an upper triangle, which means that all values of and below the diagonal have to be zero. This data file is the time that a project takes by every stage. It means that every [i][j] represents the time for stage from i to j.
Just to make it more complicated the problem ask you to find the longest time per column and add it to the longest time in the next column.
here is my code so far:
#include <iostream>
#include<iomanip>
#include <fstream>
#include <cmath>
using namespace std;
//Function prototype
int minCompletionTime (int Data[], int numTasks);
int main()
{
//Declaring and initializing variables
int num_Events(0), completion_Time(0);
int startSearch(0), endSearch(0);
const int SIZE(10);
char datch;
//Declaring an array to hold the duration of each composite activity
int rows(0),duration_Data [10];
//Declaring an input filestream and attaching it to the data file
ifstream dataFile;
dataFile.open("duration.dat");
//Reading the data file and inputting it to the array. Reads until eof
//marker is read
while (!dataFile.eof())
{
//Declaring an index variable for the array
//Reading data into elements of the array
dataFile >> duration_Data[rows];
//Incrementing the index variable
rows++;
}
//Taking input for the number of events in the project
cout << "Enter the number of events in the project >>> ";
cin >> num_Events;
//Calling the function to calculate the minimum completion time
completion_Time = minCompletionTime(duration_Data, num_Events);
//Outputting the minimum completion time
cout << "The minimum time to complete this project is " << completion_Time
<< "." << endl;
}
int minCompletionTime (int Data[], int numTasks)
{
int sum=0;
//As long as the index variable is less than the number of tasks to be
//completed, the time to complete the task stored in each cell will be
//added to a sum variable
for (int Idx=0; Idx < numTasks ; Idx++)
{
sum += Data[Idx];
}
return sum;
}
Any help will be appreciated
My data file only has 6 elements that holds this elements: 9 8 0 0 7 5
my data should look like this in order to start doing operations.
0 0 0 0 0 0 0 0 0 0
0 0 9 8 0 0 0 0 0 0
0 0 0 0 7 0 0 0 0 0
0 0 0 0 5 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
It is a little confusing. I am sorry. The first and second column should have values of zero and first row the same way. after fifth row should be all zeros as well since it will be filled with more information from other data file.
There are a few ways of solving this problem. Here are 2 very naive ways:
1. Use a 10x10 array:
Read everything in from the data file (dataFile >> data[row][col]).
Have 2 nested loops:
The outer loop iterates over columns.
The inner loop iterates over the rows of that specific column.
Since you have to find the max and the values under the diagonal is zero, you can just be lazy and find the max of each column (you might have trouble if it's a lot larger than 10x10). However, if you want to only go through the rows that are necessary, I'll let you figure it out (it's very simple, don't over think).
2. Only use a 1x10 array:
Initialize the array with the minimal value (0 or -1 should work for you), let's call it the max_row.
Read item by item on each row, and compare it to the value that's stored in the max_row and replace appropriately.
When you're done, just sum up the elements in max_row.