C++ for_each loop can't find pointed to map element - c++

I'm building a huffman coding program and when I try and run the code I have so far it just gives me a warning that the freq map object .begin() doesn't exist.
Huff.h
#ifndef HuffPuff_Huff_h
#define HuffPuff_Huff_h
//---Include---
#include <iostream>
#include <vector>
#include <set>
using namespace std;
//---Node---
struct Node {
int weight;
char litteral;
string symbol;
Node* childL;
Node* childR;
void set_node(int w, char l, Node* L, Node* R){
weight = w;
litteral = l;
childL = L;
childR = R;
}
bool operator>(Node & r){
if(this->weight > r.weight)
return true;
return false;
}
};
//---Code---
struct Code {
string symbol;
char content;
};
//---HuffClass---
class Huff {
private:
typedef pair<char, int> c_pair;
vector<Code> code;
string content;
void copy_to(c_pair c);
public:
Huff(string);
~Huff();
string compress();
bool set_content();
string get_content();
string get_compress();
};
#endif
Huff.cpp
//---Include---
#include <iostream>
#include <vector>
#include "Huff.h"
#include <map>
#include <set>
using namespace std;
//---|+ -|---
Huff::Huff(string c): content(c){}
Huff::~Huff(){}
//---Compress---
struct CopyTo {
vector<Node*>* & nodes;
CopyTo(vector<Node*>* & c):nodes(c){}
void operator()(pair<char, int> c){
Node * n = new Node;
n->set_node(c.second, c.first, NULL, NULL);
nodes->push_back(n);
}
};
void show_freq(pair<char, int> p) {
cout << p.first << "\t" << p.second << endl;
}
/*void show_freq(Node* p) {
cout << p->litteral << "\t" << p->weight << endl;
}*/
string Huff::compress(){
vector<Node *>* nodes; // Vector of nodes for later use
map<char, int>* freq = new map<char, int>; // Map to find weight of nodes
for(int i = 0; i < content.length(); i++)
(*freq)[content[i]]++;
for_each(freq->begin(), freq->end(), show_freq);
CopyTo copyto(nodes); //Copy map elements to nodes in this and next one
for_each(freq->begin(), freq->end(), copyto);
delete freq;
Node p;
while(nodes->size() != 1){ //Sorts nodes by weight and then removes two of them and replaces them with one
sort(nodes->begin(), nodes->end());
vector<Node *>::iterator beg = nodes->begin();
int w= (**beg).weight + (**beg++).weight;
Node* p = new Node;
p->set_node(w, '*', *nodes->begin(), *(nodes->begin()++));
nodes->erase(nodes->begin(), nodes->begin()+2);
nodes->push_back(p);
//for_each(nodes->begin(), nodes->end(), show_freq);
cout << "--------------" << endl;
}
Node* root = *nodes->begin();
return "110";
}
Main.cpp
int main(){
Huff mike("Testing-");
mike.compress();
}

Where is including of algorithm header?
online compiler
results
Compilation output:
source.cpp: In member function 'std::string Huff::compress()':
source.cpp:76:39: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
source.cpp:94:11: warning: unused variable 'root' [-Wunused-variable]
Execution output:
- 1
T 1
e 1
g 1
i 1
n 1
s 1
t 1

Related

error: request for member ‘getdata’ in ‘*(& it)->__gnu_cxx::__normal_iterator<st**, std::vector<st*> >::operator->()’, *(it)->getdata();

Here is the code I am trying to creat a N object and store it into vector array. And trying to display the data of each object using Vector class . But Compiler is throwing an error. How to fixed it ???
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef struct st SLL;
struct st
{
int id;
char Name[10];
void setdata();
void getdata();
SLL * creatObject();
};
void SLL :: setdata()
{
cout << "Enter the Data\n";
cin >> id>> Name;
}
void SLL:: getdata()
{
cout << id << " " << Name << endl;
}
SLL * SLL:: creatObject()
{
SLL * newObject = new SLL();
newObject->setdata();
newObject->getdata();
return newObject;
}
int main()
{
std::vector<SLL*> v;
for (int i = 0; i < 3; ++i)
{
v.push_back(creatObject());
}
std::vector<SLL*> ::iterator it ;
for(it = v.begin(); it != v.end() ;it++)
{
*(it)->getdata();
}
}

Breadth First Search implementing to vector of Linked List

Can anybody explain me, how to do Breadth first search in the graph that uses vector of linked lists ?
My Graph header file:
#include <string>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
struct vertex {
string code;
vertex* next;
};
struct AdjList {
vertex *head;
AdjList(vertex* Given) {
head = Given;
}
};
class Graph {
map<string, string> associations;
int nodeNum; //amount of nodes or size of the graph;
vector<AdjList> adjList;
public:
Graph(int NodeNum);
~Graph();
int singleSize(string codeName);
int getSize();// must destroy every prerequisite list connected to the node
vertex* generateVertex(string codeName);
int getIndexOfVertex(vertex* givenVertex); // will find the location of the vertex in the array
void addVertex(vertex* newVertex);
void addEdge(string codeName, string linkCodeName);
void printPrerequisites(vertex* ptr, int i);
bool deleteVertex(string codeName);
bool deleteEdge(string codeName, string linkCodeName);
bool elemExistsInGraph(string codeName);
void printPrereq(string codeName);
void printCourseTitle(string codeName);
void printGraph();
};
I am trying to print all connected nodes within the graph using the breadth first search. Here is my code for the breadth first search algorithm that does not work.
void Graph::printPrereq(string codeName) {
int adjListSize = this->adjList.size();
int index = getIndexOfVertex(generateVertex(codeName));
bool visited[this->adjList.size()];
for(int i = 0; i < adjListSize; i++) {
visited[i] = false;
}
list<int> queue;
visited[index] = true;
queue.push_back(index);
while(!queue.empty()) {
index = queue.front();
vertex* pointer = this->adjList[index].head;
cout << pointer->code;
queue.pop_front();
while(pointer != nullptr){
if(!visited[getIndexOfVertex(pointer)]) {
queue.push_back(getIndexOfVertex(pointer));
visited[getIndexOfVertex(pointer)] = true;
}
cout << pointer->code <<"->";
pointer = pointer->next;
}
cout << "Null" << endl;
}
}
This algorithm outputs nodes that are only within the linked list, but not the ones that are connected through the graph.
Can anybody help and solve this problem?

C++ error expected primary-expression before '(' token

I am trying to create a program that takes N random nodes from user input and creates a random integer that is put into a binary tree and then copied into a priority queue. The integer becomes the key for each node and another integer counts the frequency of the key. I run into issues when I copy into the priority queue because I get duplicates and I need to remove them. I tried to create a set through the node constructor but I get the error above in the .cpp file.
#include <iostream>
#include <random>
#include <ctime>
#include <queue>
#include <set>
#include <functional>
#include <algorithm>
#include<list>
#include "Q7.h"
using namespace std;
int main()
{
node * root=NULL;
node z;
int n,v;
vector<int> first;
vector<int>::iterator fi;
default_random_engine gen(time(NULL));
cout<<"how many values? "; cin>>n;
for(int i=0; i<n; i++)
{ (v=gen()%n);
first.push_back(v);
if(root==NULL){root = node(set(v));}///This is where I get the error!!
else{
root->addnode(v);
}
}
z.unsortedRemoveDuplicates(first);
cout<<"Binary Tree in a depth first manner with Duplicates removed!"<<endl;
for ( fi = first.begin() ; fi != first.end(); ++fi{cout<<"Node "<<*fi<<endl;}
cout<<"-------------------"<<endl;
root->display();
cout<<"-------------------"<<endl;
cout<<"-------------------"<<endl;
root->display_Queue1();
cout<<"-------------------"<<endl;
return 0;
}
my .h file
class node
{
public:
node(){left=NULL; right=NULL; ct = 1;}
node set(int v) {val = v; left=NULL; right=NULL; ct=1;}
node (int Pri, int cat)
: val(Pri), ct(cat) {}
friend bool operator<(//sorts queue by lowest Priority
const node& x, const node& y) {
return x.val < y.val;
}
friend bool operator>(//sorts queue by greatest Priority
const node& x, const node& y) {
return x.ct > y.ct;
}
friend ostream&//prints out queue later
operator<<(ostream& os, const node& Pri) {
return os <<"my value = "<<Pri.val<<" occured "<<Pri.ct<<" times";
}
int unsortedRemoveDuplicates(vector<int>& numbers)
{
node set<int> seenNums; //log(n) existence check
auto itr = begin(numbers);
while(itr != end(numbers))
{
if(seenNums.find(*itr) != end(seenNums)) //seen? erase it
itr = numbers.erase(itr); //itr now points to next element
else
{
seenNums.insert(*itr);
itr++;
}
}
return seenNums.size();
}
priority_queue<node, vector<node>, greater<node> > pq;
priority_queue<node, vector<node>, less<node> > pq1;
void addnode(int v)
{
if(v==val){ct++;}
pq.emplace(node (set (v)));///No error here for set with constructor why??
pq.emplace(node (set (v)));
if(v<val)
{
if(left==NULL){left=new node(set(v));
}
else{left->addnode(v);
}
}
else
{
if(right==NULL){right = new node (set(v));
}
else{right->addnode(v);
}
}
}
int display()
{
if(left!=NULL){left->display();}
cout<<"frequency "<<ct<<" value"<<val<<endl;
if(right!=NULL){right->display();}
}
void display_Queue()
{
cout << "0. size: " << pq.size() << '\n';
cout << "Popping out elements from Pqueue..."<<'\n';
while (!pq.empty())
{
cout << pq.top() << endl;
pq.pop();
}
cout << '\n';
}
void display_Queue1()
{
cout << "0. size: " << pq1.size() << '\n';
cout << "Popping out elements from Pqueue..."<<'\n';
while (!pq1.empty())
{
cout << pq1.top() << endl;
pq1.pop();
}
cout << '\n';
}
private:
int val; ///value in that node
int ct;
///ct = count of that value
node * left;
node * right;
};
Congratulations, with this line:
root = node(set(v));
You have discovered why people here often say to avoid using using namespace std;. This is being interpreted as:
root = static_cast<node>(std::set(v));
Instead of what you want, which might be:
root = new node();
root->set(v);
First, note that we need to use new as we are creating a new node, not trying to cast a node to a node, which would have also given another compiler error about trying to assign a value to a pointer.
Next, note that you don't get the error in the header file as there is no using namespace std; there, and since it is in a member function, the line:
void node::addnode(int v)
{
//...
pq.emplace(node (set (v)));///No error here for set with constructor why??
//...
}
Is interpreted as:
pq.emplace(static_cast<node>(this->set(v)));
However, is this what you really want to do?
Furthermore, I would change the constructors to be:
public:
node (int Pri = 0, int cat = 1)
: val(Pri), ct(cat), left(NULL), right(NULL) {}
// DELETED node (int Pri, int cat)
Thus you can do:
root = new node(v);
And it will work as I think you expect it to.

Function converting variable Type to Type* creating error C++ [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I keep getting an error of:
In file included from user.h:3:0,
from sn.cpp:5:
'mylist.h: In member function ‘void MyList<L>::push_back(L) [with L = int]’:
user.h:38:30: instantiated from here
mylist.h:54:3: error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive]
mylist.h: In member function ‘void MyList<L>::push_back(L) [with L = User*]’:
sn.cpp:61:25: instantiated from here
mylist.h:54:3: error: cannot convert ‘User*’ to ‘User**’ in assignment
make: *** [sn.o] Error 1
I am creating a rudimentary social network where main takes 3 command line arguments - argv[1] is a GML file with nodes containing user information and edges that are user connections. argv[2] is another file that I have not yet processed. and argv[3] is a GML file that will contain basically a copy of the user information after it has been parsed and put into an ADT list MyList that I wrote, containing instances of User* that hold private data for user id, name, zip code, and age. For some reason my pushback function to add another item to my list is either making pointers double pointers or nonpointers pointers which creates the error above. I just cannot figure out where I need to remove a * or what I did wrong. the GML reader function populates two vectors nodes and edges with information such as
nodes[0] = id 0 name "Mark Redekopp" age 34 zip 90018
nodes[1] = id 1 name "Tommy Trojan" age 124 zip 90007
and
edges[0] = source 0 target 1
edges[1] = source 1 target 0
The code to write a new GML file is not included yet
sn file
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include "user.h"
#include "mylist.h"
#include "gmlreader.h"
using namespace std;
int main(int argc, char* argv[]){
if(argc < 4){
cerr << "Please provide the input GML file, command file, and output file" << endl;
return 1;
}
vector<string>nodes;
vector<string>edges;
GMLReader::read(argv[1], nodes, edges);
for(unsigned int i =0; i<nodes.size(); i++){
cout << "node[" << i << "]: " << nodes[i] << endl;
};
for(unsigned int i=0; i<edges.size(); i++){
cout << "edge[" << i << "]: " << edges[i] << endl;
cout << "printing an edge!" << endl;
};
cout << "about to create a mylist of users" << endl;
MyList<User*>Users;
cout << "initialized user list" << endl;
for(unsigned int i =0; i<nodes.size(); i++){
string TextBlob = nodes[i];
stringstream ss(TextBlob);
cout << "started string stream" << endl;
User* newuser = new User;
while(newuser->getName()=="" || newuser->getId()==0 || newuser->getZip()==0|| newuser->getAge()==0){
if (TextBlob.compare("name")==0){
string n;
ss>>n;
newuser->setName(n);
}
else if(TextBlob.compare("age")==0){
int a;
ss>>a;
newuser->setAge(a);
}
else if(TextBlob.compare("id")==0){
int d;
ss>>d;
newuser->setId(d);
}
else if(TextBlob.compare("zip")==0){
int z;
ss>>z;
newuser->setZip(z);
}
}
Users.push_back(newuser);
}
return 0;
};
mylist.h
#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
#ifndef MYLIST_H
#define MYLIST_H
using namespace std;
template<typename L>
class MyList{
private:
L* data_;
int len_;
int MAX_LIST_SIZE;
public:
MyList();
~MyList();
void push_back(L newVal);
int size();
L& at(int loc);
bool remove(L val);
L pop(int loc);
L& operator[](int loc);
void changeLen(int new_len){
len_=new_len;
}
};
int MAX_LIST_SIZE=100;
template<typename L>
MyList<L>::MyList(){
data_ = new L[MAX_LIST_SIZE];
len_=0;
};
template<typename L>
MyList<L>::~MyList(){
delete [] data_;
};
template<typename L>
void MyList<L>::push_back(L newVal){
if(len_==MAX_LIST_SIZE-1){
L* tempList = new L[MAX_LIST_SIZE*2];
for(int i=0; i<len_; i++){
tempList[i]=data_[i];
MAX_LIST_SIZE*=2;
}
tempList[len_++]=newVal;
data_=newVal;
}
data_[len_++]=newVal;
};
template<typename L>
int MyList<L>::size(){
return len_;
};
template<typename L>
L& MyList<L>::at(int loc){
if(loc > len_)
throw invalid_argument("Out of bounds");
return data_[loc];
};
template<typename L>
bool MyList<L>::remove(L val){
for(int i=0; i<len_; i++){
if(data_[i]==val){
for(int j=i; j<len_-1; j++){
data_[j]=data_[j+1];
}
changeLen(len_-1);
return true;
};
};
return false;
};
template<typename L>
L MyList<L>::pop(int loc){
if(loc>len_)
throw invalid_argument("Out of bounds");
L temp;
data_[loc] = temp;
for(int i=len_; i>=loc; i--){
data_[i-1]=data_[i];
};
changeLen(len_-1);
return temp;
};
template<typename L>
L& MyList<L>::operator[](int loc){
return data_[loc];
};
#endif
user.h
#ifndef USER_H
#define USER_H
#include "mylist.h"
class User{
public:
User(){
name_=""; age_ =0; zip_=0; id_=0;};
~User();
void setName(string name){
name_=name;
};
string getName(){
return name_;
};
void setAge(int age){
age_=age;
};
int getAge(){
return age_;
};
void setId(int id){
id_=id;
};
int getId(){
return id_;
};
void setZip(int zip){
zip_=zip;
};
int getZip(){
return zip_;
};
MyList<int> getFriends(){
return Friends;
};
void addFriend(int friendid){
Friends.push_back(friendid);
};
void printUser(){
cout<< "User Name: " << name_ << endl;
cout<< "User Age: " << age_ << endl;
cout<< "User's Friends: ";
for(int j=0; j<Friends.size(); j++){
cout <<Friends.at(j) << " ";
};
cout << endl;
};
private:
string name_;
int age_;
int id_;
int zip_;
MyList<int> Friends;
};
#endif
The issue is in push_back, specifically, this line:
data_=newVal;
newVal is an L, but data_ is an L*. I think what you meant to say is data_ = tempList.
Don't forget to delete the old value for data_, though.

How to get the min value of an object in a list (C++)

I've a question to ask.
So, I have a structure call Node as shown below:
struct Node
{
int xKoor, yKoor;
Node *parent;
char nodeId;
float G;
float H;
float F;
Node(int x, int y, int id, Node * par)
{
xKoor = x;
yKoor = y;
nodeId = id;
parent = 0;
}
Node(int x, int y, char id)
{
xKoor = x;
yKoor = y;
nodeId = id;
}
};
And I have list that contains elements of this structure:
list<Node*> OPEN;
This list's size varies in time.
What I need to do is to find the Node object which has the minimum F value, then pop out that object from the list.
So, I tried to write a function as shown below:
void enKucukFliNodeBul(list<Node*> OPEN)
{
list<Node*>::iterator it = OPEN.begin();
for(it = OPEN.begin(); it != OPEN.end(); it++)
{
if(it._Ptr->_Myval->F < it._Ptr->_Next->_Myval->F)
{
}
}
}
But I'm stuck. I'm new to STL. How can I solve this?
My best regards...
You can use std::min_element with a suitable comparison function for this.
bool nodeComp(const Node* lhs, const Node* rhs) {
return lhs->F < rhs->F;
}
#include <algorithm> // for std::min_element
list<Node*>::iterator it = std::min_element(OPEN.begin(), OPEN.end(), nodeComp);
This assumes that list<Node*> is std::list<Node*>, in which case you should be aware that std::list itself is a linked list.
Other useful operations, based on your comments:
Remove a minimum value node from the list and delete it:
OPEN.erase(it);
delete *it; //
You may need to perform other operations, if your nodes depend on each other.
Sort the list:
OPEN.sort(nodeComp);
use std::min_element algirithm and overload Compare function
bool compareF(Node *lhs, Node *rhs)
{
return lhs->F < rhs->F;
}
if you are using C++03:
std::<Node*>::itertor ter = std::min_element(OPEN.begin(),OPEN.end(), compareF);
if you are using C++11:
auto iter = std::min_element(OPEN.begin(),OPEN.end(), compareF);
To sort the list, you can call OPEN.sort(compareF); to sort your list with compareF function
Try adding this:
bool compare_node_F(Node* n1, Node* n2)
{
return n1-> F< n2-> F;
}
#include <list>
#include <algorithm>
#include <cstdlib>
#include <iostream>
int main()
{
std::list<Node*> nodes;
for(int i= 100; i--;)
{
Node* n= new Node(42, 42, 42);
n-> F= i;
nodes.push_back(n);
}
std::list<Node*>::iterator min_element_iter= std::min_element(nodes.begin(), nodes.end(), compare_node_F);
std::cout<< "Min F: "<< (*min_element_iter)-> F<< '\n';
for(std::list<Node*>::iterator d= nodes.begin(); d!= nodes.end(); ++ d)
delete *d;
}