Today I wrote some code dealing with binary tree. Later I noticed a bug in the code:
void find(TreeNode* root, int target) {
stack<TreeNode*> myStack{{root}};
while(!myStack.empty()){
auto& top = myStack.top(); // here I used auto& by mistake
...
}
}
However, I am confused with auto& top = myStack.top();. After the type deduction, what is the type for top? Is it TreeNode & or TreeNode* &?
How about if I used auto* top = myStack.top()?
auto top = myStack.top(); will assign a local copy of myStack.top() to top.
In this case the type of top will be TreeNode*.
auto& top = myStack.top(); will assign a reference to myStack.top() to top.
In this case the type of top will be TreeNode*&.
auto* top = myStack.top() will assign myStack.top() to top.
In this case the type of top will be TreeNode*.
Related
hello guys i am new to maps in C++ i am having a question regarding copying a particular type map to another map of same kind the details are shown below
I initially declared a map like this
map<string,int> objmap,obj_porcess ;
for(int i = 0; i < 10; i++) {
objmap ["process"+to_string(i)]=i+10//some processing the to_string is just in case but i have strings with names for all 10 values
}
like
objmap["process_today"]=1;
objmap["process_yesterday"]=-1;
objmap["process_tommorow"]=2;
now i want to define some thing like this just my key word should be added with the process and remaining all can be same for all the keys from obj_process
obj_process["today"]=objmap["process_today"] ;
instead of defining all 10 can i have a simple code cause in here i took an example of 10 but i have like 200 set of different strings in the key of map
i already asked a qn for exact opposite one this was my previous qn now when i try its vice versa i got an issue hope i find some help
If you can initialize both at the same time, the solution is straightforward:
const std::vector<std::string> days = {"today", "yesterday", /*...*/};
for(const auto& d : days)
{
objmap["process_" + d] = foo();
obj_process[d] = foo();
}
If you cannot, you should be able to iterate over objmap and get rid of the "process_" prefix with some basic string manipulation:
constexpr auto prefix_length = 8; // length of "process_"
for (const auto& p : objmap)
{
const auto& key = p.first;
const auto& processed_key = key.substr(prefix_length);
obj_process[processed_key] = objmap[key];
}
Iam currently trying an exercise from the "practical programming in C" from MIT opencourseware. the exercise is on huffman coding. it is lab2 part 2 where Iam having an Issue. Primarily the pq_insert() method. Iam getting pretty confused as to how the insertion of a node should be performed? I will post the whole .c file below. I think i need the sudo code for an insert operation.
my node is basically a struct (shown below)
struct tnode
{
struct tnode* left; /*used when in tree*/
struct tnode*right; /*used when in tree*/
struct tnode*parent;/*used when in tree*/
struct tnode* next; /*used when in list*/
float freq;
int isleaf;
char symbol;
};
Iam presuming the pointers "left" and "right" are not used in my PQ construction? I just use "parent" and "next" pointers when creating PQ and if the current "freq" value is less than the next checked nodes "freq" value, I add this to the queue before next ?? I may be wrong here but this is one of the areas in which Iam confused??
below is the full file.
#include <stdio.h>
#include <stdlib.h>
#define MAX_SYMBOLS 255
#define MAX_LEN 7
struct tnode
{
struct tnode* left; /*used when in tree*/
struct tnode*right; /*used when in tree*/
struct tnode*parent;/*used when in tree*/
struct tnode* next; /*used when in list*/
float freq;
int isleaf;
char symbol;
};
/*global variables*/
char code[MAX_SYMBOLS][MAX_LEN];
struct tnode* root=NULL; /*tree of symbols*/
struct tnode* qhead=NULL; /*list of current symbols*/
struct cnode* chead=NULL;/*list of code*/
/*
#function talloc
#desc allocates new node
*/
struct tnode* talloc(int symbol,float freq)
{
struct tnode* p=(struct tnode*)malloc(sizeof(struct tnode));
if(p!=NULL)
{
p->left=p->right=p->parent=p->next=NULL;
p->symbol=symbol;
p->freq=freq;
p->isleaf=1;
}
return p;
}
/*
#function display_tnode_list
#desc displays the list of tnodes during code construction
*/
void pq_display(struct tnode* head)
{
struct tnode* p=NULL;
printf("list:");
for(p=head;p!=NULL;p=p->next)
{
printf("(%c,%f) ",p->symbol,p->freq);
}
printf("\n");
}
/*
#function pq_insert
#desc inserts an element into the priority queue
NOTE: makes use of global variable qhead
*/
void pq_insert(struct tnode* p)
{
struct tnode* curr=NULL;
struct tnode* prev=NULL;
printf("inserting:%c,%f\n",p->symbol,p->freq);
if(qhead==NULL) /*qhead is null*/
{
/*TODO: write code to insert when queue is empty*/
//qhead = null means we nead to set something as the heeed!
//possibly p???????
qhead = p;
return;
//not too sure bout this.
}
/*TODO: write code to find correct position to insert*/
//potentially check if 'symbol' less
//than ??
if(curr==qhead)//curr is always set to null when method called????
{
/*TODO: write code to insert before the current start*/
curr->parent = p;
curr = p;
}
else /*insert between prev and next*/
{
/*TODO: write code to insert in between*/
}
}
/*
#function pq_pop
#desc removes the first element
NOTE: makes use of global variable qhead
*/
struct tnode* pq_pop()
{
struct tnode* p=NULL;
p = qhead;
if(qhead->next != NULL)
{
qhead = qhead->next;
}
/*TODO: write code to remove front of the queue*/
printf("popped:%c,%f\n",p->symbol,p->freq);
return p;
}
/*
#function build_code
#desc generates the string codes given the tree
NOTE: makes use of the global variable root
*/
void generate_code(struct tnode* root,int depth)
{
int symbol;
int len; /*length of code*/
if(root->isleaf)
{
symbol=root->symbol;
len =depth;
/*start backwards*/
code[symbol][len]=0;
/*
TODO: follow parent pointer to the top
to generate the code string
*/
printf("built code:%c,%s\n",symbol,code[symbol]);
}
else
{
generate_code(root->left,depth+1);
generate_code(root->right,depth+1);
}
}
/*
#func dump_code
#desc output code file
*/
void dump_code(FILE* fp)
{
int i=0;
for(i=0;i<MAX_SYMBOLS;i++)
{
if(code[i][0]) /*non empty*/
fprintf(fp,"%c %s\n",i,code[i]);
}
}
/*
#func encode
#desc outputs compressed stream
*/
void encode(char* str,FILE* fout)
{
while(*str)
{
fprintf(fout,"%s",code[*str]);
str++;
}
}
/*
#function main
*/
int main()
{
/*test pq*/
struct tnode* p=NULL;
struct tnode* lc,*rc;
float freq[]={0.01,0.04,0.05,0.11,0.19,0.20,0.4};
int NCHAR=7; /*number of characters*/
int i=0;
const char *CODE_FILE="code.txt";
const char *OUT_FILE="encoded.txt";
FILE* fout=NULL;
/*zero out code*/
memset(code,0,sizeof(code));
/*testing queue*/
pq_insert(talloc('a',0.1));
pq_insert(talloc('b',0.2));
pq_insert(talloc('c',0.15));
/*making sure it pops in the right order*/
puts("making sure it pops in the right order");
while((p=pq_pop()))
{
free(p);
}
qhead=NULL;
/*initialize with freq*/
for(i=0;i<NCHAR;i++)
{
pq_insert(talloc('a'+i,freq[i]));
}
/*build tree*/
for(i=0;i<NCHAR-1;i++)
{
lc=pq_pop();
rc=pq_pop();
/*create parent*/
p=talloc(0,lc->freq+rc->freq);
/*set parent link*/
lc->parent=rc->parent=p;
/*set child link*/
p->right=rc; p->left=lc;
/*make it non-leaf*/
p->isleaf=0;
/*add the new node to the queue*/
pq_insert(p);
}
/*get root*/
root=pq_pop();
/*build code*/
generate_code(root,0);
/*output code*/
puts("code:");
fout=fopen(CODE_FILE,"w");
dump_code(stdout);
dump_code(fout);
fclose(fout);
/*encode a sample string*/
puts("orginal:abba cafe bad");
fout=fopen(OUT_FILE,"w");
encode("abba cafe bad",stdout);
encode("abba cafe bad",fout);
fclose(fout);
getchar();
/*TODO: clear resources*/
return 0;
}
i think i am over thinking this really and the left and right pointers are just used in tree construction after the priority queue is created. another thing that confused me was that "curr" is set to null whenever pq_insert() is called? Iam thinking maybe curr is set to the qhead. asuming its "freq" value is less than the "qhead" freq value? Also iam not doing this as homework or anything. anyway, any input is appreciated.
also not really sure how to use "curr" and "prev" pointers in the pq_insert method. if anyone cold point me in the direction of some pseudo code that would also be pretty helpful.
One of the common ways to implement a priority queue is as a heap, and a heap is commonly represented as a tree structure. However, it appears that the OpenCourseware Lab 2 Part B specifically refers to a linked-list implementation for this priority queue.
It is therefore likely that you are correct in assuming that the "left" and "right" pointers won't be used. Additionally, the "parent" pointer likely won't be used because the comments refer to it as being for the tree-based implementation. A "next" pointer is sufficient for a simple linked list, as each node points to the next node starting from the "head" node or start of the list.
What you're looking to do is called "insert in sorted order" and the general process is described here: inserting element into a sorted list
In general, "curr" will take the value of each node of the linked list as you iterate through it, and "prev" will take the value of the previous node (set this before you advance curr.) Setting curr to null at the start of pq_insert is fine because you'll want to start at the first element of the list when you go to insert a new element. You'll want to know what the previous node was in the case where you find that the current node belongs after the node you're trying to insert.
I was trying to implement singly linked list using share_ptr. Here is the implementation...
Below is the node class...
template<typename T>
class Node
{
public:
T value;
shared_ptr<Node<T>> next;
Node() : value(0), next(nullptr){};
Node(T value) : value(value), next(nullptr){};
~Node() { cout << "In Destructor: " << value << endl; };
};
Below is the linked list class...
template<typename T>
class LinkedList
{
private:
size_t m_size;
shared_ptr<Node<T>> head;
shared_ptr<Node<T>> tail;
public:
LinkedList() : m_size(0), head(nullptr) {};
void push_front(T value)
{
shared_ptr<Node<T>> temp = head;
head = make_shared<Node<T>>(Node<T>(value));
head->next = temp;
m_size++;
if (m_size == 1)
tail = head;
}
void pop_front()
{
if (m_size != 0)
{
// Here I am having doubt------------------------!!!
//shared_ptr<Node<T>> temp = head;
head = head->next;
m_size--;
if (m_size == 0)
tail = nullptr;
}
}
bool empty()
{
return (m_size == 0) ? true : false;
}
T front()
{
if (m_size != 0)
return head->value;
}
};
My question is, am I using the shared_ptr properly for allocating a node? If not, how should I use the shared_ptr to allocate and how should I delete the node in the pop_front method?
I believe this belongs on code review.
Most importantly: Why are you using shared_ptr? shared_ptr means the ownership of an object is unclear. This is not the case for linked lists: Every node owns the next. You can express that using unique_ptr which is easier and more efficient.
pop_front seems to be functioning correctly. You may consider throwing an exception or an assertion instead of doing nothing when using pop_front on an empty list.
front is more problematic. If the list is empty you most likely get a garbage object.
What is the significance of tail? It does not seem to be used for anything and since you cannot go backwards there is no real point to getting the tail.
make_shared<Node<T>>(Node<T>(value)) should be make_shared<Node<T>>(value) instead. make_shared<Node<T>>(value) creates a Node using value as the parameter for the constructor. make_shared<Node<T>>(Node<T>(value)) creates a Node with value as the parameter and then creates a new Node with the temporary Node as parameter and then destroys the first Node.
You are missing the copy and move constructor and assignment and move assignment operators.
After you are satisfied with your list implementation consider using std::forward_list instead.
I have this code which works fine in VS 2013 but doesn't compile in either GCC 4.8 or clang 3.3!
AND_end(c)->next = new ListNode<Point>{ b->val };
The error message is the following: "cannot convert from "Point" to "int".
Now, gradually, member val of b is a Point:
struct Point
{
int x;
int y;
double distance(const Point& other) const
{
if (this == &other)
return 0.;
return std::sqrt(std::pow(other.y - y, 2.) + std::pow(other.x - x, 2.));
}
bool operator==(const Point& other)
{
return x == other.x && y == other.y;
}
bool operator!=(const Point& other)
{
return !(*this == other);
}
};
b is a Line:
using Line = ListNode<Point>*;
a ListNode is a typical node for a singly linked list:
template<typename T>
struct ListNode
{
T val; // Value
ListNode* next = nullptr; // Next node in the list
// Constructor: takes a value of type T and optionally a pointer to the next node
explicit ListNode(T v, ListNode* n = nullptr)
: val{ v }, next{ n }
{
// Empty body, both member variables are initialized already
}
};
So, the line of code that doesn't compile should do the following: create a new ListNode, with T = Point, by supplying to the explicit ListNode constructor its first (and only) argument T v, which is a Point (b->val is a Point). This argument will be copied into the ListNode member val by copy, using the default copy constructor.
What seems to happen in both GCC and clang is that b->val is supplied to the Point constructor, hence the error message above (and for the sake of completeness, and additional warning is given: "missing field 'y' initializer").
VC++12 seems to get it all right instead.
So, what's up? Am I missing anything obvious (maybe, happens from time to time) or is there a nasty problem here?
I think the problem is, you do not have copy constructor for Point, therefore, in this line,
explicit ListNode(T v, ListNode* n = nullptr)
: val{ v }, next{ n }
since there's no copy constructor, val{v} will try to initialize by aggregate.
From 8.5.1,
An aggregate is an array or a class (Clause 9) with no user-provided
constructors.
When an aggregate is initialized by an initializer list,
as specified in 8.5.4, the elements of the initializer list are taken
as initializers for the members of the aggregate, in increasing
subscript or member order. Each member is copy-initialized from the
corresponding initializer-clause.
For a point type, the aggregate initialization shall be val {v.x, v.y}.
Or, you can implement a copy constructor for Point class.
GCC & Clang are correct. VS is wrong and it should reject your code.
I am trying to implement a simple singly linked list of integers which are to be sorted upon insertion in Visual Studio c++ 2010 express.
The problem is that when I create a new node and call the .getValue() function on it, the correct number is returned, however somehow that is being lost when I try calling getValue() on a node already in the list. The node might not be inserted into the list correctly, however I can't find why that would be the case. Some other value which looks like a reference value or something is displayed instead of the correct value.
I added current to the watch window when debugging but was still unable to see any of my variables other than the give value to be inserted. I am new to visual studio so I'm not sure if I'm missing something there. Here is my code:
#include "Node.h";
#include <iostream>
//namespace Linked{
//The first two constructors would be the first in the linked list.
Node::Node(void){
value = 0;
next = 0;
}
Node::Node(int setValue){
value = setValue;
next = 0;
}
Node::Node(int setValue,Node *nextNode){
value = setValue;
next = nextNode;
}
Node * Node::getNext(){
return next;
}
void Node::setNext(Node newNext){
next = &newNext;
}
int Node::getValue(){
return value;
}
bool Node::isEqual(Node check){
return value==check.getValue()&&next == check.getNext();
}
/*
int main(){
int firstInt, secondInt;
std::cin>>firstInt;
Node first = Node(firstInt);
std::cout<<"Enter second int: ";
std::cin>>secondInt;
Node second = Node(secondInt, &first);
std::cout<<"Second: "<<second.getValue()<<"\nFirst: "<<(*second.getNext()).getValue();
system("pause");
}*/
Here is the linked list:
//LinkedList.cpp
LinkedList::LinkedList(void)
{
head = 0;
size = 0;
}
LinkedList::LinkedList(int value)
{
head = &Node(value);
size = 1;
}
void LinkedList::insert(int value){
if(head == 0){
Node newNode = Node(value);
head = &newNode;
std::cout<<"Adding "<<(*head).getValue()<<" as head.\n";
}else{
std::cout<<"Adding ";
Node current = *head;
int numChecked = 0;
while(size<=numChecked && (((*current.getNext()).getValue())<value)){
current = (*(current.getNext()));
numChecked++;
}
if(current.isEqual(*head)&¤t.getValue()<value){
Node newNode = Node(value, ¤t);
std::cout<<newNode.getValue()<<" before the head: "<<current.getValue()<<"\n";
}else{
Node newNode = Node(value,current.getNext());
current.setNext(newNode);
std::cout<<newNode.getValue()<<" after "<<current.getValue()<<"\n";
}
}
size++;
}
void LinkedList::remove(int){
}
void LinkedList::print(){
Node current = *head;
std::cout<<current.getValue()<<" is the head";
int numPrinted = 0;
while(numPrinted<(size-1)){
std::cout<<(current.getValue())<<", ";
current = (*(current.getNext()));
numPrinted++;
}
}
int main(){
int a[5] = {30,20,25,13,2};
LinkedList myList = LinkedList();
int i;
for(i = 0 ; i<5 ; i++){
myList.insert(a[i]);
}
myList.print();
system("pause");
}
Any guidance would be greatly appreciated!
When you create nodes in insert, you're allocating them off the stack, which means that they'll be lost after the function returns.
Get them off the heap with:
Node * newNode=new Node(value);
When you use:
Node newNode=Node(value);
You're allocating that object on the stack, which means that pointers:
&newNode
to it are only valid until that function returns. If you use heap memory this is no longer an issue, but it does mean that you have to implement a destructor for your list which goes through and deletes each node.