C++ 2D vector SIGSEV error - c++

I am getting segmentation error in the following code, can anyone bother to explain. I think it might have to do with initialization, but not sure. I am just trying to clone the existing stack and perform operation such as adding entry to the clone or removing entry from existing and cloning it to new stack.
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <deque>
#include <string>
using namespace std;
#define in cin
#define out cout
int main()
{
//ifstream in("postfix.in");
//ofstream out("postfix.out");
int n;
in>>n;
long sum=0;
vector<int> tm(0);
vector<vector<int>> ar(0,tm);
//ar[0].push_back(0);
out<<ar[0][0];
for(int i=0;i<n;i++)
{
int ind,val;
in>>ind>>val;
if(val==0)
{
for(int j=0;j<ar[ind-1].size();j++)
ar[i].push_back(ar[ind-1][j]);
ar[i].pop_back();
}
else
{
for(int j=0;j<ar[ind-1].size();j++)
ar[i].push_back(ar[ind-1][j]);
ar[i].push_back(val);
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<ar[i].size();j++)
sum+=ar[i][j];
}
out<<sum<<endl;
return 0;
}

vector<int> tm(0);
vector<vector<int>> ar(0,tm);
Here you initialized ar as an empty vector of vector of int. Without enlarging its size through push_back(), resize(), insert(), etc., you cannot access ar[i].
You may instead initialize ar as
vector<vector<int>> ar(n);
But in the existing snippet you provided there is no clue about how large the second dimension should be.
Per your comment in this answer, your declaration of tm and ar should be
vector<int> tm(1, 0);
vector<vector<int>> ar(1, tm);
Or even shorter since tm is not really used later,
vector<vector<int>> ar(1, vector<int>(1, 0));

I think I see where you're getting tripped up.
vector<int> tm(0);
This does not create a vector containing a 0. This creates a vector with a size of 0. Because this list has a size of 0, you can't get the first element; since it's empty!
Same here:
vector<vector<int>> ar(0,tm);
This doesn't create a vector with 1 "row". It creates an empty vector, since you made the size 0 again.
You likely intended something like:
vector<int> tm(1, 0);
vector<vector<int>> ar(1,tm);
Which creates a row, tm, with a single 0, then creates a 2D vector, ar containing that 1 row.
Check the reference. You're attempting to use the "fill" constructor.

For starters it is a bad idea to use such definitions
#define in cin
#define out cout
It is better to use explicitly std::cin and std::cout because any programmer knows what these names mean.
These declarations
vector<int> tm(0);
vector<vector<int>> ar(0,tm);
do not make great sense. It would be much clear and simpler just to write
vector<int> tm;
vector<vector<int>> ar;
SO as the vectors are empty you may not use the subscript operator as you are doing for instance here
out<<ar[0][0];
^^^^^^^^^
for(int i=0;i<n;i++)
{
int ind,val;
in>>ind>>val;
if(val==0)
{
for(int j=0;j<ar[ind-1].size();j++)
^^^^^^^^^^^
ar[i].push_back(ar[ind-1][j]);
^^^^^
ar[i].pop_back();
^^^^^
}
and so on. You need at first ro append new elements to the vector before using the subscript operator.

Related

How to make a list of stacks in C++?

I'm trying to make a list of stacks in C++ using the code below , but I'm getting the error
main.cpp:17:13: error: ‘__gnu_cxx::__alloc_traits > >::value_type {aka class std::stack}’ has no member named ‘push_back’
vs[i-1].push_back(s);
Code:
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<stack<int>> vs;
for(int i=1; i<4; i++)
{
stack<int> s;
s.push(i*2);
s.push(i*3);
s.push(i*4);
vs[i-1].push_back(s);
}
return 0;
}
you can't use this line:-
vs[i-1].push_back(s);
Either define the size of the list earlier.
For Eg
vector<stack<int> > vs(100);
else only write
vs.push_back(s);
Updated Solution
#include <iostream>
#include<stack>
#include<vector>
using namespace std;
int main()
{
vector< stack<int> > vs;
for(int i=1; i<4; i++)
{
stack<int> s;
s.push(i*2);
s.push(i*3);
s.push(i*4);
vs.push_back(s);
}
return 0;
}
First of all, your vector is empty, any indexing in it will be out of bounds and lead to undefined behavior.
Secondly, vs[any_valid_index] is a stack and not a vector.
What you probably want is
vs.push_back(s);
Its not a fact for only vector of stacks. It is actually basic property of vector. You have two options to add value into vector.
If you don't declare size of vector (what you did) like
vector<stack<int>> vs;
stack<int>s;
Then you can insert by using vs.push_back(s) It will automatically handle the index.
Another way is you can declare the size of the vector first. like
vector<stack<int>> vs(sz); //size(sz) is defined by user
stack<int>s;
Then you can insert by using vs[index]= s This time you have to manually handle the index.

When I use 'auto' in the first loop it works fine, but with 'int' it gives an error, why?

As you can see, my code works fine, but I had a doubt about use of auto and int in the first loop while accessing a vector:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<vector<int>> a{{1,2,3},{4,5,6}};
//why don't work when i use int in the first loop,and why it work when i use auto
for(auto n:a)
{
for(int b:n)
{
cout<<b<<" ";
}
cout<<endl;
}
}
because in the first loop (the outer one), n type is an std::vector<int> not an int.
Note that a is a vector of vectors, hence its elements are vectors, not integers. And of course, the elements of each element of its elements are integers.
The range-based loop can be written explicitly as
for(vector<int> n:a)
Or even better
for(vector<int>& n:a)
to avoid copying
Or even more better
for(const vector<int>& n:a)//equivalent to for(const auto & n:a)
because you don't make a change to it

Declaration of Vectors

Vectors size dynamically, so why is this giving a seg fault:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(){
vector<int> vectorOfInts;
vectorOfInts[0] = 3;
}
What I'm trying to actually do is declare a vector in a class.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Directory{
public:
string name;
int maxIndex;
vector<Directory> subDirectories;
void addSubdirectory(string x){
Directory newSubdirectory(x);
subDirectories[maxIndex++] = newSubdirectory;
}
Directory(string x){
name = x;
maxIndex = 0;
}
};
int main(){
Directory root("root");
root.addSubdirectory("games");
}
But this also gives a seg fault.
Vectors don't resize entirely automatically. You use push_back or resize to change the size of a vector at run-time, but the vector will not automatically resize itself based on the index you use--if you index beyond its current size, you get undefined behavior.
In your demo code, you could do something like this:
vector<int> vectorOfInts(1);
vectorOfInts[0] = 3;
Alternatively, since you're just adding 3 to the end of the existing data (or nonexistent data, in this case) you could just use push_back (or emplace_back):
vector<int> vectorOfInts;
vectorOfInts.push_back(3);
It looks like the same basic approach will work with your real code as well. It also simplifies things a bit, since you don't need to explicitly track the maxIndex as you've done.
A default-constructed vector has no elements (i.e. its size() returns zero).
The operator[] does not check if it is supplied a valid index, and gives undefined behaviour if supplied an invalid index. It does not resize the vector. A vector with size zero has no valid indices.
That combination explains your problem.
The seg fault, come from the fact that you try to acces an element that does not exist. When you use operator [ ], be sure that you already alocate memory for this element using resize, push_back, emplace_back...
To make your code work, just replace this
void
addSubdirectory(string x)
{
Directory newSubdirectory(x);
subDirectories[maxIndex++] = newSubdirectory;
}
by
void
addSubdirectory(string x)
{
subDirectories.emplace_back(x); // c++11
// else subDirectories.push_back(Directory(x));
}
and you don't need the maxIndex, you can have it using the size method: subDirectories.size() - 1.

Storing a string into a vector

The error says that no matching function to call for push_back().
I included <vector> so I don't understand why this error is occurring. If you could also show me how to take in a string and store it into a vector that would be really helpful!
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> list;
char input;
while(cin>>input)
{
list.push_back(input);
}
for(int i=0;list.size();i--)
{
cout<<list[99-i];
}
}
Since your list is a vector of string, pushing single chars into it wouldn't work: you should either make it a vector of chars, or read strings:
string input;
while(cin>>input) {
list.push_back(input);
}
Note that list[99-i] is rather suspicious: it will work only if the list has exactly 99 elements, and only if you change i-- for i++. Otherwise, you would get undefined behavior either on accessing elements past the end of the vector, or accessing elements at negative indexes.
If you would like to print the list from the back, use list[list.size()-1-i] instead, and use i++ instead of i--, because otherwise the loop would not stop.
Well, the error is correct. It helps, though, to read all of it!
The class vector<string> has a function push_back(const string&).
It does not have a function push_back(char).
I don't know why you're extracting individual chars but storing whole strings; don't do that.
Because you are trying to put in char into a string vector.
Change input to string.
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
string v;
vector<string> s;
for(int i=0;i<n;i++)
{
cin>>v;
s.push_back(v);
}
sort(s.begin(),s.end());
for(int i=0;i<n;i++)
{
cout<<s[i]<<endl;;
}
return 0;
}

c++ vector push_back need assistance

Question is very easy but i forgot to use c++ and don't know where else to ask.
I have question regarding vectors in c++: when i make vector with objects and when i try to push_back new object on vector i get some wierd error. Can u help me and say how should i use push_back (on object?) so it works. Thanks!
I have .h class:
class x{
public:
x();
double cpuGHz;
int hddGB;
char brand[25];
};
and have main class:
#include "Racunalo.h"
#include <iostream>
#include <cstdlib>
#include <string.h>
#include <vector>
using namespace std;
int main()
{
int n,i;
double cpu;
int hdd;
char bra[25];
vector<Racunalo> vec;
Racunalo rac;
cin >> n;
for (i=0; i<n; i++)
{
cin >> bra;
cin >> hdd;
cin >> cpu;
strcpy(rac.brand, bra);
rac.hddGB = hdd;
rac.cpuGHz = cpu;
vec[i].push_back(rac); // this line is "rotten"
}
Replace
vec[i].push_back(rac);
with
vec.push_back(rac);
Good luck
vec[i].push_back(rac);
^^^^^^^
a reference to Recunalo object
vec[i] gives you an element of your vector (a reference to element), so you cannot push_back to it (unless it is object of class with push_back function). Here vec[i] refers to Racunalo object. std::vector::push_back is a member function of vector, so we call it on the object this way:
vec.push_back( rac);
^^^^
std::vector<Recunalo>
std::vector::push_back
Vector is just like an array except that it can grow dynamically.
push_back is a method that adds at the end of the container. If you create a vector like vector a(10) and then do a push_back you are inserting at the 11th place since all the first 10 places are initialized with 0. So, to be helpful it is ideal to create a vector like vector a, without any size, and then using push_back to insert at the end.
vector a;
a.push_back(5);