Multidimensional Vector? - c++

So I recently started learning C++ and I'm trying to figure out how to access a multidimensional vector or a vector with vectors stored inside of it. I've looked all over and I can't find exactly what I'm looking for. I want to be able to test the contents of each vector inside of the multidimensional vector by printing them out. Also whenever I try to see the size of the vector after each iteration, I'm getting random constants for each iteration. They look like they may be memory locations but I'm not sure.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int numofArrays;
int numofQueries;
vector<vector<int>> arr(numofArrays);
cin >> numofArrays;
cin >> numofQueries;
int arrSize;
int number;
vector<int> indArr;
// Outer loop, appends vectors containing ints to a multidimensional vector
for (int i = 0; i < numofArrays; i++) {
cin >> arrSize; // Getting number of elements from user
// Inner loop, gets user inputted values then creates a vector which is added to the multidimensional vector
for (int x = 0; x < arrSize; x++) {
cin >> number;
indArr.push_back(number);
cout << "Last number added to vector: " << number << endl; // Checking to see if correct numbers are being added.
}
arr.push_back(indArr);
cout << "Multidimensional Vector size: " << arr.size() << endl; // Checking size of vector after each iteration
indArr.clear(); // Empties vector for next iteration
}
return 0;
}
As I am very new to C++, I welcome constructive criticism.
Newly Revised Code:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int numofArrays;
int numofQueries;
cin >> numofArrays;
cin >> numofQueries;
vector<vector<int>> arr(numofArrays);
// Outer loop, appends vectors containing ints to a multidimensional vector
for (int i = 0; i < numofArrays; i++) {
int arrSize;
vector<int>indArr;
cin >> arrSize; // Getting number of elements from user
indArr.resize(arrSize); // Resizing array for next values
// Inner loop, gets user inputted values then creates a vector which is added to the multidimensional vector
for (int x = 0; x < arrSize; x++) {
int number;
cin >> number;
indArr.push_back(number);
cout << "Last number added to vector: " << number << endl; // Checking to see if correct numbers are being added.
}
arr.push_back(indArr);
cout << "Multidimensional Vector size: " << arr.size() << endl; // Checking size of vector after each iteration
}
int test = arr[0][0];
cout << test;
return 0;
}

Just some tips:
vector<vector<int>> arr(numofArrays); constructs a vector of vectors of size numofArrays. But numofArrays is not yet read from cin, so it is an undefined number. Care with the order of operations.
arr.push_back(indArr); adds a vector at the end of arr.
Hence, in your loop, even if you fix the order of reading numofArrays and declaring arr, you start with an array of size numofArrays, and each cycle you add an element. You will end up with arr holding 2 times numofArrays elements.
Also, indArr is a temporary variable, which you reset each cycle. Although there is nothing wrong about what you are doing, in general is better to keep each variable limited to its scope. If you define indArr inside the loop, it will be automatically cleared and re-created. May not be the most efficient way to do things in all cases, but I'd leave this details for later.
Something like this should work for you:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int numofArrays;
int numofQueries;
cin >> numofArrays;
cin >> numofQueries; // this is an unused variable
vector<vector<int> > arr;
// Outer loop, set vectors containing ints to a multidimensional vector
for (int i = 0; i < numofArrays; i++) {
int arrSize;
vector<int> indArr;
cin >> arrSize; // Getting number of elements from user
// Inner loop, gets user inputted values then creates a vector which is added to the multidimensional vector
for (int x = 0; x < arrSize; x++) {
int number;
cin >> number;
indArr.push_back(number);
cout << "Last number added to vector: " << number << endl; // Checking to see if correct numbers are being added.
}
arr.push_back(indArr);
cout << "Multidimensional Vector size: " << arr.size() << endl; // Checking size of vector after each iteration
}
return 0;
}

The way you're inspecting the size is correct. For example in your code you're printing the integer number of elements in the first dimension of the array arr.
The odd results you're getting is because of how you're initializing the vector. In the constructor for arr there you specify a size describing the number of default-constructed elements to fill the vector with. However you're providing numofArrays which is an undefined value. Hence you receive random looking vector sizes when you print this out.
The real size of the vector arr's first dimension will be whatever this undefined value is plus one, due to the push_back operation.

Related

C++ program not entering a for loop using vector

I was practicing with vector, I wanted to push an element using push_back(); using a for loop, but the program doesn't even enter the for loop, help!!!
#include <iostream>
#include <vector>
using namespace std;
int main()
{
cout << "check ";
int val;
vector<char> vec;
cout << "check " << endl << "Its in the game";
//those two "check" were to confirm if the program is even running and is it a
problem while declaring the vector
for(int i = 0; i < vec.size(); i++){
cout << "enter element for vector" << endl;
cin >> val;
vec.push_back(val);
}
}
Your vector is empty. The for loop starts at zero, which is not less than zero, so the for loop never runs.
Your vector is literally empty, which means vec.size() is 0.So It will never enter the loop. If you know what your vector size is gonna be, you should define it as
std::vector<int> vec(vec_size);
for(int i=0;i<vec_size;++i)
{
//whatever.....
}
Or you could have used a while loop.
while(std::cin>>val)
{
//do your thing....
}

How to determine number of values added to vector in C++?

I'm trying to build a little task using C++ in which I need to allow the user to determine up front how many gross_paychecks they would like to place in a vector called 'gross_paychecks_vector'.
So far this is what I have:
vector<double> gross_paychecks_vector (5);
double gross_paychecks;
// Add 5 doubles to vector
cout << "Please enter an integer" << endl;
cin >> gross_paychecks;
for(gross_paychecks = 0; gross_paychecks <= gross_paychecks_vector; ++gross_paychecks ){
cin >> gross_paychecks;
}
Right now I'm somewhat lost because I'm not sure whether to switch the vector to something like vector<double> gross_paychecks {} because it throws an error in the for loop.
Also I'm not sure how to go with the for loop (should I actually use a for-loop or something else?). I need to accept input from the user as long as it has not met the numbers of gross_paychecks that he/she has specified.
You probably want this:
vector<double> gross_paychecks_vector; // initially the vector is empty
...
cout << "How many paychecks:" << endl;
cin >> gross_paychecks;
for (int i = 0; i < gross_paychecks; i++)
{
double value;
cin >> value;
gross_paychecks_vector.push_back(value); // add new value to vector
}
// display values in vector
for (auto & value : gross_paychecks_vector)
{
cout << value << "\n";
}
Additionally. If you want to use modern C++ features, you would use:
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
int main()
{
std::vector<double> grossPaychecks{};
std::cout << "How many paychecks:\n";
size_t numberOfPaychecks{0};
std::cin >> numberOfPaychecks;
// Read all data
std::copy_n(std::istream_iterator<double>(std::cin),numberOfPaychecks, std::back_inserter(grossPaychecks));
// Print all data
std::copy(grossPaychecks.begin(), grossPaychecks.end(), std::ostream_iterator<double>(std::cout,"\n"));
return 0;
}

How to print desired amount of elements in an array?

If I want to print a single dimensional array with n number of elements. Can I initialize the array as array[n] ?
#include "pch.h"
#include <iostream>
using namespace std;
int main()
{
int n;
std::cout << "Please enter the number of elements (n): ";
std::cin >> n;
int array[n];
for (int i = 0; i <= n; i++) {
std::cin >> array[n];
}
return 0;
}
As C++ does not support Variable Length Arrays (VLAs) contrary to C99, you'll have to use some other means of allocating memory of arbitrary size in C++ like std::vector:
#include <iostream>
int main()
{
int n;
std::cout << "Please enter the number of elements (n): ";
std::cin >> n;
std::vector<int> foo(n);
// valid indexes range form 0 to size - 1: < n instead of <= n
for (int i = 0; i < n; ++i)
std::cin >> foo[i];
}
Also you mixed up i and n in your for-loop.
std::cin >> array[n] << " ";
^^^^^^
won't work either.
In C++ you cannot initialize an array with a variable length. Either you:
dynamically allocate memory
int *array = new int[n];
in which case you should not forget to deallocate later with
delete[] array;
Or you can use a std::vector
std::vector<int> array(n);
which will be deallocated when it exits the scope.
Additional mistakes are:
The for loop should be like
for (int i = 0; i < n; i++)
because with n elements the array indexes go from 0 to n - 1.
To read the input you can simply use
std::cin >> array[n]
The code you wrote with a combination of >> and << cannot work.

Stumped on array creation program

For a program I must use an array and not vector. I have to take in user's input, and it's a indefinite amount of them. The user can type in 5 values, or 50. I am absolutely stumped as to how to go about doing this. Using a for loop for example:
Int a[10];
Int b;
For (int i=0; i<10; i++)
{
Cout<<"enter values:";
Cin>>b;
A[i]=b;
}
With this I can take an array of 10 of user defined variables but how would I go about making it a dynamic size? Thank you for the help!
The size of a static array must be known at compile time, otherwise you must use a dynamic array. For example
#include <iostream>
int main()
{
// Determine how many total entries are expected
int entries;
std::cout << "How many values do you want to enter?" << std::endl;
std::cin >> entries;
// Allocate a dynamic array of the requested size
int* a = new int[entries];
// Populate the array
for (int i = 0; i < entries; ++i)
{
std::cout << "enter a value: ";
std::cin >> a[i];
std::cout << std::endl;
}
// Clean up your allocated memory
delete[] a;
return 0;
}

Arranging elements from two vectors alphabetically into one vector

The two vectors the user enters will always be in alphabetical order, and the function merge_items places those values in one vector seeing which one comes before the other by using the < operator, the code initially gave a segmentation fault and at certain times, it doesn't show the last element.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void merge_items(vector<string>& a1,vector<string>& b1,vector<string>& merged);
int main(){
vector<string> v1,v2;
string a,b;
int n1,n2;
cout << "How many values for v1? " << endl;
cin >> n1;
for(int i = 0;i < n1;i++){
cin >> a;
v1.push_back(a);
}
cout << "How many values for v2? " << endl;
cin >> n2;
for(int i = 0;i < n2;i++){
cin >> b;
v2.push_back(b);
}
vector<string> merge;
merge_items(v1, v2, merge);
for(int i = 0;i < merge.size();i++){
cout << merge[i] << endl;
}
return 0;
}
void merge_items(vector<string>& a1,vector<string>& b1,vector<string>& merged){ int i1 = 0,i2 = 0;
string temp;
while(i1+i2 < (a1.size()-1+b1.size()-1)){
if(a1[i1] < b1[i2]){
temp = a1[i1];
merged.push_back(temp);
i1++;
}else{
temp = b1[i2];
merged.push_back(temp);
i2++;
}
}
}
This is the appropriate way to merge:
std::merge(a1.begin(), a1.end(),
b1.begin(), b1.end(),
std::back_inserter(merged));
As far as what's wrong with your solution. A couple things.
First, once you reach the end of one of the two vectors, you need to stop comparing against that vector and just copy whatever elements are left from the other vector. So you need to compare i1 against a1.size(), separately from your comparison of i2 against b1.size(). With what you're doing now, when you reach the end of one vector, you continue comparing against out of bounds elements from that vector, which is undefined behavior, and likely the cause of your segmentation faults.
Second, you don't need to be subtracting 1 from the size of the vectors. The way you're doing it will leave you with a merged vector which has 2 fewer elements than the combined sizes of the source vectors.