2-D vector Size - c++

In C++ , I Made A Code That has A 2D Vector in it and Users are Required to give The inputs In 2D vector . I find It difficult To find The no. of rows in 2 vector with the help of size function.
#include <bits/stdc++.h>
#include <vector>
using namespace std;
int diagonalDifference(vector<vector<int>> arr)
{
int d = arr[0].size();
cout << d;
return 0;
}
int main()
{
int size;
cin >> size;
vector<vector<int>> d;
for (int i = 0; i < size; i++)
{
d[i].resize(size);
for (int j = 0; j < size; j++)
{
cin >> d[i][j];
}
}
cout << diagonalDifference(d);
}
The Output Should BE No. Rows , But it is coming NULL

Here
vector<vector<int>> d;
for (int i = 0; i < size; i++)
{
d[i].resize(size);
//...
d is a vector of size 0 and accessing d[i] is out of bounds. You seem to be aware that you first have to resize the inner vectors, but you missed to do the same for the outer one. I dont really understand how your code can run as far as printing anything for arr[0].size(); without segfaulting. Anyhow, the problem is that there is no element at arr[0].

But first, Look at your function argument -> is a copy of your vector ,use (vector<> & my vec) to avoid the copying mechanism of vector class (copy constructor for instance) cause if you put there your vector as a parameter and u will make some changes inside the function brackets you will not see any results ( if you dont wanna change your primary vector from function main, keep it without changes).
Secondly, look at code snippet pasted below.
std::vector<std::vector<typename>> my_vector{};
my_vector.resize(width);
for (size_t i = 0; i < my_vector.size(); ++i)
{
my_vector[i].resize(height);
}
It gives you two dimensional vector
Operator[] for vector is overloaded and you have to use my_vector[0].size() just
my_vector[1].size() and so on ! I recommend for that displaying the size by kind of loops given in c++ standards
Regards!

Related

Accessing a 2D vector using push_back()

I am currently declaring my vector as follows
std::vector<std::vector<int>> test(5, std::vector<int>(2,0));
I then access it like this
`
for (int i = 0; i < 5; i++) {
std::cin >> test[i][0];
std::cin >> test[i][1];
}
`
Since the vector is static (5 Rows, with 2 columns), I would like to make it variable (rows variable, column staitc) by using push_back. However, I don't know how to access the individual columns. Maybe someone can help me.
I already tried to access it with
test.at(i).at(0) and
test.at(i).at(1) but it wont work.
Although I found this solution
`
#include <iostream>
#include <vector>
using namespace std;
int main() {
std::vector<std::vector<int> >nns;
int i = 5;
nns.push_back(std::vector<int> {i});
for(int i = 0; i <nns.size(); i++)
{
for(int j = 0; j < nns[i].size(); j++)
{
std::cout << nns[i][j] << std::endl;
}
}
}
` but there you have to define a static size (int i = 5).
You know how to push a vector into the vector of vectors. You wrote this:
nns.push_back(std::vector<int> {i});
You do not have to specifiy the size i here, you can push an empty vector
nns.push_back({});
Now nns has a single element. nns[0] has 0 elements. Pushing elements to nns[0] works exactly the same, just that its elements are not vectors but integers:
nns[0].push_back(42);
If you do that m-times then nn[0] will have m elements. Also resize works on the inner as well as on the outer vectors. For example to get n elements (vectors) each with m elements (integers):
nns.resize(n);
for (int i=0; i<nn.size(); ++i) nns[0].resize(m);
TL;DR There is nothing special about nested vectors. The outer vectors work exactly the same as the inner vectors. You can construct them with or without elements and you can push elements or resize them.

C++- Filling a 2D array from user input

I'm new to programming and was finding transpose of a matrix.
However, I want the input of the matrix from the user and by writing the following code, the complier doesn't take any input values and immediately stops.
I looked into previous questions posted here about the same but found non useful.
#include<iostream>
using namespace std;
int main()
{
int rows,val;
int num[rows][rows];
cin>> rows;
for(int i=1; i<= rows; i++)
{
for(int j = 1; j <= rows; j++)
{
cin>> val;
arr[i][j]= val;
}
cout<<endl;
}
You can't use variables in array length if they aren't defined as one of the comments mentioned.
arr[i][j] inside your nested for loop isn't declared so that would also give an error, I guess you wanted to use num array which you declared.
The rest is all looking good

Problems with for loop c++

i used to code in javascript, but my new school force me to learn c++.
Im kind new in this language, and here's the problem:
In javascript i can write such a code:
for(let i = 0; i < 10; i++){
var variable[i] = i+3;
}
for(let j = 0; j < 10; j++){
console.log(variable[j]);
}
You may say 'Why don't you just write the code into 1 for loop', but that's only example.
And now i'm trying to rewrite above code to cpp:
int n,k,w;
cin>>n>>k;
for(int i = 0; i < n; i++){
int w[i];
cin>>w[i];
}
//some code here
for(int i = 0; i < n; i++){
cout<<w[i];
}
And here's the question. How can i cout all variables w with index i, cause im getting an error [Error] invalid types 'int[int]' for array subscript.
What you probably want is:
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec;
int size = 0;
std::cin >> size;
for(int i = 0; i < size; i++){
int number = 0;
std::cin >> number;
vec.push_back(number);
}
for(int i : vec){
std::cout << i << " ";
}
}
std::vector<int> is a class designed to provide an interface to resizable array. The push_back() function appends the vector with given argument.
The last loop, which is called a ranged-based for(), is used to print all elements of the vector. You can replace it with plain old for() loop with indexing, since std::vector supports operator [], but if ranged-based approach is sufficient, it should be preferred.
EDIT: I don't know JavaScript, but I assume (from your example) that variables declared inside loops are visible everywhere. This is not the case in C++. Variables' visibility is dependent on the scope they are declared in. If you want your list/array/vector/any other container to be visible to those two for() loops, you have to declare it outside them - like in my example above.
EDIT2: While you should almost always use std::vector for such tasks, one could argue that they want to disable resizing the container. In this case, we are left with simple dynamic allocation. We reach for <memory> library, since we shouldn't manage it ourselves:
#include <iostream>
#include <memory>
int main() {
int size = 0;
std::cin >> size;
auto arr = std::make_unique<int[]>(size);
for(int i = 0; i < size; i++){
int number = 0;
std::cin >> number;
arr[i] = number;
}
for(int i = 0; i < size; i++){
std::cout << arr[i] << " ";
}
}
For auto, either read here or imagine that it's just a magic type that is (almost always) correct. It's like var in Python or JavaScript (but later on its type cannot be changed).
For std::unique_ptr<T[]>, either read here or imagine that it's just a dynamically allocated array that automatically delete[]s itself. If you did not learn about dynamic allocation yet, simply ignore what that means and wait until it's introduced.
Notice that we also got rid of the ranged-based for() loop. Unfortunately, it does not work with plain, dynamically allocated arrays.
Not all compilers support VLA so stick to the Standards; always specify a constant size for arrays. If you need some dynamically changed size then consider using another type of containers like: std::vector.
Also why you re-declared int w inside the for loop? It is local to for loop and changes to it won't affect the outer one.
You get a compile time error in the second loop that complains that w is not an array. To solve it make int w[] outer and on top of the two loops.
int n, k;
cin >> n >> k;
int w[n];
for(int i = 0; i < n; i++)
cin >> w[i];
//some code here
for(int i = 0; i < n; i++)
cout << w[i];
The alternative to VAL use std::vector:
std::vector<int> w;
int n, k;
std::cin >> n;
for(int i(0); i!= n; ++i){
std::cin >> k;
w.push_back(k);
}
for(auto i(0); i != w.length(); ++i)
std::cout << w[i] << ", ";

vector to array and array size in c++

I have a struct:
struct xyz{
int x,y,z;
};
and I initialize a struct xyz type vector:
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
for (int k = 0; k < N; k++)
{
v.x=i;
v.y=j;
v.z=k;
vect.push_back(v);
}
}
}
then I want to transform that vector to array because array is 2 time faster than vector to manipulate, so I do
xyz arr[vect.size()];
std::copy(vect.begin(), vect.end(), arr);
when I run this program it shows me segmentation fault which I think is because vect.size() is too large.
So I am wondering is there any way to convert that large size vector to array without that problem.
I appreciate for any help
My overly pedantic comment got too big, so instead I'll try to make this a somewhat roundabout answer. The short answer is probably just to stick with vector but make sure to use reserve; oh, and benchmark.
You didn't say what compiler or C++ version you're using, so I'll just go with my current gcc.godbolt.org default of gcc 4.9.2, C++14. I'm also assuming that you really want this as a 1-dimension array, rather than the more natural (for your example) 3.
If you know N at compile time, you could do something like this (assuming I got the array offset calculation correct):
#include <array>
...
std::array<xyz, N*N*N> xyzs;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
for (int k = 0; k < N; k++) {
xyzs[i*N*N+j*N+k] = {i, j, k};
}
}
}
The biggest downsides, IMO:
error-prone offset calculation
depending on N, where the code is run, etc, this can blow the stack
On the compilers I tried this on, the optimizers seem to understand that we're moving through the array in contiguous order, and the generated machine code is more sensible, but it could also be written like so, if you prefer:
#include <array>
...
std::array<xyz, N*N*N> xyzs;
auto p = xyzs.data();
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
for (int k = 0; k < N; ++k) {
(*p++) = {i, j, k};
}
}
}
Of course, if you actually know N at compile time, and it won't blow the stack, you might consider a 3-dimensional array xyz xyzs[N][N][N]; since this might be more natural for the way these things are being ultimately being used.
As pointed out in comments, variable length arrays aren't legal C++, but they are legal in C99; if you don't know N at compile time you should be allocating off the heap.
A vector and an array will wind up being identical in terms memory layout; they differ in that vector allocates memory from the heap, and the array (as you are writing it) would be on the stack. The only recommendation I'd make is to call reserve before entering your loop:
vect.reserve(N*N*N);
This means you'll only be doing a single memory allocation up front, rather than grow-and-copy mechanism that you'll get from a default constructed vector.
Assuming xyz is as simple as you declare here, you could also do something like the second example above:
std::vector<xyz> xyzs{N*N*N};
auto p = xyzs.data();
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
for (int k = 0; k < N; ++k) {
(*p++) = {i, j, k};
}
}
}
You lose the safety of push_back, and it is less efficient if xyz default constructor needs to do anything (like if xyz members were changed to have default values).
Having said all that, you really should benchmark. But then, you should probably be benchmarking the code that ultimately uses this array, rather than the code to construct it; I'd have other concerns if construction was dominating usage.

Initializing a member vector<vector<int>> in the constructor value-by-value

I have a class that should generate a 2D vector of ints (in the range of 0-1) that I want to use as a map (called matrix).
class generator
{
public:
void draw(void);
void iterate(void);
generator();
~generator();
private:
vector<vector<int>> matrix;
};
In the constructor I want to fill the matrix with random data:
vector<vector<int>> matrix(height, vector<int>(width));
for (int i = 0; i < height; i++){
for (int j = 0; j < width; j++) {
matrix[i][j] = rand() % 2;
}
}
But I get a read acess violation.
Thank you for your time and effort.
DEPRECATED UPDATE:
I tried using the member function .data() to retrieve the pointer to the data and accessing it directly
ptr = matrix[i][j].data();
*ptr = rand() % 2;
But the result doesn't differ. I'm fairly convinced that this isn't about how I want to access the vector but how I set it up.
UPDATE 2:
The correction provided below does result in the vector being filled as intended. When trying to
cout << matrix[i][j];
in the draw member function I get a read-acess-violation again.
UPDATE 3:
As suggested I checked when exactly this error happens. It happens on the very first try do print out the first integer at matrix[0][0]. The value returned is 0x8. Important: If not replaced by a constant matrix.size() already causes the error.
UPDATE 4:
This is basically my draw()
void generator::draw() {
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix[i].size(); j++) {
cout << matrix[i][j];
}
cout << endl;
}
}
The original source has been updated to reflect the current one.
UPDATE 4:
Slightly cut source code at http://pastebin.com/83vrDJWZ
UPDATE 5:
One more simple mistake on my part has been resolved in the comments. Problem is silved. Thank you all.
Looks like the problem is an invalid pointer due to:
vector<vector<int>*> matrix;
You have a vector of pointers to vector of int, but you never actually allocate the inner elements.
Instead use:
vector<vector<int>> matrix;
And during the initialization steps:
matrix[i].resize(width); // instead of: matrix[i]->resize(width);
Actually, you could simplify it a bit:
std::vector<std::vector<int>> matrix(height, std::vector<int>(width));
Still have to iterate to fill the data, though.