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);
Related
I am receiving the following error while calling push_back() method on the Vector class object:
error: request for member 'push_back' in 'edges.std::vector<_Tp, _Alloc>::operator[]<int, std::allocator<int> >(((std::vector<int>::size_type)a))', which is of non-class type 'int'
I am trying to create a graph using an adjacency list and it isn't working
#include <bits/stdc++.h>
using namespace std;
/****************************************/
/// INPUT / OUTPUT
ifstream f("ciclueuler.in");
ofstream g("ciclueuler.out");
/****************************************/
/// GLOBAL DECLARATIONS
int n, m;
const int nmax = 100005;
vector <int> edges;
/****************************************/
inline void readInput()
{
f >> n >> m;
for(int i = 1 ; i <= m ; ++ i)
{
int a, b;
f >> a >> b;
edges[a].push_back(b);
}
}
int main()
{
readInput();
return 0;
}
Sorry for the bad writing this is my first question!
edges[a].push_back(b);
edges[a] gets the a.th element from the vector. As you use a vector<int>, the value you get is an int. And you can't call push_back on an int, as the type int has no member function push_back.
push_back as the name said, pushes a new value at the end of a vector. So you have to use edges.push_back(b).
If your intention is to insert a new value at a given position, you have to use std::vector::insert
Try changing the edges[a].push_back(b) to edges.push_back(b).
And as bolov commented, please explain what are you trying to achieve with edges[a].push_back(b). You ought to call push_back() method directly on the Vector class object.
Checkout this answer, it may help you out:
https://stackoverflow.com/a/34608598/9339019
By doing like this you execute the push_back method on an int and not on a std::vector. Try it instead:
edges.push_back(b);
I need a dynamic array that I don't have to scale(Determine) to a fixed number like the following
string* s;
I have this code so far, but obviously it doesn't work.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
fstream f;
f.open("resa.txt");
string* s;
int i = 0;
while (f.good())
{
f >> *(s + i);
i++;
}
return 0;
}
This is my task:
Now we change the class definitions a bit. No static arrays can occur anymore. The fact that the arrays instead become dynamic means that some class methods need to be modified, and that some / some of the classes need copy constructors and assignment methods (or superimposed assignment operator). [...]"
This means, that I just can't use data structures.
It's not automatic, you have to allocate more memory every time you want to resize, copy elements into new array and delete the old one. Fortunately, standard library got you covered with std::vector - an automatically resizable array.
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
fstream f;
f.open("resa.txt");
string temp;
std::vector<std::string> s;
while (f >> temp)
{
s.push_back(temp);
}
return 0;
}
I also fixed your input reading - see Why is iostream::eof inside a loop condition (i.e. while (!stream.eof())) considered wrong? (applies to good() as well).
Alternatively, you can use std::istream_iterator to initialize vector in one line instead of using loop (credit to Ayxan):
vector<string> s{ istream_iterator<string>{f}, {} };
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.
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.
I have this code:
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector <bool> v;
cin >> v[0];
return 0;
}
Why can't I do that? The compiler won't compile that, but I have other variable types in the vector, it will work just fine. What's the problem with this?
It's because std::vector<bool> is a specialization and doesn't act like a vector at all. This is widely recognized to be a major flaw in the Standard.
In order to save memory, vector<bool> stores each element as a single bit. But bits aren't individually addressable, so operator[] can't return a bool& reference connected to a bit. Instead it returns vector<bool>::reference... and cin doesn't provide function overloads to deal with this.
(juanchopanza correctly points out that your vector didn't have an element zero. But even if it did via resize or other mechanism, the fact that operator[] doesn't return a reference still gets in the way.)
At the time you call v[0], the vector has zero size, so you are accessing out of bounds. This is undefined behaviour.
Furthermore, std::vector<bool> is a specialization which has strange behaviour due to the fact that it does not hold individual bool elements. Its operator[] returns a kind of proxy object, the call to that operator may not do what you expect. It should be used with care, or not used at all.
You can solve the problem by reading a value into a local variable and then pushing it into the back of the vector, as in this working example (similar live demo here):
#include <vector>
#include <iostream>
int main()
{
std::vector<bool> v;
std::cout << std::boolalpha;
v.push_back(true);
std::cout << v[0] << std::endl;
bool b;
cin >> b;
v[0] = b;
std::cout << v[0] << std::endl;
}
This should work:
#include <iomanip>
...
bool a;
cin >> boolalpha >> a;
v.push_back(a);
(In addition to the problem mentioned by Ben Voigt, your current code isn't safe with types other than bool because your vector is empty when you're accessing v[0].)