This might be something really simple but I can't seem to work it out. Within my Vertex I have a std::list<Edge> but when I try to call methods on it like push_front I get an error saying the list is const and I can't push into it. I think for some reason the compiler is converting the std::list<Edge> to a const std::list<Edge>. I know my code isn't set up very well but it's just homework so I'm taking a few shortcuts.
Header file:
#ifndef GRAPH_H
#define GRAPH_H
#include <set>
#include <list>
class Edge{
public:
unsigned int to;
unsigned int weight;
};
class Vertex{
public:
unsigned int id;
std::list<Edge> edges;
bool operator<(const Vertex& other) const{
return id < other.id;
}
};
class Graph{
public:
void add_vertex(unsigned int id);
void add_edge(unsigned int from, unsigned int to, unsigned int weight);
std::set<Vertex> get_vertices();
std::list<Edge> get_edges(unsigned int id);
private:
std::set<Vertex> _vertices;
unsigned int size = 0;
};
Lines causing the error:
void Graph::add_edge(unsigned int from, unsigned int to, unsigned int weight)
{
Vertex find_vert;
find_vert.id = from;
set<Vertex>::iterator from_v = _vertices.find(find_vert);
Edge new_edge;
new_edge.to = to;
new_edge.weight = weight;
from_v->edges.push_front(new_edge); // ERROR HERE
}
Compiler Error message from running g++ -c Graph.cpp:
Graph.cpp:23:38: error: passing ‘const std::list<Edge>’ as ‘this’ argument of ‘void std::list<_Tp,
_Alloc>::push_front(const value_type&) [with _Tp = Edge; _Alloc = std::allocator<Edge>; std::list<_Tp,
_Alloc>::value_type = Edge]’ discards qualifiers [-fpermissive]
The contents of a std::set are implicitly const, because changing the contents could invalidate their sort order.
That makes from_v implicitly const here.
set<Vertex>::iterator from_v = _vertices.find(find_vert);
And your error is telling you that you're trying to modify a const object.
from_v->edges.push_front(new_edge);
// ^^^^^^ const ^^^^^^^^^^ non-const behavior
Related
How to add object of class to vector in another class.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class info{
private:
int id;
string name;
public:
info(int extId, string extName) {
this->id = extId;
this->name = extName;
}
};
class db {
private:
vector<info> infoVector;
public:
void pushData(info * data) {
this->infoVector.push_back(&data);
}
};
int main(){
info * testData = new info(123, "nice");
db database;
database.pushData(testData);
return 0;
}
I am creating a object of info class. The object contains one int and one string variables. Then I am creating db object and I am passing there a testData object.
I got error message while building project.
main.cpp: In member function ‘void db::pushData(info*)’:
main.cpp:23:44: error: no matching function for call to ‘std::vector<info>::push_back(info*&)’
this->infoVector.push_back(data);
^
In file included from /usr/include/c++/5/vector:64:0,
from main.cpp:2:
/usr/include/c++/5/bits/stl_vector.h:913:7: note: candidate: void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = info; _Alloc = std::allocator<info>; std::vector<_Tp, _Alloc>::value_type = info]
push_back(const value_type& __x)
^
/usr/include/c++/5/bits/stl_vector.h:913:7: note: no known conversion for argument 1 from ‘info*’ to ‘const value_type& {aka const info&}’
What am I doing wrong?
It looks like you are trying to pass the address of an info * type to vector<info>::push_back, which only accepts types of const info & or info &&. Try using the dereference operator * instead of the address-of operator & when you call push_back:
this->infoVector.push_back(*data);
This isn't a great way to use pointers, however, and could lead to memory leakage or segfaults if data is removed from the vector or if it is deleted. It is better for the vector to own its members, so you might consider doing this instead:
class db {
private:
vector<info> infoVector;
public:
void pushData(info data) { // note: not a pointer
this->infoVector.push_back(data); // note: not address-of
}
};
int main(){
info testData(123, "nice"); // note: not a pointer
db database;
database.pushData(testData);
return 0;
}
Otherwise, if you really want infoVector to contain pointers, declare it as:
std::vector<info*> infoVector;
Then remove the address-to operator.
P.S., avoid using namespace std whenever possible!
You have vector<info> and you want to put info *, try to do:
int main(){
info testData(123, "nice");
db database;
database.pushData(testData);
return 0;
}
I have seen similar questions asked and tried their solutions but the answers to them do not seem to work. I have the following code:
.h
#include <iostream>
#include <vector>
#include <string>
using std::string; using std::vector;
struct DialogueNode;
struct DialogueOption {
string text;
DialogueNode *next_node;
int return_code;
DialogueOption(string t, int rc, DialogueNode * nn) : text{t},
return_code{rc}, next_node{nn} {}
};
struct DialogueNode {
string text;
vector <DialogueOption> dialogue_options;
DialogueNode();
DialogueNode(const string &);
};
struct DialogueTree {
DialogueTree() {}
void init();
void destroyTree();
int performDialogue();
private:
vector <DialogueNode*> dialogue_nodes;
};
.cpp
#include "dialogue_tree.h"
DialogueNode::DialogueNode(const string &t) : text{t} {}
void DialogueTree::init() {
string s = "Hello";
for(int i = 0; i < 5; i++) {
DialogueNode *node = new DialogueNode(s);
dialogue_nodes.push_back(node);
delete node;
}
}
void DialogueTree::destroyTree() {
}
int DialogueTree::performDialogue() {
return 0;
}
int main() {
return 0;
}
I get the error: error: no matching function for call to ‘DialogueNode:: DialogueNode(std::__cxx11::string&)’ DialogueNode *node = new DialogueNode(s);
EDIT additional notes on error
dialogue_tree.h:17:8: note: candidate: DialogueNode::DialogueNode()
dialogue_tree.h:17:8: note: candidate expects 0 arguments, 1 provided
dialogue_tree.h:17:8: note: candidate: DialogueNode::DialogueNode(const DialogueNode&)
dialogue_tree.h:17:8: note: no known conversion for argument 1 from ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to ‘const DialogueNode&’
dialogue_tree.h:17:8: note: candidate: DialogueNode::DialogueNode(DialogueNode&&)
dialogue_tree.h:17:8: note: no known conversion for argument 1 from ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to ‘DialogueNode&&’
Which makes no sense to me because I have the constructor defined to take a string as an argument.
You've declared your constructor as:
DialogueNode(const string);
But defined it as:
DialogueNode(const string &t);
Those two aren't the same; the former takes a const string while the latter takes a const string reference. You'll have to add the & to specify a reference argument:
DialogueNode(const string &);
it is because in the constructor you are specifying that the parameter will be a string of constant type and when creating an object you are passing a string. The type mismatch is the problem, either fix the constructor parameter to string or change when you are creating an object.
I write too simple odb example and copy all codes from document but when calling db.persist(john) compiler say
/usr/include/odb/traits.hxx: In instantiation of ‘struct odb::object_traits_impl’:
/usr/include/odb/database.txx:61:28: required from ‘typename odb::object_traits::id_type odb::database::persist_(const typename odb::object_traits::pointer_type&) [with T = Person; odb::database_id DB = (odb::database_id)1; typename odb::object_traits::id_type = odb::access::object_traits::id_type; typename odb::object_traits::pointer_type = Person*]’
/usr/include/odb/sqlite/database.ixx:47:37: required from ‘typename odb::object_traits::id_type odb::sqlite::database::persist(T*) [with T = Person; typename odb::object_traits::id_type = odb::access::object_traits::id_type]’
/home/mohsen/Desktop/Workstation/Projects/C++/Rubik/main.cpp:25:21: required from here
/usr/include/odb/traits.hxx:177:10: error: invalid use of incomplete type ‘class odb::access::object_traits_impl’
struct object_traits_impl:
what is wrong ?
my codes:
main.cpp
using namespace std;
using namespace odb::core;
int main(int argc, char **argv) {
odb::sqlite::database db("sqlite.db", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);
Person john("John", "Doe", 33);
// Person jane("Jane", "Doe", 32);
// Person joe("Joe", "Dirt", 30);
// odb::transaction t(db.begin());
db.persist(john);
// t.commit();
return 0;
}
Person.h
#pragma db object
class Person
{
public:
Person (const std::string& first,
const std::string& last,
unsigned short age)
: first_ (first), last_ (last), age_ (age)
{
}
const std::string&
first () const
{
return first_;
}
const std::string&
last () const
{
return last_;
}
unsigned short
age () const
{
return age_;
}
void
age (unsigned short age)
{
age_ = age;
}
private:
friend class odb::access;
Person () {}
#pragma db id auto
unsigned long id_;
std::string first_;
std::string last_;
unsigned short age_;
};
odb compile command
odb -dsqlite --generate-query --generate-session --generate-schema --generate-prepared --output -dir/home/mohsen/Desktop/Workstation/Projects/C++/Rubik/cmake-build-debug/odb_gen --hxx-suffix.h --ixx-suffix_inline.h --cxx-suffix.cpp --odb-file-suffix_odbPerson.h
You are getting this error because ‘class odb::access::object_traits_impl<Person, (odb::database_id)1>’ is defined in the file Person-odb.hxx generated by odb.
Including "Person-odb.hxx" at the beginning of your main.cpp file would solve your problem.
abstract base class:
#ifndef BUILDINGORG_H
#define BUILDINGORG_H
#include <iostream>
#include <memory>
#include <vector>
class BuildingOrg
{
public:
BuildingOrg(int _id);
virtual int addBuildingComponent(std::shared_ptr<BuildingOrg> buildingOrg,
std::string _type) const;
virtual void removeBuildingComponent(std::shared_ptr<BuildingOrg> buildingOrg);
virtual void getInfo()=0;
private:
int id;
std::string type;
};
#endif // BUILDINGORG_H
concrete subclass:
#ifndef BUILDINGCOMPONENT_H
#define BUILDINGCOMPONENT_H
#include "buildingorg.h"
class BuildingComponent : public BuildingOrg
{
public:
BuildingComponent(int _id);
int addBuildingComponent(std::shared_ptr<BuildingOrg> _buildingOrg,
std::string _type) const override;
void removeBuildingComponent(std::shared_ptr<BuildingOrg> buildingOrg)
override;
void getInfo() override;
private:
std::vector<std::shared_ptr<BuildingOrg>> building_Org;
};
#endif // BUILDINGCOMPONENT_H
Implementation of subclass:
#include "buildingcomponent.h"
BuildingComponent::BuildingComponent(int _id):
BuildingOrg(_id)
{
}
int BuildingComponent::addBuildingComponent(std::shared_ptr<BuildingOrg> _buildingOrg, std::string _type) const
{
building_Org.push_back(_buildingOrg);// I am having error here
return 1;
}
void BuildingComponent::removeBuildingComponent(std::shared_ptr<BuildingOrg> buildingOrg)
{
}
void BuildingComponent::getInfo()
{
}
When I try to put shared pointer in my Vector I get this nasty error;
I really don't know why I am getting the error:
cpp:10: error: passing 'const std::vector<std::shared_ptr<BuildingOrg> >' as 'this' argument of 'void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::shared_ptr<BuildingOrg>; _Alloc = std::allocator<std::shared_ptr<BuildingOrg> >; std::vector<_Tp, _Alloc>::value_type = std::shared_ptr<BuildingOrg>]' discards qualifiers [-fpermissive]
building_Org.push_back(_buildingOrg);
I don’t understand what is it saying.
The const in int addBuildingComponent(std::shared_ptr<BuildingOrg> _buildingOrg, std::string _type) const override; is a promise that addBuildingComponent will not change BuildingComponent. However, it tries to modify the member variable building_Org with the push_back()...
Removing the const from addBuildingComponent() should fix the error.
The discards qualifiers part of the error message refers to the conflict with the const qualifier of the member function.
C++ template related error messages can be notoriously difficult to parse at first, but it does get easier with practice :-)
You defined BuildingComponent::addBuildingComponent method as const (i.e. that it won't change member varialbles), but you are adding passed in value to a member list (i.e. changing the member variable).
addBuildingComponent() is a const method. within its scope, *this is const, and so this->building_Org is const.
std::vector::push_back() is a non-const method. So it can't be called in a context where the vector is const.
Problem
I want to assign values in a class definition which is in a separate header file from the class declaration cpp.
On compilation I recieve theses error messages:
error: ‘const std::map<unsigned int, std::basic_string<char> > bob::mRegexes’ is not a static member of ‘class bob’const std::map<uint,std::string> bob::mRegexes = {
^
error: ‘const std::map<unsigned int, std::basic_string<char> > bob::mResponses’ is not a static member of ‘class bob’ const std::map<uint,std::string> bob::mResponses = {
both of which have been absolutely infurriating because I do not understand why the compiler is ignoring thetypedef for std::string I feel like I'm missing something here but I'm not sure why the bob.h file is seeing the parameters differently than the bob.cpp.
bob.h
#ifndef BOB_H
#define BOB_H
#include <iostream>
#include <string>
#include <boost/regex.hpp>
#include <map>
typedef unsigned int uint;
// This was first to go when I started having problems.
/*using std::string;*/
using std::map;
// boost::regex > c++11::regex (gcc doesn't follow standards).
using boost::regex;
class bob
{
enum respond_to{
QUESTION,
YELL,
NAME,
DEFAULT,
LENGTH
};
public:
static const respond_to mResponseTypes;
static const map<uint,std::string> mRegexes;
static const map<uint,std::string> mResponses;
static std::string hey(std::string sentence);
static const std::string* evaluate (const std::string& sentence);
static const std::string* getResponse(const std::string& sentence, const respond_to& type) noexcept(true);
};
#endif
bob.cpp
#include "bob.h"
const std::map<uint,std::string> bob::mRegexes = {
{QUESTION, "[a-z]+\\?"},
{YELL,"[A-Z]+"}
};
const std::map<uint,std::string> bob::mResponses = {
{QUESTION,"Sure"},
{YELL,"Whoah, chill out!"},
{DEFAULT,"Whatever."}
};
// ...