I have a school project and I have to use the AM in the Student.h as a char*.The AM have to have numbers in it. I can't understand why what I am doing is not working.
Student.cpp
#include <iostream>
#include <string>
#include "Student.h"
using namespace std;
int main()
{
Student dlg;
dlg.AM[10]={2,1,3,9,0,2,6,6};
}
Student.h
#pragma once
#include <string>
using namespace std;
class Student
{
public:
char *AM[20];
string Name;
unsigned int Semester = 1;
};
If you really need your student number to be a char string, then you need to convert your ints to char* before assigning them to the array.
int main()
{
Student dlg;
int j = 0;
for (auto i : {2,1,3,9,0,2,6,6})
{
auto strInt { std::to_string(i) }; // create a C++ string containing a int
// next copy the internal memory of the C++ string to a read-writable memory buffer
// and assign a pointer to that buffer casted to a char* to the appropriate slot in the array
dlg.AM[j++] = static_cast<char*> (std::memcpy (new char[16], strInt.c_str(), strInt.size()));
}
// test
for (int i = 0; i < 8; i++)
{
cout << dlg.AM[i] << ' ';
}
}
Are you sure the student number should be a char* ?
Related
I have a vector of Workout objects, and I want to sort it by the prices of the workout (each Workout have const field price and getPrice function)
When Im trying to sort the array i get a C2280 error -
Workout &Workout::operator =(const Workout &)': attempting to reference a deleted function
#ifndef WORKOUT_H_
#define WORKOUT_H_
#include <string>
class Workout {
public:
Workout(int w_id, std::string w_name, int w_price, WorkoutType w_type);
int getPrice() const;
Workout& operator =(const Workout& other)
{
if (this == &other) return *this;
return *new(this) Workout(other.getId(), other.getName(),
other.getPrice(), other.getType());
}
private:
const int price;
};
I else have virtual class Customer and cheapCustomer object that inheritence from it, and function- order(const std::vector& workout_options) that needs to sort the vector by the prices.
Here is the Customer cpp file -
#include "Customer.h"
#include <algorithm>
using namespace std;
Customer::Customer(std::string c_name, int c_id) :name(c_name), id(c_id)
{
}
CheapCustomer::CheapCustomer(std::string name, int id) :Customer(name, id)
{
}
std::vector<int> CheapCustomer::order(const std::vector<Workout>& workout_options)
{
std::vector<int>* v = new std::vector<int>();
std::vector<Workout> tmp = workout_options;
std::sort(tmp.begin(), tmp.end(), [](const Workout& w1, const Workout& w2) {
return w1.getPrice() < w2.getPrice();
});
return *v;
//delete v
}
#include <vector>
#include "Customer.h"
#include "Trainer.h"
#include <algorithm>
using namespace std;
int main(int argc, char** argv) {
Workout w1 = Workout(1, "w1", 10, CARDIO);
Workout w2 = Workout(2, "w2", 20, CARDIO);
Workout w3 = Workout(3, "w3", 30, MIXED)
std::vector<Workout> v;
v.push_back(w1);
v.push_back(w2);
v.push_back(w3);
Customer* c_cheap = new CheapCustomer("Cheap", 20);
vector<int> order_cheap = c_cheap->order(v);
can some one please tell me how to fix it?
Thank you so much
I tried to use unique_ptr and still the same error-
C2280 'std::unique_ptr<Workout,std::default_delete>::unique_ptr(const std::unique_ptr<Workout,std::default_delete> &)': attempting to reference a deleted function
std::vector<int> CheapCustomer::order(const std::vector<Workout>& workout_options)
{
vector<int>* v = new std::vector<int>();
vector<unique_ptr<Workout>> v_unique_ptr;
for (Workout workout : workout_options) {
v_unique_ptr.push_back(unique_ptr<Workout>(new Workout(workout.getId(),workout.getName(),workout.getPrice(),workout.getType())));
}
std::sort(v_unique_ptr.begin(), v_unique_ptr.end(), [](unique_ptr<Workout> w1, unique_ptr<Workout> w2) {
return w1->getPrice() < w2->getPrice();
});
}
Edited:
its worked here
vector<int>* v = new std::vector<int>();
vector<unique_ptr<Workout>> v_unique_ptr;
for (Workout workout : workout_options) {
v_unique_ptr.push_back(move(unique_ptr<Workout>(new Workout(workout.getId(),workout.getName(),workout.getPrice(),workout.getType()))));
}
std::sort(v_unique_ptr.begin(), v_unique_ptr.end(), [](unique_ptr<Workout>& w1, unique_ptr<Workout>& w2) {
return w1->getPrice() < w2->getPrice();
});
v->push_back(v_unique_ptr[0]->getId());
return *v;
Thank you so much
In order to use std::sort, the element type needs to be move-assignable. Your element type isn't, because of all the const data members.
So you may either:
Remove the const
Provide your own move assignment operator that somehow gets around const
Don't place Workout objects in a container, place pointers instead (preferably smart pointers such as unique_ptr).
I keep getting this error. I know what function causes it, but don't know how to fix it. Looking up online from this post saying:
You need to pass a pointer to a dynamically allocated object, or make your own insde your chainLink class.
However, as I try to pass a string pointer. error still popping up. Here is my code.
#include <iostream>
#include "MWTNode.h"
#include "MWT.h"
using namespace std;
int main() {
MWT t;
string str ="abc";
string* strPtr = &str;
t.insert(strPtr);
std::cout << "Hello, World!" << std::endl;
return 0;
}
#include "MWTNode.h"
class MWT {
public:
MWTNode *root;
string find(const string &);
void insert(const string* string);
};
void MWT::insert(const string* word) {
MWTNode* curr = root;
MWTNode newNode;
string w = *word;
for (int i = 0; i < word->length(); i++) {
const char c = w[i];
if (curr->children.find(c) == curr->children.end()){
//curr->children[c]= MWTNode();
//node->frequency=node->frequency+1;
}
curr = &(curr->children[c]);
}
curr->flag = true;
}
#include <unordered_map>
#include <vector>
#include <string>
#include <sstream>
#include <set>
using namespace std;
class MWTNode {
public:
unordered_map<char, MWTNode> children;
string value;
bool flag;
int frequency;
MWTNode(const string &);
MWTNode(const char c);
MWTNode();
void setFrequency ();
int getFrequency ();
};
MWTNode::MWTNode(const string &val) {
value = val;
flag = false;
frequency = 0;
}
MWTNode::MWTNode(const char c) {
value =c;
flag = false;
frequency = 0;
}
MWTNode::MWTNode() {
value ="";
flag = false;
frequency = 0;
}
Lets highlight a few lines of the code you show
class MWT {
public:
MWTNode *root;
// ...
};
In that you declare the member variable root as a pointer.
void MWT::insert(const string* word) {
MWTNode* curr = root;
// ...
}
In the above you make curr point to where root is pointing.
But you never make root point anywhere! The MWT::root variable is uninitialized and will have an indeterminate value. Using this pointer in any way without initialization will lead to undefined behavior.
And yes you use this pointer, as you dereference curr inside the MWT::insert function.
It's a little unclear what you're doing (to me) but you need to make sure that root (and therefore curr) is a valid pointer before attempting to dereference it.
I have a function in Rcpp, which creates a very long map-structure within a class. I've given a simple example of it below:
#include <Rcpp.h>
using namespace Rcpp;
class A{
private:
std::map<int, int> m_map;
public:
void fill_map(const size_t limit){
for(size_t i=0; i<limit; ++i){
m_map[i] = i;
}
}
size_t size_map(){return m_map.size();}
};
// [[Rcpp::export]]
void func1(const size_t limit) {
A a;
a.fill_map(limit);
}
/* NOT WORKING */
// [[Rcpp::export]]
void func2(A a)
{
std::cout << a.size_map() << "\n";
}
/* NOT WORKING */
Say I call func1(1e7), which fills up the map in the a-object. I need to pass this A-object to other functions as shown above with func2.
However, my example with func2 doesn't work. Within the Rcpp-framework, what is the correct and most efficient approach to call func2 with an object defined in a previous function?
C++ code
#include <Rcpp.h>
using namespace Rcpp;
class A
{
private:
std::map<int, int> m_map;
public:
void fill_map(const size_t limit)
{
for(size_t i=0; i<limit; ++i)
{
m_map[i] = i;
}
}
size_t size_map(){return m_map.size();}
};
// [[Rcpp::export]]
XPtr<A> func1(const size_t limit)
{
XPtr<A> ptr(new A(), true);
ptr->fill_map(limit);
return(ptr);
}
// [[Rcpp::export]]
void func2(XPtr<A> ptr)
{
Rcout << ptr->size_map() << std::endl;
}
R code
a = func1(10)
func2(a)
a being an External pointer.
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <stdlib.h>
using namespace std;
struct trienode
{
map<char, struct trienode*> m;
bool endofword;
};
struct trienode* create_node()
{
struct trienode* new_node = (struct trienode*)malloc(sizeof(struct trienode));
new_node->endofword = false;
return new_node;
};
void word_insert(struct trienode* root, string word)
{
struct trienode* curr = root;
for (unsigned int i =0; i < word.size(); i++) {
if (curr->m.find(word[i]) == curr->m.end()) {
struct trienode* new_node = create_node();
***curr->m.insert(pair<char, struct trienode*>(word[i], new_node) );***
}
curr = curr->m.find(word[i])->second;
}
curr->endofword = true;
}
int main()
{
struct trienode* root = NULL;
root = create_node();
vector<string> v = {"aspirin", "aspetol", "astray", "atran", "chronic"};
for (unsigned int i =0; i < v.size(); i++) {
word_insert(root, v[i]);
}
}
I am trying to build a trie data structure to hold a set of strings. I have written a word_insert() function to insert a word into the trie. For inserting a word into the trie, I start at the root node, see if the map in the root node contains the char and if yes, I proceed to the next charachter. If the char is not present in the map of the node, I create another trienode and insert an entry into the map. However, when I am doing this, I see a problem with my code. My code hangs at the point where I try to insert the (char, struct trienode*) pair into the map.
Could someone tell me what is wrong with that? Thank you.
This program give below compiles properly by doing
g++ -o boostwrite boostwrite.cpp -lboost_system -lrt -lm -lpthread
with version g++ (Ubuntu 4.9.2-0ubuntu1~14.04) 4.9.2
Setting the unordered_map works well but getting the value of it does not work
For example on execution of the program
./boostwrite set
write valuebefore crash 1
test1=0.1
write valuebefore crash 2
test2=0.2
test1=0.1
write valuebefore crash 3
test3=0.4
test2=0.2
test1=0.1
But getting returns the size of map as zero
/boostwrite get
mymap address 0x7fb1ca8ad118
reading value
reading valuebefore crash
reading valuebefore crash 0
I am thinking there are 2 problems here
shared_memory_object::remove("MySharedMemory");
else if(strcmp(argv[1],"get")==0)
{
mymap = segment.construct("MyHashMap") //object name
( 30, boost::hash(), std::equal_to() //
But I dont know how to fix the problem ?
Any boost experts here to help ?
This program should work like
Header file
boostwrite.h
#ifndef BOOSTWRITE_H
#define BOOSTWRITE_H
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <iostream>
#include <boost/unordered_map.hpp> //boost::unordered_map
#include <functional> //std::equal_to
#include <boost/functional/hash.hpp> //boost::hash
using namespace boost::interprocess;
//Typedefs of allocators and containers
typedef managed_shared_memory::segment_manager segment_manager_t;
typedef allocator<void, segment_manager_t> void_allocator;
typedef allocator<char, segment_manager_t> char_allocator;
typedef basic_string<char, std::char_traits<char>, char_allocator> char_string;
typedef allocator<int, segment_manager_t> int_allocator;
typedef allocator<float, segment_manager_t> float_allocator;
typedef float complex_data;
//Definition of the map holding a string as key and complex_data as mapped type
typedef std::pair<const char_string, complex_data> map_value_type;
typedef allocator<map_value_type, segment_manager_t> map_value_type_allocator;
typedef boost::unordered_map < char_string, complex_data
, boost::hash<char_string > ,std::equal_to<char_string >
, map_value_type_allocator> complex_map_type2;
complex_map_type2 * mymap;
#endif
boostwrite.cpp file
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <iostream>
#include <boost/unordered_map.hpp> //boost::unordered_map
#include <functional> //std::equal_to
#include <boost/functional/hash.hpp> //boost::hash
#include "boostwrite.h"
managed_shared_memory segment(open_or_create,"MySharedMemory", 65530);
void_allocator alloc_inst (segment.get_segment_manager());
bool insert(string str,float value);
float readfloat(string str);
int main (int argc ,char** argv)
{
shared_memory_object::remove("MySharedMemory");
// remove_shared_memory_on_destroy remove_on_destroy("MySharedMemory");
if(strcmp(argv[1],"set")==0)
{
mymap = segment.construct<complex_map_type2>("MyHashMap") //object name
( 30, boost::hash<char_string>(), std::equal_to<char_string>() //
, segment.get_allocator<map_value_type>()); //allocator instance
insert("test1",0.1);
insert("test2",0.2);
insert("test3",0.4);
}
else if(strcmp(argv[1],"get")==0)
{
mymap = segment.construct<complex_map_type2>("MyHashMap") //object name
( 30, boost::hash<char_string>(), std::equal_to<char_string>() //
, segment.get_allocator<map_value_type>());
printf("mymap address %p \n",mymap);
// readfloat("test3");
}
return 0;
}
bool insert(string str,float value)
{
{
char_string key_object(str.c_str(), alloc_inst);
complex_data mapped_object(value);
map_value_type value(key_object, mapped_object);
mymap->insert(value);
}
printf("write valuebefore crash %ld \n",mymap->size());
for(complex_map_type2::iterator i = mymap->begin(); i != mymap->end(); ++i){
std::cout << i->first << "=" << i->second << std::endl;
}
}
float readfloat(string str)
{
printf("reading value\n");
typedef complex_map_type2::iterator iter;
char_string key_object(str.c_str(), alloc_inst);
printf("reading valuebefore crash\n");
iter got = mymap->find(key_object);
printf("reading valuebefore crash %ld \n",mymap->size());
}
There are 2 main problems here:
shared memory file is always being removed at program start
"get" part of the program constructs new map
To address these problems:
remove shared memory file in "set" part of the program just before creating new shared memory file (this will also require moving opennening or creating shared memory file into "set" and "get" parts)
in "get" find already created map
Your code fixed (your code is a bit of mess - I did not bother to fix other issues like not returning values from functions that require to return, etc.):
// ......
// #include's and other code
// .....
//managed_shared_memory segment(open_or_create,"MySharedMemory", 65530);
//void_allocator alloc_inst (segment.get_segment_manager());
bool insert(string str,float value, void_allocator &alloc_inst);
float readfloat(string str, void_allocator &alloc_inst);
int main (int argc ,char** argv)
{
try
{
//shared_memory_object::remove("MySharedMemory");
//remove_shared_memory_on_destroy remove_on_destroy("MySharedMemory");
if(strcmp(argv[1],"set")==0)
{
shared_memory_object::remove("MySharedMemory");
managed_shared_memory segment(open_or_create,"MySharedMemory", 65530);
void_allocator alloc_inst (segment.get_segment_manager());
mymap = segment.construct<complex_map_type2>("MyHashMap") //object name
( 30, boost::hash<char_string>(), std::equal_to<char_string>() //
, segment.get_allocator<map_value_type>()); //allocator instance
insert("test1",0.1, alloc_inst);
insert("test2",0.2, alloc_inst);
insert("test3",0.4, alloc_inst);
}
else if(strcmp(argv[1],"get")==0)
{
managed_shared_memory segment(open_or_create,"MySharedMemory", 65530);
void_allocator alloc_inst (segment.get_segment_manager());
mymap = segment.find<complex_map_type2>("MyHashMap") //object name
.first;
printf("mymap address %p \n",mymap);
readfloat("test3", alloc_inst);
}
}
catch(boost::interprocess::interprocess_exception &e)
{
printf("%s\n", e.what());
}
return 0;
}
bool insert(string str,float value, void_allocator &alloc_inst)
{
{
char_string key_object(str.c_str(), alloc_inst);
complex_data mapped_object(value);
map_value_type value(key_object, mapped_object);
mymap->insert(value);
}
printf("write valuebefore crash %ld \n",mymap->size());
for(complex_map_type2::iterator i = mymap->begin(); i != mymap->end(); ++i){
std::cout << i->first << "=" << i->second << std::endl;
}
}
float readfloat(string str, void_allocator &alloc_inst)
{
printf("reading value\n");
typedef complex_map_type2::iterator iter;
char_string key_object(str.c_str(), alloc_inst);
printf("reading valuebefore crash\n");
iter got = mymap->find(key_object);
printf("reading valuebefore crash %ld \n",mymap->size());
for(complex_map_type2::iterator i = mymap->begin(); i != mymap->end(); ++i){
std::cout << i->first << "=" << i->second << std::endl;
}
}
Output:
./boostwrite get
mymap address 0x7f80a724d118
reading value
reading valuebefore crash
reading valuebefore crash 3
test3=0.4
test2=0.2
test1=0.1