2D vector of unknown size - c++

I defined an empty vector of vectors :
vector< vector<int> > v;
How do i fill that empty vector with vector of size 2 integers ( from input ) each iteration of while loop?
while ( cin >> x >> y ) {
//....
}
Will this one work? Or what's the best and most elegant / effective way of doing it?
while ( cin >> x >> y )
{
vector<int> row;
row.push_back( x );
row.push_back( y );
v.push_back( row );
}

As pointed out by JerryCoffin, you probably better use a :
struct Point {
int x;
int y;
};
and then you might overload the output operator
std::ostream& operator<< (std::ostream& o,const Point& xy){
o << xy.x << " " << xy.y;
return o;
}
and similar the input operator (see e.g. here). And then you can use it like this:
int main() {
Point xy;
std::vector<Point> v;
v.push_back(xy);
std::cout << v[0] << std::endl;
return 0;
}

The another way of doing so is to push the value in a 1-D vector and then push that 1-D vector in 2-D vector. I have also printed the values as a test.
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t,n,temp;
cin>>t;
vector<vector<int>> value;
for(int i=0;i<t;i++)
{
cin>>n;
vector<int> x;
for(int j=0;j<n;j++)
{
cin>>temp;
x.push_back(temp);
}
value.push_back(x);
}
for(int i=0;i<t;i++)
{
for(int j=0;j<value[i].size();j++)
{
cout<<value[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
Hope it helps!!

I wrote it - compilator didnt say anything but i have never used vectors so i haven't figured out how to print it yet
You can print using for example a range based for loop (C++11):
for (const auto &vec : v) { // for every vector in v
for (const auto &num : vec) // print the numbers
cout << num << " ";
cout << '\n';
}
And regular for loop:
for (unsigned int i = 0; i != v.size(); ++i) {
for (unsigned int j = 0; j != v[i].size(); ++j) {
cout << v[i][j] << " ";
}
cout << '\n';
}

Related

Want to reverse an array of numbers C++

I have some code written but I'm not sure why the reversed array is not giving me the exact values I need. I created a second array the same size as the first and used nested for loops to fill the second with the contents of the first in reverse.
See below:
#include <iostream>
using namespace std;
int main()
{
// Ask for how big the array is
int n;
cout << "how big is the array?" << endl;
cin >> n;
// create array
int a[n];
// create second array
int b[n];
// ask for contents of the 1st array
cout << "what's in the array?" << endl;
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
// reverse the array
for (int i = n - 1; i >= 0; i--)
{
for (int k = 0; k < n; k++)
{
b[k] = a[i];
break;
}
}
// print out the new array
for (int k = 0; k < n; k++)
{
cout << b[k] << endl;
}
return 0;
}
you don't need 2 bucles for fill the second array
try with:
//reverse the array
s = 0;
for (int i=n-1;i>=0;i--){
b[n]=a[s];
s++;
}
Try something like this:
#include <algorithm>
#include <iostream>
#include <vector>
namespace {
template <typename IStream>
[[nodiscard]] int readOneIntFrom(IStream& istream) {
int x;
istream >> x;
return x;
}
}
int main()
{
// Ask for how big the array is
std::cout << "how big is the array?" << std::endl;
auto n = readOneIntFrom(std::cin);
// create array
std::vector<int> a;
// ask for contents of the 1st array
std::cout << "what's in the array?" << std::endl;
for (int i = 0; i < n; i++)
{
a.emplace_back(readOneIntFrom(std::cin)); // Make a new entry at the end of a.
}
// Construct b from a backward. (Or do auto b = a; std::reverse(b.begin(), b.end());
auto b = std::vector<int>(a.rbegin(), a.rend());
// print out the new array
for (const auto& bi : b)
{
std::cout << bi << std::endl;
}
return 0;
}

How to pass matrix and int into a class method as parameters?

int main(){
int row1, column1;
cout << "How many rows for first matrix?";
cin >> row1;
cout << "How many columns first matrix?";
cin >> column1;
int org[row1][column1];
cout << "Enter the elements of first matrix: ";
for(int i=0;i<row1;i++){
for(int j=0;j<column1;j++){
cin>>org[i][j];
}
}
for(int i=0;i<row1;i++){
for(int j=0;j<column1;j++){
cout<<org[i][j];
}
cout<<endl;
}
matrixreshape sol;
I have problems passing column1, row1, and matrix org into the matrixReshape function.
cout<<sol.matrixReshape(vector<vector<int> org[row1][column1],row1, column1);
matrixReshape function as follows:
class matrixreshape {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
vector<vector<int>> newMatrix(r, vector<int>(c, 0));
The method matrixReshape needs a vector<vector<int>> as an actual argument. You are trying to pass it a 2D VLA which is not directly convertible.
You need to use vector<vector<int>> for input and pass that to the matrixReshape.
Here's an example:
vector<vector<int>> org( row1 );
for ( int i = 0; i < org.size(); i++ )
{
org[i].resize( column1 );
for ( int j = 0; j < org[i].size(); j++ )
{
cin >> org[i][j];
}
}
// and then pass it
matrixreshape sol;
cout << sol.matrixReshape( org, row1, col1 );
Or, with C++11's range-for loop, it would be like this:
std::size_t rows {0};
std::size_t cols {0};
std::cin >> rows >> cols;
std::vector<std::vector<int>> matrix( rows );
for ( auto& r : matrix )
{
r.resize( cols );
for ( auto& c : r )
{
std::cin >> c;
}
}
matrixreshape sol;
std::cout << sol.matrixReshape( matrix, rows, cols );
Here's a complete working example: https://godbolt.org/z/XPwRMq
In addition, you don't need rows and columns information to pass to matrixReshape() method as the std::vector has size() method. You can use that if you need that.
Another thing is that you have to overload stream insertion operator << for this type to print it with std::cout.
Here's an example (live):
#include <iostream>
#include <vector>
using Matrix = std::vector<std::vector<int>>;
std::ostream& operator<<( std::ostream& os, const Matrix& m )
{
for ( const auto& r : m )
{
for ( const auto& c : r )
{
os << c << ' ';
}
os << '\n';
}
return os;
}
int main()
{
const Matrix m
{
{ 1, 2 },
{ 3, 4 }
};
std::cout << m;
return 0;
}
Output:
1 2
3 4

How to get input separated by space and store it in a vector in c++

I have a class having three instances, one integer - noOfCouples and two vectors - womenHotness and menHotness
I have to first take the input noOfCouples and then according to my first input i have to take input separated by spaces and create the two vectors
So far i have done this
#include <iostream>
#include <vector>
class hotness {
private:
int noOfCouples;
std::vector<int> womenHotness;
std::vector<int> menHotness;
public:
void setNoOfCouples(int num);
void setWomenHotness(std::vector<int>& hotness);
void setMenHotness(std::vector<int>& hotness);
int getNoOfCouples();
std::vector<int> getWomenHotness();
std::vector<int> getMenHotness();
};
void hotness::setNoOfCouples(int num) {
noOfCouples = num;
}
void hotness::setMenHotness(std::vector<int> &hotness) {
menHotness.swap(hotness);
}
void hotness::setWomenHotness(std::vector<int> &hotness) {
womenHotness.swap(hotness);
}
int hotness::getNoOfCouples() {
return noOfCouples;
}
std::vector<int> hotness::getMenHotness() {
return menHotness;
}
std::vector<int> hotness::getWomenHotness() {
return womenHotness;
}
int main() {
int t, i = 0, noc, k = 0, output;
std::vector<int> women(1000);
std::vector<int> men(1000);
std::cin >> t;
hotness input[1000];
while(i < t) { // this loop is just for test cases
std::cin >> noc;
input[i].setNoOfCouples(noc);
k = 0;
std::cout << "i = " << i << " k = " << k << "\n";
while(k<noc) {
std::cin >> men[k];
std::cin >> women[k];
k++;
}
input[i].setMenHotness(men);
input[i].setWomenHotness(women);
i++;
}
}
but while debugging i am getting EXC_BAD_ACCESS i.e. i guess my code is trying to access unassigned address to my vector
Is it the right way to assign take the input and assign into a new vector, or is there any mistake in my code
Please suggest most efficient way
Thanks in advance
You get the error because setMenHotness() and setWomenHotness() use the vector::swap() function.
This will swap the contents of the men vector with the menHotness vector.
So at the first iteration of the while(i < t) loop, after the call to the swap function, the menHotness vector will contain 1000 ints and the men vector will contain none.
Then, at the second iteration, you will call std::cin >> men[k];.This will try to store an integer in men[0] but men[0] does not exist anymore and so you get the error.
I would change the setMenHotness and setWomenHotness functions to use the = operator, i.e:
void hotness::setMenHotness(std::vector<int> &hotness) {
menHotness = hotness;
}
void hotness::setWomenHotness(std::vector<int> &hotness) {
womenHotness = hotness;
}
and then change the main function like this:
int main() {
int t, i = 0, noc, k = 0, output;
int user_input;
std::vector<int> women;
std::vector<int> men;
std::cin >> t;
hotness input[1000];
while(i < t) { // this loop is just for test cases
std::cin >> noc;
input[i].setNoOfCouples(noc);
k = 0;
std::cout << "i = " << i << " k = " << k << "\n";
while (k < noc) {
std::cin >> user_input;
men.push_back(user_input);
std::cin >> user_input;
women.push_back(user_input);
k++;
}
input[i].setMenHotness(men);
input[i].setWomenHotness(women);
i++;
}
}
I got the reason for EXC_BAD_ACCESS, it was because of the temporary vector men and women was not getting new instance as it was initiated before the loop for input
Update in the main
int main() {
int t, i = 0, noc, k = 0, output;
std::cin >> t;
hotness input[1000];
while(i < t) {
std::cin >> noc;
std::vector<int> women(1000);
std::vector<int> men(1000);
input[i].setNoOfCouples(noc);
k = 0;
while(k<noc) {
std::cin >> men[k];
k++;
}
k = 0;
while(k<noc) {
std::cin >> women[k];
k++;
}
input[i].setMenHotness(men);
input[i].setWomenHotness(women);
i++;
}
}

vector subscript out of range when writing to file

I want to write a vector to a file, which represents the outcomes of a function that increments j with steps of "double Golf_dl".
The vector itself must have "int Golf_NL" elements in it. (Golf_dl is a private member of class Tsunami)
The problem is that I get a constant vector with all values equal to 0.5, which is rubbish.
Can someone see what's wrong?
Code:
void T_Tsunami::Toestand(int nl)
{
struct pb
{
std::vector<double>& v_;
pb(std::vector<double>& v)
: v_(v){};
pb& operator+(double i)
{
v_.push_back(i);
return *this;
}
};
for( double i = 0; i < nl; i++ )
{
double j=0;
double y = 0.25*(1-tanh(double(j-75)/5));
j+=Golf_dl;
pb(T_1)+y;
}
}
void T_Tsunami::Write(vector<double>d)
{
const int Naamgrootte=64;
char Naam[Naamgrootte];
std::cout << "Geef een bestandsnaam in" << std::endl;
std::cin >> Naam;
std::cout << std::endl;
std::ofstream outFile(Naam);
if (!outFile)
{
std::cerr << "Kan bestand niet openen" << std::endl;
exit (1);
}
for (int i=0; i<100; i++)
{
outFile << d[i] << std::endl;
}
outFile.close();
}
Your problem is in here:
for( double i = 0; i < nl; i++ )
{
double j=0;
double y = 0.25*(1-tanh(double(j-75)/5));
j+=Golf_dl;
pb(T_1)+y;
}
Consider the fact that the loop variable, i, is not used anywhere inside the loop. Also, j and y do not retain their values between loops (they are not static).

dynamically allocated arrays with user input c++

I want to have a mini function that allows the user to type a group of numbers, and each of them will be dynamically allocated into an array. For example:
int main()
{
int* x = NULL;
int n, numbers;
std::cin >> n;
x = new int[n]
for (int i=0;i<n;i++){
std::cin >> numbers;
x[i] = numbers;
}
delete [] x;
So when the user types in
3
The user will be able to type in 3 numbers following that
3 1 2 3
I am trying to store the values 1, 2, 3 into an array so it will look like
[1, 2, 3]
but right now it's storing as
[123]
Anyway i can fix this? I'm new to C++ programming so I feel like there's an easy solution to this but i'm not sure how.. thank you!
You could store each element of the array directly into x[i]. Not sure what numbers is used for (I've assigned numbers from x[i]).
x is the array that is to be deleted. And there is a missing ; at x = new int[x] - is that a typo?
int main()
{
int* x = NULL;
int n, numbers;
std::cin >> n;
x = new int[n];
for (int i=0;i<n;i++){
std::cin >> x[i];
numbers = x[i];
}
delete [] x;
You can use a vector instead:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> v;
for (int i = 0; i < n; ++i)
{
int val;
cin >> val;
v.push_back(val);
}
}
C++'s vector takes care of memory allocation for you. You could then simply traverse it and print its contents.
cout << "[";
for (int i = 0; i < v.size(); ++i)
{
if (i != 0)
cout << ",";
cout << v[i];
}
cout << "]";
Example 1
int main()
{
int* x = NULL;
int n, numbers;
std::cin >> n;
x = new int[n]; // need a semi-colon here
for (int i=0;i<n;i++)
{
std::cin >> numbers;
x[i] = numbers;
}
for (int j = 0; j < n; ++j)
{
std::cout << "x[" << j << "] = " << x[j] << std::endl;
}
delete [] x; // you mean x, not a
return 0;
}
Once you fix (what I assume are just typos), what you have works fine. However, unless this is for an assignment, you should consider using std::vector instead of raw dynamic memory allocation. Doing so would reduce your code to about 4 lines.
int main()
{
std::vector<int> myvector;
std::copy(std::istream_iterator<int>(std::cin), std::istream_iterator<int>(), std::back_inserter(myvector));
std::copy(myvector.begin(), myvector.end(), std::ostream_iterator<int>(std::cout, "\n"));
return 0;
}
or, in C++11
int main()
{
std::vector<int> myvector{std::istream_iterator<int>(std::cin), std::istream_iterator<int>()};
std::copy(myvector.begin(), myvector.end(), std::ostream_iterator<int>(std::cout, "\n"));
return 0;
}
Why not just create the array dynamically? This way, the user won't have to type in the number of elements in advance:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vec;
int x;
while (cin >> x)
vec.push_back(x);
for (int y: vec)
cout << y << ' ';
cout << '\n';
}
The cout statements are just to illustrate that everything worked.