I am trying to fill an array with different integers, but it doesn't work as expected.
#include <iostream>
using namespace std;
int main(){
int i=0;
int num;
int MyArray[]={};
while (true) {
cout<<"sayi giriniz"<<endl;
cin>>num;
MyArray[i]=num;
i++;
for (int j=0; j<i; j++) {
cout<<MyArray[j]<<endl;
}
}
return 0;
}
https://imgur.com/a/tANGpSY
When I enter the 3rd value it gives an unexpected result.
int MyArray[]={};
Now, MyArray has a size of 0, so any indexes that you tried to access MyArray will cause undefined behavior.
If you want to make an array that is dynamically in size, use std::vector in the <vector> header.
Change
int MyArray[]={};
to
std::vector<int> MyArray;
This:
MyArray[i]=num;
i++;
To this:
MyArray.push_back(num); // you don't even need i
This
for (int j=0; j<i; j++) {
cout<<MyArray[j]<<endl;
}
To this:
for(const auto &i : MyArray) // range based for loop, recommend
{
std::cout << i << '\n';
}
Also, using namespace std; is bad, so don't use it.
If you want to take input and are unsure about the number of elements, you should use a vector. The array which you have made is of 0 size. It will surely give you an error.
I am confused about c++ two dimensioanal vectors
#include <vector>
int main()
{
//First Code
std::vector<int> oneDimArray;
oneDimArray.push_back(5);
for (int i = 0; i < oneDimArray.size(); i++)
{
std::cout << oneDimArray[i];
}
//Second Code
std::vector<std::vector<int>> twoDimArray;
twoDimArray[0].push_back(5); //Here giving error
for (int i = 0; i < twoDimArray.size(); i++)
{
for (int j : twoDimArray[i])
{
std::cout << j;
}
}
return 0;
}
when i try to run this code First Code is working. But in Second Code i am getting vector out of range error while trying to push back. I guess at first i should say twoDimArray's first size to it. But i dont know how. Because i am definig this twoDimArray in my .h file so if i do this i must do it there. Please can you help me?
The reason this is happening is because of two reasons.
The vector you are trying to access is empty
You are trying to put an int into a vector that was supposed to hold vector<int>s.
Fixed code:
#include <vector>
#include <iostream>
int main()
{
std::vector<int> oneDimArray;
oneDimArray.push_back(5);
for (int i = 0; i < oneDimArray.size(); i++)
{
std::cout << oneDimArray[i];
}
std::vector<std::vector<int>> twoDimArray;
twoDimArray.push_back(oneDimArray); //You can put a vector of ints in here
for (int i = 0; i < twoDimArray.size(); i++)
{
for (int j : twoDimArray[i])
{
std::cout << j;
}
}
return 0;
}
twoDimArray[0].push_back(5) is invalid because the vector had no size yet. After you have pushed back something, or done twoDimArray.resize(new size here);, then you can do that (as long as it isn't out of range).
Also, once a vector has size, you can access the elements of the vector inside the vector by going like twoDimArray[0][0] = 1;. That would give the first value of the first vector inside of the vector to get the value 1.
I am trying to use STl sort on a vector which is a part of a 2d array, but getting an error. What is the correct way to do this? Trying to use vector normally as sort(A,A+A.size()) where A is the vector.
I have added a comment at the sort statement that is giving an error.
#include <iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
while(1)
{
int m,n;
cin>>m>>n;
int arr[m][n];
for(int x=0;x<m;x++)
for(int y=0;y<n;y++)
cin>>arr[x][y];
vector<int> cost[m][n]; //THIS IS THE 2-D ARRAY OF VECTORS
cost[0][0].push_back(arr[0][0]);
for(int i=1;i<m;i++)
{
cost[0][i].push_back(cost[0][i-1][0]+arr[0][i]);
}
for(int i=1;i<n;i++)
{
cost[i][0].push_back(cost[i-1][0][0]+arr[i][0]);
}
for(int i=1;i<m;i++)
{
for(int j=1;j<n;j++)
{
vector<int>::iterator it;
for(it=cost[i-1][j].begin(); it!=cost[i-1][j].end();it++)
cost[i][j].push_back(((*it)+arr[i][j]));
vector<int>::iterator it1;
for(it1=cost[i][j-1].begin(); it1!=cost[i][j-1].end();it1++)
cost[i][j].push_back(((*it1)+arr[i][j]));
//freevec(cost[i][j]);
}
}
int tx,ty,k;
cin>>tx>>ty>>k;
//THIS STEP IS GIVING AN ERROR.
sort(cost[tx][ty],cost[tx][ty]+cost[tx][ty].size());
//THIS STEP IS GIVING AN ERROR.
cout<<cost[tx][ty][k-1]<<endl;
/*
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{ cout<<"\n\n"<<arr[i][j]<<endl;
vector<int>::iterator it;
for(it=cost[i][j].begin(); it!=cost[i][j].end();it++)
cout<<(*it)<<" ";
}
cout<<endl;
}*/
}
}
A vector doesn't change its properties by being an element of an array. So you would sort it just like you would sort a vector that is not an element of a 2D array:
sort(cost[tx][ty].begin(), cost[tx][ty].end());
or
sort(begin(cost[tx][ty]), end(cost[tx][ty]));
Assuming argument dependent lookup finds std::sort, std::begin and std::end.
I have the following code, where i defined a vector of vector of struct
#include <vector>
#include <iostream>
using namespace std;
struct node
{
int index;
double value;
};
int main()
{
vector < vector <node> >vett1;
node p;
p.index=5;
p.value=2;
for (int i=0; i<10; i++)
vett1[i].push_back(p);
return 0;
}
i don't know the right way to fill it. In this way when i run it, compilers gives me segmentation fault error.
When you access vett1[i], but the vett1 has not been filled with size zero. That's why the segmentation fault error occur.
Three ways to fix it:
Add
vett1.resize(10);
before the for loop.
Or define vett1 and set its size as follows:
vector <vector <node>> vett1(10);
Or you can do this if you don't know the exact size pre-hand:
for (int i=0; i<10; i++)
{
vector<node> temp;
temp.push_back(p);
vett1.push_back(temp);
}
I want to create 2D array using vector. But, when I do this, I get seg fault.
Can anyone please explain what I am doing wrong, and possible solution for this problem.
I made everything public since I dont want to deal with getters and setters now.
I want to get the concept of 2D array clear.
#include <iostream>
#include <vector>
using namespace std;
class point
{
public:
point():x(0),y(0){}
~point(){}
point(float xx,float yy):x(xx),y(yy){}
float x,y;
};
int main()
{
vector<vector<point> > a; // 2D array
point p(2,3);
a[0][0] = p; // error here
return 0;
}
Your vector is empty. So you can't use [0][0].
Here is how you declare it:
a.push_back(vector<point>());
a[0].push_back(p);
If you know how many items you will have from the start, you can do :
vector<vector<point> > a(10, vector<point>(10));
It's a vector containing 10 vectors containing 10 point. Then you can use
a[4][4] = p;
However, I believe that using vector of vectors is confusing. If you want an array, consider using uBLAS http://www.boost.org/doc/libs/1_41_0/libs/numeric/ublas/doc/index.htm
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
int main () {
using namespace boost::numeric::ublas;
matrix<double> m (3, 3);
for (unsigned i = 0; i < m.size1 (); ++ i)
for (unsigned j = 0; j < m.size2 (); ++ j)
m (i, j) = 3 * i + j;
std::cout << m << std::endl;
}
Here's another suggestion. What you're trying to accomplish has been done before and can be found within the Boost Multi-Array.
You have constructed a vector of vectors that is empty, and have tried to dereference the first element without adding any elements to it.
Vectors don't work like (some) associative arrays, where attempting to access a value that's missing will add it to the collection. You need to ensure the vectors have an appropriate number of entries before you try to access them by using the appropriate form of the vector constructor or by using push_back.
You're creating your 2D array just fine. The problem is that when you create it, it's an empty array -- it doesn't hold any points at all yet. You try to use the point at [0][0] before you've actually created a point there. Normally, to put a new element into a vector, you use resize() to set the size of the vector, or push_back() to add items one at a time. In this case, the latter will probably be a bit clumsy -- since you have a vector of vectors of point, you need to create a vector of point, push a point onto that vector, then push that vector onto your array.
The simplest way would be to use resize() method as follow:
vector <vector<int>> v;
cin>>n>>m; //n is rows and m is columns
v.resize(n,vector<int>(m));
for(i=0;i<n;i++) // inserts elements into the vector v
for(j=0;j<m;j++)
cin>>v[i][j];
for(i=0;i<n;i++) //accesses elements of vector v
for(j=0;j<m;j++)
cout<<v[i][j]<<" ";
Managed to get it working. Picked up the idea for the 'typedef' from somewhere else. Try the below code, it works:
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <vector>
using namespace std;
int main()
{
int i = 0;
int j = 0;
///////////////////////////////////////////////////////////
typedef vector<string> vecRow;
typedef vector<vecRow> vecCol;
vecRow vr;
vecCol vc;
///////////////////////////////////////////////////////////
// Assigning string elements to the 2d array
for(i=0;i<10;i++)
{
for(j=0;j<5;j++)
{
vr.push_back("string ["+to_string(i)+"]["+to_string(j)+"]");
}
vecRow vr_temp = vecRow(vr);
vc.push_back(vr_temp);
vr.clear();
}
///////////////////////////////////////////////////////////
// Printing back the elements from the 2D array
for(auto element : vc)
{
for(unsigned int ictr = 0;ictr < element.size() ; ictr++)
{
cout<<element[ictr]<<"\t";
}
cout<<endl;
}
getchar();
return 0;
}
You can define vectorMatrix[][], which is a matrix of vectors as follows.
Class:
class vectorMatrix
{
std::vector<object> **cell;
int columns;
int rows;
public:
vectorMatrix(int columns, int rows);
virtual ~vectorMatrix();
void addCellAt(int row, int column, const object& entry);
virtual std::vector<object>* getCell(int row, int column);
void clearMatrix();
};
Define constructor:
vectorMatrix::vectorMatrix(int columns, int rows)
{
this->columns = columns;
this->rows = rows;
cell = new std::vector<object>* [columns];
for (int i = 0; i < columns; i++)
{
cell[i] = new std::vector<object>[rows];
}
}
A method for adding an entry:
void vectorMatrix::addCellAt(int row, int column, const object& entry)
{
cell[channel][timeSlot].push_back(entry);
}
Getting a pointer to the vector in a given row and column:
std::vector<object>* vectorMatrix::getCell(int row, int column)
{
return &cell[row][column];
}
Clearing all the matrix:
void vectorMatrix::clearMatrix()
{
for (int tmpRow = 0; tmpRow < columns; tmpRow ++)
{
for(int tmpColumn = 0; tmpColumn < rows; tmpColumn ++)
{
cell[tmpRow][tmpColumn].clear();
}
}
}
You can use resize(); e.g., here I resize a to a 100 x 200 array:
vector<vector<point> > a; // 2D array
a.resize(100);
for_each(a.begin(),a.end(),[](vector<point>& v){v.resize(200);});
point p(2,3);
a[0][0] = p; // ok now