Unable to access vector value by index - c++

#include<iostream>
#include<vector>
using namespace std;
class Stack
{
public:
int top;
vector<int> v;
Stack(int size)
{
top=0;
cout<<"Enter the values"<<endl;
for(int i=0; i<size; i++)
{
int val;
cin>>val;
v.push_back(val);
top++;
}
}
void push(int val)
{
v.push_back(val);
top++;
}
int pop()
{
int x=v[top];
top--;
return x;
}
void disp()
{
for(int j=top; j<=0; j--)
cout<<v[j]<<' ';
}
};
int main()
{
Stack s(3);
int k=s.pop();
cout<<k;
return 0;
}
I am trying to learn the basics of OOP.
Here, my Stack constructor and push function are working fine, but there is a problem with the pop and disp functions.
I'm assuming that I am using an incorrect syntax to access the elements of a vector(maybe?). Can anyone tell me where I am going wrong?
Also, the value of k always comes out to be 0.

You can use the vector functions
int k = s.back();
s.pop_back();
cout << k;
more informationhttp://www.cplusplus.com/reference/vector/vector/back/

You have a off-by-one index error.
The way you have implemented your class, when there are N items in the stack, the value of top is N.
Hence, top is not a valid index to access the elements of v. You can use:
int pop()
{
int x=v[top-1];
top--;
return x;
}
or
int pop()
{
top--;
int x=v[top];
return x;
}

As some of the other answers say, you can use the built-in vector functions to do these things (see pop_back and back.
However, if you want to define your own, I would use the vector.at(index) function. Addressing the values with the index as you have works, but it doesn't do any bounds checking at() does. Which would solve your problem above where your index isn't correct for the zero-based indexing of a vector.

Related

c++ question:After assigning value to a variable,the other variable changed

Following codes are my own API for index prior queue.When I test insert function,I get wrong answer.Then I debug codes,I found that the value of array qp changed after executing sentence----item[k]=vwhich is in insert function.Why the value of array qp changed after assigning value to array item?
template <class T>
class IndexPriorQueue{
private:
int index;//the num of items
int size;//capacity
int* pq;//index binaryheap
int* qp;//qp[pq[i]]=pq[qp[i]]=i
T* item;//item array;
public:
IndexPriorQueue(int qsize){//constructor function
size=qsize;
index=0;
pq=new int(size+1);
qp=new int(size+1);
item=new T(size+1);
for(int i=0;i<size+1;i++)
qp[i]=-1;
}
void insert(int k,T v){
if(contain(k)){
cout<<"index is already in queue"<<endl;
return;
}
//cout<<"insert"<<endl;
item[k]=v;//debug,after excuting this sentence,the value of qp exchanged??
pq[++index]=k;
qp[k]=index;
swim(index);
}
bool contain(int k){
return qp[k]!=-1?1:0;
}
void swim(int j){
while(j>1){
if(item[pq[j/2]]<item[pq[j]]){
exch(j/2,j);
j=j/2;
}else{
break;
}
}
}
void exch(int m,int n){
int temp=pq[m];
pq[m]=pq[n];
pq[n]=temp;
qp[pq[m]]=m;
qp[pq[n]]=n;
}
void display(){
cout<<"item:";
for(int i=1;i<size+1;i++){
cout<<item[i]<<" ";
}
cout<<endl;
cout<<"pq:";
for(int i=1;i<size+1;i++){
cout<<pq[i]<<" ";
}
cout<<endl;
cout<<"qp:";
for(int i=1;i<size+1;i++){
cout<<qp[i]<<" ";
}
cout<<endl;
}
};
Following codes are main function
int main(){
cout<<"before insert:"<<endl;
IndexPriorQueue<char> ipq(10);
ipq.display();
ipq.insert(1,'a');
cout<<"after insert:"<<endl;
ipq.display();
return 0;
}
The problems is your allocations. Take for example
new T(size+1)
That allocates one object of type T and initializes it to the value size + 1 (i.e. it calls the T constructor with size + 1).
If you need to allocate an "array" you should use square brackets [] as in
new T[size+1]
That will allocate an array of size + 1 number of T objects.
A much better solution though, is to use std::vector instead of doing it all manually yourself.

Messy and wrong char visualization (after passing actual parameters) C++

this is my first post. Below the code of my implementation of a char Stack. Theoretically It should print f,g,h. But when I execute it, I can just see a long list of strange signs in the console. Is a compiler issue or code issue? Thanks.
#include <iostream>
using namespace std;
const int max_L = 10;
class Stack {
protected:
char array[];
int length;
public:
Stack(){length = 0;}
bool push(char c) {
if(length < max_L){
array[length] = c;
length++;
return(true);
}
else return(false);
}
void pop(){
if(length >= 1){
cout << array[length];
length--;
} else return ;
}
bool is_empty(){
return(length == 0);
}
void print(){
for(int i = 0; i < length; i++){
cout << array[i];
}
}
};
int main() {
Stack p1;
p1.push('f');
p1.push('g');
p1.push('h');`
p1.print();
return 0;
}
There are two problems in the code. As πάντα ῥεῖ said, the array has to be created with a size. The other problem is that push and pop aren't quite complementary. push puts the added value at array[length], then increments length. So after a call to push, length is the index of the next entry, i.e., the one that hasn't been put in yet. pop has to look at the previous entry, i.e., the one that was just put in. So the code for pop should decrement length before looking at array[length]. Change
cout << array[length];
length--;
to
length--;
cout << array[length];

combinations of k-tuple from n elements set by recursive

#include <vector>
#include <iostream>
using namespace std;
void SubSetNum(bool * select, int*a, int selectk, int k, int selectn, int n )// depthk to
{
if(k>n) return;
if(selectn==n)
{
if(selectk==k)
{
for(int i=0;i<n;i++)
if(select[i]==true)
cout<<a[i];
cout<<endl;
}
return;
}
select[selectk]=false;
SubSetNum(select,a,selectk,k,selectn+1,n);
select[selectk]=true;
SubSetNum(select,a,selectk+1,k,selectn+1,n);
}
int main()
{
int k=3;
int n=5;
int a[]={1,5,8,10,13};
//while(cin>>k)
{
bool *select=new bool[n];
memset(select,0,sizeof(bool)*n);
SubSetNum(select,a,0,k,0,n);
delete []select;
}
return 0;
}
This a question, that I want to get k elements from n elements set.
But it prints out incorrect answer? I am always confused when I design recursive algorithms...Especially the parameter of functions, if or not return value, and so on, thus I always try to forcely remember the code in textbook.
Your mistake is here:
select[selectk]=false;
...
select[selectk]=true;
It should be this:
select[selectn]=false;
...
select[selectn]=true;
I believe the cause of the mistake was a failure to remember what the variables represent. The variable selectn is the index of the element being included or excluded. The variable selectk is the number of elements already included. It does not make sense to use selectk as an index into a.

How store class objects in vector<vector<class *>> and access and pass them to function either by reference or value

#ifndef BINARY_TREE_H
#define BINARY_TREE_H
#include<iostream>
#include<vector>
using namespace std;
class Binary_Tree;
static int levelCount=0;
extern vector<vector<Binary_Tree*>> vec;
extern vector<Binary_Tree*> tempVec;
class Binary_Tree
{
public:
Binary_Tree()
{
childNum=0;
data=0;
level=0;
prev=NULL;
next[0]=NULL;
next[1]=NULL;
};
Binary_Tree(int d)
{
childNum=0;
data=d;
level=0;
prev=NULL;
next[0]=NULL;
next[1]=NULL;
levelCount++;
}
void insert_node(int,int,int);
int get_level();
int get_childCount();
friend int set_childNum(Binary_Tree*);
private:
int childNum;
int data;
int level;
Binary_Tree *prev;
Binary_Tree *next[2];
};
#endif // BINARY_TREE_H
Here is the implementation file
#include<iostream>
#include<cmath>
#include "Binary_Tree.h"
using namespace std;
void Binary_Tree::insert_node(int lev, int d, int sib)
{
if(vec.empty())
{
cout<<"You Have to create Root first";
}
else
{
if(set_childNum(vec[lev][sib-1])==0)
{
cout<<"Child cant be created parent Node already has two childs.";
}
else
{
childNum=set_childNum(vec[lev][sib-1]);
data=d;
level=lev+1;
prev=vec[lev][sib];
next[0]=NULL;
next[1]=NULL;
tempVec.clear();
for(int i=0; i<pow(2,(lev+1)); i++)
{
if(i==childNum-1)
{
tempVec.push_back(this);
}
else
tempVec.push_back(vec[lev][i]);
}
vector<vector<Binary_Tree*>>::iterator itr=vec.begin()+(lev+1);
vec.erase(itr);
vec.insert(itr,tempVec);
}
}
}
int set_childNum(Binary_Tree *lstNdAdr)
{
if(lstNdAdr->get_childCount()==0)
return 1;
else if(lstNdAdr->get_childCount()==1)
return 2;
else
return 0;
}
int Binary_Tree::get_level()
{
return level;
}
int Binary_Tree::get_childCount()
{
if(next[0]==NULL)
{
return 0;
}
else if(next[0]!=NULL && next[1]==NULL)
{
return 1;
}
else
{
return 2;
}
}
MAIN.cpp
#include <iostream>
#include<cmath>
#include"Binary_Tree.h"
using namespace std;
vector<vector<Binary_Tree*>> vec;
vector<Binary_Tree*> tempVec;
int main()
{
Binary_Tree tree;
here:
cout<<"Enter your Choice:1.Create Root Of Tree\n"
<<"2.Insert node\n"<<endl;
int choice;
cin>>choice;
switch(choice)
{
case 1:
{
int d;
cout<<"Enter Data to insert: ";
cin>>d;
Binary_Tree treeDummy(d);
tree=treeDummy;
tempVec.push_back(&tree);
vec.push_back(tempVec);
}
break;
case 2:
{
int lev;
int sibbling;
int d;
cout<<"Enter at which level and data and parent's sibling-no.: ";
cin>>lev;
cin>>d;
cin>>sibbling;
if(sibbling>pow(2,lev))
cout<<"Illegal Sibbling Number."<<endl;
else
tree.insert_node(lev,d,sibbling);
}
break;
}
int x;
cin>>x;
if(x==5)
{
cout<<endl<<endl;
goto here;
}
return 0;
}
in above code i am trying to create a binary tree type structure which can be manipulated and traversed dynamically that is any node can be inserted and can be removed at run time (although its incomplete because i am stuck at a problem). While pushing back the tempVec vector the code produces a segmentation fault and i am also doubtful in passing the object stored in vetcor> vec to the functions in the implementation (I am new to Stl and first time dealing with vector of vectors containing pointer to the class types)
The nested vector's entries are only filled if i is set to 1. But you attempt to access its element [0][0] regardless. You have out of bounds access when i is not 1.
There are numerous problems present in your code, that and combined with the poor style and formatting makes it not so fun to debug.
Binary_Tree treeDummy(d);
tree = treeDummy;
tempVec.push_back(&tree);
I'm not sure what you're trying to do here but the above looks wrong. You are shallow copying treeDummy's data over to tree. You'll lose the link to whatever child node tree points to. Afterwards you're pushing that same tree instance into your temporary vector. That means all the elements in your vector ends up pointing to the local variable tree in main. So even if no segfault occurred you would run into aliasing problems since they all refer to the same tree object and not a separate unique BinaryTree instance.
vector< vector<Binary_Tree*> >::iterator itr=vec.begin()+(lev+1);
vec.erase(itr);
vec.insert(itr,tempVec);
Your BinaryTree::insert_node is using an invalidated iterator after performing erase which is undefined behavior.
childNum = set_childNum(vec[lev][sib-1]);
// ...
prev = vec[lev][sib];
The above can access an out-of-bound index in your vector. eg. You push_back a tempVec with only 1 element in it and then call insert_node with sib = 1.
// ...
if(x == 5)
{
cout<<endl<<endl;
goto here;
}
The use of goto is also completely unnecessary here and should be replaced with a traditional while loop that checks for condition != 5.
The higher level problem in your program, however, is that there's no clear constraints and invariants in its design. What assumptions and preconditions do each of those functions need to work? Why use vectors to hold BinaryTree nodes when the class itself should be dealing with that. You should get the overall design sorted out first, otherwise you'll just play whack-a-mole as other bugs crop up.

Implementing binomial heap

My aim is to construct a binomial heap. Here is my code which i have written right now:
#include<iostream>
using namespace std;
void maxheapify(int a[],int length,int i)
{
int left=2*i;
int right=2*i+1;
int largest=i;
if(left<length && a[left]>a[largest])
{
largest=left;
}
if ( right<length && a[right]>a[largest])
{
largest=right;
}
if(largest!=i)
{
int temp=a[i];
a[i]=a[largest];
a[largest]=temp;
maxheapify(a,length,largest);
}
}
void buildmax(int a[],int length)
{
for(int i=(length-1)/2;i>=0;i--)
{
maxheapify(a,length,i);
}
}
/*void heapsort(int a[],int length)
{
buildmax(a,length);
for(int i=length-1;i>0;i--)
{
int temp=a[i];
a[i]=a[0];
a[0]=temp;
maxheapify(a,i,0);
}
}
*/
void combine_heap(int a[],int n,int b[],int m,int c[])
{
}
int main()
{
int a[100];
int n=sizeof(a)/sizeof(a[0]);
int b[100];
int m=sizeof(b)/sizeof(b[0]);
int c[200];
int length=sizeof(a)/sizeof(a[0]);
for(int i=0;i<length;i++){
a[i]=34+rand()%(length-33);
b[i]=rand()%(i+1);
}
/*heapsort(a,length);*/
/*for(int i=0;i<length;i++)
cout<<a[i]<<" ";*/
return 0;
}
i think trivial solution would be to combine two array into third one and then call buildmax procedure,but i think it is not efficient,i have tried to implement this pseudo code from wikipedia
function merge(p, q)
while not( p.end() and q.end() )
tree = mergeTree(p.currentTree(), q.currentTree())
if not heap.currentTree().empty()
tree = mergeTree(tree, heap.currentTree())
heap.addTree(tree)
else
heap.addTree(tree)
heap.next() p.next() q.next()
but i dont know how to implement it,because in generally how to access subtrees?another variant is construct priority queue and by using insert function insert first from one array and then from another array,but is this optimal?please help me to write code to combine these two max heap into one efficiently
This is a good example of Binomial Heap but it is in c. You will get the basic logic to implement binomial heap. See Example here
Or get video tutorial to here to understand algorithm.