Is there a way to force C++17 to convert a nullptr return value safely so that the return type is deduced as a pointer of type T assuming that all branches return either T* or nullptr?
samedi 30 septembre 2017
Is it possible to multiply mpz_class and mpf_class?
I am using GMP lib and I currently have mpz_class integers around 10^5000 and mpf_class floats around 10^-6000. I am wondering if there is a way to multiply these, as that is what I need done. I may be missing something but I don't see anything in the documentation about getting something like this accomplished. I also don't see anything about converting mpz to mpf or vice versa. Any help is appreciated
Passing unique_ptr
I need to pass a unique pointer to a derived class by reference to a function which accepts a reference to a unique pointer to the base class, like here:
#include <memory>
using namespace std;
class Base {};
class Derived : public Base {};
void foo(std::unique_ptr<Base>& d){}
int main()
{
unique_ptr<Derived> b = make_unique<Derived>();
foo(b);
}
-
Why doesn't this code work? I checked out other posts like this one, and the answer seems to be "because C++ wants the types to match exactly", but why is that? What dangerous situation am I potentially creating?
-
If I instead do this, it compiles:
void foo(unique_ptr<Base>&& d){} foo(move(b));
Is this a reasonable approach?
c++11 move constructor and move assigment usage
I try to figure out when move constructor and move assignment constructor is used, my code is:
class A {
public:
A(int p) {
printf("constructor\n");
ptr = new int(p);
}
~A() {
delete ptr;
ptr = nullptr;
}
A(const A& a) {
if (ptr == a.ptr) {
return;
} else {
delete ptr;
ptr = a.ptr;
}
}
A(A&& a) {
printf("move constructor\n");
if (ptr == a.ptr) {
a.ptr = nullptr;
return;
} else {
ptr = a.ptr;
a.ptr = nullptr;
}
}
A& operator=(A&& a) {
printf("move assign constructor\n");
if (ptr == a.ptr) {
a.ptr = nullptr;
return *this;
} else {
ptr = a.ptr;
a.ptr = nullptr;
}
return *this;
}
void print() {
if (ptr) {
printf("value = %d\n", *ptr);
} else {
printf("empty value\n");
}
}
private:
int* ptr;
};
this is my simple class support move operate. and I use a function to test it:
void f(A&& a) {
printf("f begin------->\n");
A al = std::move(a);
printf("f end------->\n");
}
int main () {
A a1(1);
f(std::move(a1));
a1.print();
return 0;
}
the out put is OK:
constructor
f begin------->
move constructor
f end------->
empty value
but if I try to use move assignment by change f() like this:
void f(A&& a) {
printf("f begin------->\n");
A al = a;
printf("f end------->\n");
}
Oops:
constructor
f begin------->
*** Error in `./test': free(): invalid pointer: 0x00007ffd64fb7280 ***
Aborted
It is supposed to use move assignment, but fail with a invalid pointer. That is why?
Pre-C++14 template metaprogramming and ternary operator
From cppreference.com:
Such conditional operator was commonly used in C++11 constexpr programming prior to C++14.
std::string str = 2+2==4 ? "ok" : throw std::logic_error("2+2 != 4");
What does cppreference refer to? What was the pre-C++14 idiom and why in C++14 that technique is no longer relevant?
Perfect forwarding of return values, undefined behaviour?
I have a set of functions where I employ template specialisation to perform transforms on certain values. However, for many types I want to pass the values through unchanged.
To pass a value unchanged I have something like the following function as the default:
template< typename arg >
arg&& convert( arg&& x )
{
return std::forward( x );
}
This seems great but according to the answer here it runs the risk of leaving a dangling reference in a statement like:
int&& x = convert( 5 );
If I only use this inline in function arguments, is this risk avoided?
For example, do I run into undefined behaviour if I do something like...
void foo( int&& x )
{
// Do something with x...
}
foo( convert( x ) );
C++ Private Inner Class
I have a question about privately defined inner class
#pragma once
#ifndef CIRCULAR_ARRAY_H
#define CIRCULAR_ARRAY_H
class CircularArray
{
private:
class Node
{
private:
int data;
Node* next;
public:
Node(int val, Node* next) : data(val), next(next) {}
~Node() { delete[] next; }
int get_data(void);
};
Node* head;
public:
Node* add(int data, Node* next);
};
Node* CircularArray::add(int data, Node* next)
{
}
#endif
Why am I unable to access Node in the method definition CircularArray::add
? I thought that a private inner class Node would be accessible to CircularArray because private members of a class are visible to the class the same way they are visible to a derived class? Is there an exception when that private member is a class?
Does c++ not support private inner classes like Java? Do I have to publicize inner classes for their members to be accessible?
c++11 inheritance : public BaseClass
I'm not familiar with the c++11 inheritance notation :public BaseClass
I see in
Stroustruup's C++ Programming Language
I thought specifying public before the base class name would publicize the base class members. However, it doesn't and I have to publicize them myself using public:
What is the purpose of :public BaseClass
? I wrote some code to try and understand this
#pragma once
#ifndef ARITHMETIC_H
#define ARITHMETIC_H
class Arithmetic
{
virtual void* add(void* operand_one, void* operand_two) = 0;
virtual void* subtract(void* operand_one, void* operand_two) = 0;
virtual void* multiply(void* operand_one, void* operand_two) = 0;
virtual void* divide(void* numerator, void* denominator) = 0;
virtual ~Arithmetic() {}
};
#endif
#pragma once
#ifndef MATH_H
#define MATH_H
#include "Arithmetic.h"
class Math : public Arithmetic
{
public:
void* add(void* operand_one, void* operand_two);
void* subtract(void* operand_one, void* operand_two);
void* multiply(void* operand_one, void* operand_two);
void* divide(void* numerator, void* denominator);
Math();
~Math();
};
void* Math::add(void* operand_one, void* operand_two)
{
}
void* Math::subtract(void* operand_one, void* operand_two)
{
}
void* Math::multiply(void* operand_one, void* operand_two)
{
}
void* Math::divide(void* numerator, void* denominator)
{
}
Math::Math() // can't; base class constructor is private
{
}
Math::~Math() // can't; base class destructor is private
{
}
#endif
What does :public BaseClass
do?
Error when compiling multi-threaded C++ though my function arguments are fine
After reading several articles on SO about similar errors, I however was unsuccessful to understand the cause behind these errors. The error I get on compiling on VS 2015 I get are :
Severity Code Description Project File Line Suppression State Error C2893 Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)' Busy_Waiting c:\program files (x86)\microsoft visual studio 14.0\vc\include\thr\xthread 240
Severity Code Description Project File Line Suppression State Error C2672 'std::invoke': no matching overloaded function found Busy_Waiting c:\program files (x86)\microsoft visual studio 14.0\vc\include\thr\xthread 240
#include "stdafx.h"
#include "iostream"
#include "thread"
using namespace std;
class Node
{
public:
int value;
public:
Node *next;
Node(int val);
};
Node::Node(int val)
{
value = val;
}
class tQueue {
public:
Node *front;
Node *rear;
Node *prev;
public:
~tQueue();
void enqueue(int val);
Node* dequeue();
void display();
};
void tQueue::enqueue(int val)
{
Node* temp;
temp = new Node(val);
if (front == NULL)
{
front = temp;
rear = temp;
prev = temp;
}
else
{
prev = rear;
rear->next = temp;
rear = rear->next;
}
}
Node* tQueue::dequeue() {
prev = front;
while (prev->next != rear)
{
prev = prev->next;
}
if (rear != NULL) {
rear = prev;
delete rear->next;
rear->next = NULL;
}
return rear;
}
void tQueue::display() {
Node* iter = front;
while (iter != NULL) {
cout << iter->value;
iter = iter->next;
}
}
tQueue::~tQueue() {
delete this;
}
int main()
{
//tQueue<int> obj ;
std::thread t1(&tQueue::enqueue, 1);
std::thread t2(&tQueue::enqueue, 2);
t1.join();
t2.join();
return 0;
}
How to create a map of std::ofstream objects
How can I create a map of std::ofstream objects in c++? I have tried solutions from other related questions, but I keep getting a segmentation fault. The problem is occurring in my openFile function.
I found another question relating to this, and tried using map::emplace, but I got a segmentation fault: 36817 Segmentation fault: 11
Is it possible to handle std::ofstream with std::map?
This is my header file:
#include <fstream>
#include <iostream>
#include <map>
#ifndef WRITE_FILES_H
#define WRITE_FILES_H
typedef std::map<int, std::ofstream> FileMap;
class writeFiles {
public:
static void openFile (int num);
static void writeTextFile (int num, string dataWrite, bool append);
static void closeAllFiles ();
private:
static std::string getName (int num);
static FileMap fileMap;
};
#endif
Here is my cpp file:
#include "writeFiles.h"
FileMap writeFiles::fileMap = {};
void writeFiles::writeTextFile (int num, std::string dataWrite, bool append) {
if (!fileMap.count(num)) {
openFile(num);
}
if (!append) {
fileMap[num].close();
std::ofstream w;
w.open(getName(num), std::fstream::out);
w << dataWrite;
fileMap[num].open(getName(num), std::fstream::out | std::fstream::app);
} else {
fileMap[num] << dataWrite;
}
}
void writeFiles::openFile (int num) {
fileMap.emplace(num, std::ofstream(getName(num)));
}
void writeFiles::closeAllFiles () {
for (auto const &ent : fileMap) {
ent.second.close();
}
}
std::string writeFiles::getName (int num) {
return "./temp/matrix/matrix" + std::to_string(num) + ".txt";
}
Interesting use-case where a regular array cannot stand-in for a std::array
This comes across as an interesting use-case of a std::array over a regular array: somewhere where I cannot change the syntax to work for a regular array (or so I have convinced myself).
#include <iostream>
#include <algorithm>
#include <array>
#include <map>
using namespace std;
int main()
{
int n, c = 0; cin >> n;
array<int, 3> tri;
map<array<int, 3>, int> freq;
while (n--)
{
cin >> tri[0] >> tri[1] >> tri[2];
sort(begin(tri), end(tri));
freq[tri]++;
}
for (auto i : freq)
{
cout << &i.first << ' ' << i.second << endl;
if (i.second == 1)
{
c++;
}
}
cout << c;
}
When I try to switch the std::array over with a regular int[3]
, and the map template parameters to map<int*, int>
, the program seems to make the map freq
reuse tri
, even if I put it inside the while loop, as if an optimization.
Note that for working with map<int*, int>
the statement for printing the map's contents would be
cout << i.first << ' ' << i.second << endl;
My question is, why isn't the std::array experiencing technical difficulties here? What is the hidden magic underneath the freq[tri]++
statement?
Here's where I found the code.
template, well formedness and zero pack length rule
From the accepted answer of a previous question I've discovered a rule I didn't know about templates and well formedness
The program is ill-formed, no diagnostic required, if:
- [...]
- every valid specialization of a variadic template requires an empty template parameter pack, or
- [...]
According this rule (if I understand correctly), the following template function is ill-formed
template <typename ... Ts>
int foo (std::tuple<Ts...> const &)
{ return std::get<sizeof...(Ts)>(std::tuple<int>{42}); }
because the only valid specialization require and empty Ts...
parameter pack.
But (maybe because I don't know English very well) I'm not sure to understand this rule in case of a template with two ore more parameter packs.
I mean... the following foo()
function
#include <tuple>
#include <iostream>
template <typename ... Ts, typename ... Us>
int foo (std::tuple<Ts...> const &, std::tuple<Us...> const &)
{ return std::get<sizeof...(Ts)+sizeof...(Us)-1U>(std::tuple<int>{42}); }
int main ()
{
auto t0 = std::tuple<>{};
auto t1 = std::tuple<int>{0};
//std::cout << foo(t0, t0) << std::endl; // compilation error
std::cout << foo(t0, t1) << std::endl; // print 42
std::cout << foo(t1, t0) << std::endl; // print 42
//std::cout << foo(t1, t1) << std::endl; // compilation error
}
is well-formed or ill-formed?
Because a valid specialization of it require that Ts...
or Us...
is empty (and that the other parameter pack is exactly of size 1).
The rule should be interpreted in the sense that a programm is ill-formed if there is an empty parameter pack that must be ever empty (so my example should be well formed because both parameter packs can be not empty) or in the sense that is ill-formed if in every specialization there is at least an empty parameter pack, not necessarily the same in every specialization (so my example should be ill-formed) ?
Creating shared pointer from this pointer
Below code gives segmentation fault as expected.
struct B{
shared_ptr<B> createShared(){ return shared_ptr<B>(this);}
};
int main()
{
shared_ptr<B> p1 = make_shared<B>();
shared_ptr<B> p2 = p1->createShared();
return 0;
}
but when I change the code
shared_ptr<B> p1 = make_shared<B>();
to
shared_ptr<B> p1(new B);
program compiles as runs without any crash.
Can someone explain me what exactly is causing the change in behavior between these two cases.
Note:- I know that it is not the right way to create the shared pointer from this pointer, what I am looking for is the reason for change in behavior. Compiler I used is clang++-3.8 and g++-5.4.
What does 'char (&) [13]' mean?
As an old c++ programmer, I'm learning c++11 recently. When reading Effective Mordern C++, I found the interesting type:
char (&) [13]
When passing an array to a function template requiring T&:
template<typename T>
void funcTemplate1(T& param)
{
std::cout << boost::typeindex::type_id_with_cvr<T>().pretty_name() << std::endl;
}
void main()
{
char szHello[] = "Hello, World";
funcTemplate1(szHello);
}
It output :
char (&) [13]
Never have seen that. What does is mean?
vendredi 29 septembre 2017
Why is the copy constructor called when initializing and resizing a vector?
I am trying to understand better how copy and move constructors work, so I wrote this piece of code:
#include <iostream>
#include <vector>
class MyClass {
public:
int x;
MyClass(int i) : x(i) {
std::cout << "Standard constructor - x=" << x << std::endl;
}
MyClass(const MyClass& other) : x(other.x) {
std::cout << "Copy constructor - x=" << x << std::endl;
}
MyClass(MyClass&& other) : x(other.x) {
std::cout << "Move constructor - x=" << x << std::endl;
}
~MyClass() {}
};
int main() {
std::cout << " Initialization list:" << std::endl;
std::vector<MyClass> v {MyClass(1), MyClass(2)};
std::cout << " push_back:" << std::endl;
v.push_back(MyClass(3));
std::cout << " emplace_back:" << std::endl;
v.emplace_back(4);
return 0;
}
And here is what I obtained, using g++ version 4.8.4, on Ubuntu 14.04:
$ g++ -std=c++11 -o my_prgm my_file.cpp && ./my_prgm
Initialisation list:
Standard constructor - x=1
Standard constructor - x=2
Copy constructor - x=1
Copy constructor - x=2
push_back:
Standard constructor - x=3
Move constructor - x=3
Copy constructor - x=1
Copy constructor - x=2
emplace_back:
Standard constructor - x=4
There are a few things that are not clear to me:
-
When initializing the vector, why is the copy constructor called? I thought that
MyClass(.)
, being an rvalue, would be moved rather than copied. -
When calling
push_back
, I assume that there is some kind of resizing that happens in the background, which is why two new objects are created. However I do not understand why, once again, the copy constructor is used instead of the move constructor.
gcc std::regex with -fpack-struct seg faults
Consider the following simple c++ program
#include <iostream>
#include <regex>
int main(int argc, char * argv[])
{
std::regex foobar( "[A]+");
return 0;
}
When compiling with -fpack-struct=1 it seg faults
g++-5 -std=gnu++14 ./fpack_regex.cpp -fpack-struct=1 -o a.out && a.out
Segmentation fault (core dumped)
While
g++-5 -std=gnu++14 ./fpack_regex.cpp -o a.out && a.out
works just fine.
Any clue why the pack-struct=1 option might cause this failure?
C++ Getters/Setters
Lots of information on Stack about this and good advice here and also non-stack there not to forget this but, as a Java programmer, it feels as if Gosling is standing behind me with paddle when I consider making instance members public to avoid getters.
I know there are many schools of thought on this from using friend
declarations to many different flavors and styles of getter/setter. Is it an acceptable practice always for private variables to have a getter (or setter if needed).
What specifically should I consider regarding their avoidance using simple rules. I think the answers given above are good but add complexity to the decision.
Linked List ostream overload weird values
I'm realitively new to using linked lists. I'm trying to overload the ostream opperator for a doubly linked list with decleration :
template <class T>
class DynamicList;
template <class T>
template <class T>
class DynamicList
{
private:
Node<T> *head;
public:
class Node
{
public:
T* value;
Node<T> *next;
Node<T> *prev;
Node(T val)
{
next = nullptr;
prev = nullptr;
value = &val;
}
};
DynamicList();
~DynamicList();
void operator+=(const T);
friend std::ostream & operator<< <>(std::ostream &, const DynamicList<T> &);
};
and function defenition:
template <class T>
ostream& operator << (ostream & out , const DynamicList<T> & rhs)
{
Node<T>* nodePtr = rhs.head;
Node<T>* nptr = nodePtr->next;
while(nodePtr != NULL)
{
cout<<*(nodePtr->value)<<" ";
nodePtr = nodePtr->next;
}
out<<endl;
return out;
}
template <class T>
void DynamicList<T>:: operator +=(const T val)
{
Node<T>* nodePtr = nullptr;
T vall = val;
Node<T>* newNode = new Node<T>(vall);
if(!head)
{
head = newNode;
}
else
{
nodePtr = head;
while((nodePtr->next))
{
nodePtr = nodePtr->next;
}
nodePtr->next = newNode;
newNode->prev = nodePtr;
}
Every time I'm calling the opperator it gives a weird output for example using:
for(int i = 1; i <= 3; i++)
{
list += i;
}
cout<<list;
It would give an output like 135727363 135727383 135727383 ,I'd just like to know what I'm doing wrong and possibly how I could solve it
C++11 Strange notation [0:size())
Am I to understand from
Stroutrup C++ Programming Language - Invariants
that the notation above is a range initializer or is this interpretive instruction to convey mathematically that the Vector class array range is between 0 and some predetermined size?
Should I even be using this book because it contains errors such as accessing a struct member from a variable of that struct using .
instead of ->
?
difference in output using std::size_t and std::bitset for bit operations
Having following code:
#include <iostream>
#include <bitset>
#include <limits>
#include <limits.h>
using namespace std;
constexpr std::size_t maxBits = CHAR_BIT * sizeof(std::size_t);
int main() {
std::size_t value =47;
unsigned int begin=0;
unsigned int end=32;
//std::size_t allBitsSet(std::numeric_limits<std::size_t>::max());
std::bitset<maxBits> allBitsSet(std::numeric_limits<std::size_t>::max());
//std::size_t mask((allBitsSet >> (maxBits - end)) ^(allBitsSet >> (maxBits - begin)));
std::bitset<maxBits> mask = (allBitsSet >> (maxBits - end)) ^(allBitsSet >> (maxBits - begin));
//std::size_t bitsetValue(value);
std::bitset<maxBits> bitsetValue(value);
auto maskedValue = bitsetValue & mask;
auto result = maskedValue >> begin;
//std::cout << static_cast<std::size_t>(result) << std::endl;
std::cout << static_cast<std::size_t>(result.to_ulong()) << std::endl;
}
Which in fact should return the same value as value
, but for some reason the version with std::bitset
works just fine and version with std::size_t
does not.
It is strange as such, because AFAIK std::bitset
, when something is wrong simply throws exception and what is more AFAIK bitset should behave the same way as operations on unsigned integers, but as we can see even if bitset has same number of bits it does not behave the same. In fact it seems for me, that std::bitset
works fine, while std::size_t
does not.
My configuration is: intel corei7 - g++-5.4.0-r3
Fibonacci Series Using One variable
I digged in StackOverflow for about 10 minutes but I found no other question related this.
Problem: I am trying to print the fibonacci using one variable,
Tried: I am little bit confused as I use recursion :
I have to print the value when I reach the minimal value thats if var = 0 return 0;
in upwards direction thats 0,1,1,2,3,5,7 ... plus at that time I have to return that value.
I can do something (Algorithm):
var = fab( n- 1 ) + fab(n-2)
Print var
Return var
But I have only to use one variable.
Adding an extra behavior to old code
I need a design input on a programming problem I'm trying to solve.
The problem:
I have old Licensing class and a new Licensing class. I have an app that uses the old Licensing class. The app has calls of the old Licensing class methods everywhere in the code.
After looking at the old Licensing closely I realized that the only thing separating it from the new Licensing class what kind of file it reads. Old: Reads .ini
files (normal textfile), New: reads .file
(binary).The new licensing tool reads a binary file only it can understand. But I know that if there is a way I make the old Licensing class to understand .file
then it saves me from going everywhere in the app and doing things like if (License::Instance().isFeature1Licensed() || NewLicensingTool::Instance.isFeature1Licensed())
.
Requirement:
- App must accept both types of file for licensing (
.ini
) or (.file
) - Old Licensing tool must not know anything about new licensing tool or vice versa
Here is the current general layout of the app:
// Singleton
class License
{
public:
.
.
.
void read (string& filename)
{
// read a specific kind (.ini) of file
// a certain way
}
.
.
.
}
// This exists in the app level
// This class requires a lot of
// dependency
class NewLicensingTool
{
public:
.
.
.
void read (string& filename)
{
// reads a specific kind of file (.file)
// a different way than the old way
}
vector<NewLicensingTool::LicensingIDs> getLicenses()
.
.
.
}
class App
{
// needs to be able to license the old and
// new way
// There are calls to License::Instance() methods
// everywhere in the code
...
void doSomething()
{
...
if (License::Instance().isFeature1Licensed())
{
...
}
...
}
...
void doAnother()
{
..
if (License::Instance().isFeature2Licensed())
{
}
..
}
}
Here is my proposed solution:
class OtherReadBehavior
{
public:
void read(string& filename) = 0;
}
// Singleton
class License
{
public:
.
.
.
void read (string& filename)
{
// read a specific kind (.ini) of file
// a certain way
OtherReadBehavior::read(filename);
}
.
.
.
}
// This exists in the app level
// This class requires a lot of
// dependency
class NewLicensingTool
{
public:
.
.
.
void read (string& filename)
{
// reads a specific kind of file (.file)
// a different way than the old way
}
vector<NewLicensingTool::LicensingIDs> getLicenses()
.
.
.
}
class App
{
// needs to be able to license the old and
// new way
// There are calls to License::Instance() methods
// everywhere in the code
class NewLicensingReadBehavior : public OtherReadBehavior
{
public:
void read(string& filename)
{
NewLicensingTool::Instance().read(filename);
}
}
...
void doSomething()
{
...
if (License::Instance().isFeature1Licensed())
{
...
}
...
}
...
void doAnother()
{
..
if (License::Instance().isFeature2Licensed())
{
}
..
}
}
I'm not sure if this is a good design or an ugly design. Before I present it to my peers, I want to get experts opinion on this. And if you know a better way to do it or pattern I should look up. Please let me know.
update
I just realize this solution won't work because the old License class has a private array of the valid Licenses. So even tho NewLicensingBehavior inherits from OtherLicensingBehavior, it will not be able to set the valid licenses array.
C++11 auto and void* generics
Based upon this, can I infer that int age = 45; auto* page = &age; std::cout << *page;
will allow true generics in c++ whereas void*
requires knowledge of the type to cast it and grab the value?
I am studying c++ again and thought auto*
would be a very suitable and ideal replacement for void*
.
How do I create and array of pointers to functions?
gcc 6.4.0 win 7 Netbeans 8.2
I can't figure what I'm doing wrong.
#ifndef TYPEDEF_H
#define TYPEDEF_H
class Typedef {
class Alphabet { };
class Tuple { };
class Operations { };
public:
void test();
private:
Tuple constant(long one, long two, Alphabet& bet, Operations& op) { return Tuple(); } ;
Tuple expression(long one, long two, Alphabet& bet, Operations& op) {return Tuple(); } ;
};
#endif /* TYPEDEF_H */
===================== .cpp file ========================
#include "Typedef.h"
void Typedef::test() {
typedef Tuple (*fn)(long, long, Alphabet&, Operations&);
fn func[] = { constant, expression };
Tuple (*fnc[2])= { constant, expression };
}
Typedef.cpp: In member function 'void Typedef::test()':
Typedef.cpp:6:44: error: cannot convert 'Typedef::constant' from type 'Typedef::Tuple (Typedef::)(long int, long int, Typedef::Alphabet&, Typedef::Operations&)' to type 'fn {aka Typedef::Tuple (*)(long int, long int, Typedef::Alphabet&, Typedef::Operations&)}' fn func[] = { constant, expression };
The error message is repeated for all four instances. I've tried &constant and as expected it didn't work.
Is there a way to query a std::locale for a list of all facets currently installed?
I am familiar with the use of std::has_facet(loc) to determine whether a specific facet has been loaded into a locale.
if ( ! std::has_facet<custom_facet_t>(std::cout.getloc()) ) {
/* load facet in to locale */
}
Is there a way to get a list of all facets currently loaded? Given the nature of locales, I am fairly certain that it would violate all types of rules... but I had to ask :) .
Variadic template as parameters to std::function
I want to build a structure that allow me to call member functions with an undefined number of parameters. For now I wrote something like this
template<typename Class, typename Return, typename ... Args>
struct Caller
{
private:
std::function<Return(Args ...)> callerFunction;
Caller() = delete;
Caller(const Caller&) = delete;
Caller(Caller&&) = delete;
Caller& operator=(const Caller&) = delete;
public:
~Caller() = default;
Caller(Class& instance, Return(Class::*function)(Args ...))
{
callerFunction = [&instance, function](Args... args)
{
return (instance.*function)(args ...);
};
}
Return operator() (Args ... args)
{
return callerFunction(args ...);
}
};
I am afraid that I cannot work around the fact that I cannot declare a std::function variable as std::function<Return<Args&& ...)> callerFunction
When I try to do this the compiler says that it cannot convert from int
to int&&
(if for example the parameters are int
s), so I'm guessing that the function sees the Args&& ...
as a parameter pack of rvalue references. Am I correct?
Is there a workaround?
Can one use template specialization on a templated typedef?
I would like to do something like the following (in c++11, c++14; not c++17):
template <class T>
using partner = void;
template<>
using partner<A> = X;
template<>
using partner<B> = Y;
template<>
using partner<C> = Z;
But I get a compilation error---
error: expected unqualified-id before ‘using’
---on the first template specialization.
Is such a thing possible? (I already know I can use a templated class with a using
statement inside it. I'm hoping directly use the using
statement without the class wrapper, since it's simpler and more elegant. If there's another simple, elegant solution, please share!)
Access violation on std::function assigned to a lambda
I was trying to play around with std::function and std::bind and I stepped in a problem. I would like to build a general structure that allows me to bind a std::function to a member function without knowing a priori the arguments of the member function. I wrote this thing
template<typename Class, typename Return, typename ...Args>
struct Caller
{
private:
std::function<Return(Args ...)> callerFunction;
Caller(const Caller&) = delete;
Caller(Caller&&) = delete;
Caller& operator=(const Caller&) = delete;
public:
~Caller() = default;
Caller() = default;
Caller(Class& instance, Return(Class::*function)(Args...))
{
callerFunction = [&](Args... args) { return (instance.*function)(args...); };
}
Return operator() (Args ... args)
{
return callerFunction(args...);
}
};
FYI I know that the arguments to the function are passed by value (I encountered some problem using universal references with variadic template, I will work on that later).
The problem here is that when I fire the function with operator() I get an Access Violation Error. I tried to narrow down the problem and created a structure without the variadic arguments (allowing the member function to have just an int as argument) and I saw that assigning the lambda to the std::function was given me the same error, but if I used std::bind with a placeholder everything was just fine.
The test ground is this
class A
{
public:
bool foo(int a)
{
std::cout << a << std::endl;
return true;
}
};
int main()
{
A a;
a.foo(9);
Caller<A, bool, int> caller(a, &A::foo);
caller(10);
std::cin.ignore();
}
Using the lambda, do I need to save the instance of the class in order to call properly the member function?
(std::__cxx11::string) [with T = std::__cxx11::basic_string
C++ showing error
(std::__cxx11::string) [with T = std::__cxx11::basic_string<char>; std::__cxx11::string = std::__cxx11::basic_string<char>]cannot be overloaded
I am trying to overload a Template class constructor here. Extended error:
In file included from main.cpp:2:0: dlist.h: In instantiation of class Sinwan::DList::DoublyLinkList >: main.cpp:5:45: required from here dlist.h:62:13: error: Sinwan::DList::DoublyLinkList::DoublyLinkList(std::__cxx11::string) [with T = std::__cxx11::basic_string; std::__cxx11::string = std::__cxx11::basic_string] cannot be overloaded DoublyLinkList(std::string dummyData_) ^ dlist.h:52:13: error: with Sinwan::DList::DoublyLinkList::DoublyLinkList(T) [with T = std::__cxx11::basic_string] DoublyLinkList(T dummyData_)
code:
DoublyLinkList(T dummyData_)
{
node = new Node;//dummy node
node->_next=NULL;
node->_prev=NULL;
node->_data=dummyData_;
head=node;
tail=node;
_iteratorObj=begin();
}
DoublyLinkList(std::string dummyData_)
{
node = new Node;//dummy node
node->_next=NULL;
node->_prev=NULL;
node->_data=dummyData_;
head=node;
tail=node;
_iteratorObj=begin();
}
Best practice for using global static const objects that are initialised once at the start of the program
I am trying to both corroborate my understanding and perhaps find a more complete solution to this.
Use-case:
Program has to parse a config file that specifies various parameters, if some parameters are missing the default values defined in a header should be used. The object should be created and intialised once at the start and then be available to all objects through the program till its termination. Nothing should be able to change the values inside that object.
I've looked at several questions and there seems to be lots of conflicting solutions, from using singletons to just static const
objects. I know the latter will cause duplication as each single unit will have a copy of the content.
So far part of the solution seems to be using extern
as shown in c++ global object in combination with declaring it 'const'.
Also, I use c++11. But I welcome answers about future standards (if applicable).
Questions:
1) Can I also make it static?
2) Where should I initialise this static const
globalVal?
3) Does this make sense? Are there better ways? I saw that I could also create an object that only gives a const
reference to its content. Would that be better?
4) Is this a good way of dealing with this problem? Just want to make sure I am not totally off.
shared_timed_mutex is unavailable: introduced in macOS 10.12
I am running on MacOs Sierra 10.12.6
with Xcode9. As per Apple #include <shared_mutex>
is available in MacOS 10.12.
But trying to include gives me error saying
shared_timed_mutex
is unavailable: introduced in macOS 10.12
initialize class A static std::map
I have a static std::map declared static in class A (A.hpp) :
typedef bool (*fct_pointer_t)(uint8 *msg, void *other);
typedef std::map<std::string, fct_pointer_t> map_string_to_fct_t;
class A {
static map_string_to_fct_t str_to_fct;
}
I need to initialize this A static std::map with pointers to class B functions. This is done in B.cpp file:
map_string_to_fct_t A::str_to_fct = {
{"string1", &B::fct1},
{"string2", &B::fct2},
}
B::fct1(uint8* msg, void*){
...
}
B::fct2(uint8* msg, void*){
...
}
In order for A static member to have access to member functions of B, I declare A friend of B as follows in B.hpp file:
class B {
friend class A;
fct1(...);
fct2(...);
}
Now, why do I get this error at compilation ?
error: could not convert [...] from 'brace-enclosed initializer list' to 'map_string_to_fct_t {aka std::map, bool (*)(uint8*, void*)>}
Thanks for your help.
Class with defaulted protected destructor not trivially-destructible but derived class is?
In the following exemple the first static assertion fired but not the second:
#include<type_traits>
struct A{
protected:
~A()=default;
};
struct B:A{
//this static assertion fails
static_assert(std::is_trivially_destructible<A>::value,"");
};
//this static assertion succeeds
static_assert(std::is_trivially_destructible<B>::value,"");
(checked with GCC,Clang,MSVC,ellcc)
I don't understand why A can not be trivially_destructible, inside B, while B is trivially destructible. This seems to be in contradiction with these 2 paragraphs of the C++ standard, where accessibility is not mentionned:
[class.dtor]
A destructor is trivial if it is not user-provided and if:
(6.1) — the destructor is not
virtual
,(6.2) — all of the direct base classes of its class have trivial destructors, and
(6.3) — for all of the non-static data members of its class that are of class type (or array thereof), each such class has a trivial destructor.
[dcl.fct.def.default]
A function is user-provided if it is user-declared and not explicitly defaulted or deleted on its first declaration.
jeudi 28 septembre 2017
Rcpp Makevars: portable -mpopcnt flag
I am using Rcpp and I am trying to make my Makevars
file written to be portable. Initially this is my file:
PKG_CXXFLAGS = -std=c++11 -mpopcnt
PKG_CXX1XFLAGS = $(PKG_CXXFLAGS)
Then I modified it so I can make the C++11 flag portable:
CXX_STD = CXX11
PKG_CXXFLAGS = -mpopcnt
PKG_CXX1XFLAGS = $(PKG_CXXFLAGS)
However, -mpopcnt
is not a portable flag. Is there a fix for this?
c++11 std::thread return from getter
I am trying to do the following
#pragma once
#ifndef PRODUCER_H
#define PRODUCER_H
#include <thread>
class Producer
{
private:
std::thread producer_thread;
public:
Producer();
std::thread get_producer(void)
{
return producer_thread;
}
};
#endif
The error in Visual Studio is that producer_thread can't be accessed because it is a deleted function?
C++ no viable constructor copying variable of type
I am getting the following error message:
main.cpp: No viable constructor copying variable of type 'communal'
On the second constructor,communal( const T& instance )
, the following message is given:
data.h: Candidate constructor not viable: no known conversion from 'communal' to 'const int &' for 1st argument
The conversion appears to be going backwards. I want the conversion to go from const int& to communal. Is there a way to get implicit conversion to work here? Thanks for any help.
main.cpp:
communal<int> test_communal1 = 123; // Implicit initialization triggers error
data.cpp:
template<typename T>
struct communal : general_type::communal<T>
{
using super = general_type::communal<T>;
communal() : super( nullptr ) {}
communal( const T& instance ) : super( new T( instance ) ) {}
communal( const T* instance ) : super( new T( instance ) ) {}
communal( communal<T>& instance ) : super( instance ) {}
communal( communal<T>* instance ) : super( instance ) {}
~communal()
{
this->counter->deallocate( [this]()
{
delete this->counter;
delete this->instance;
});
}
};
Random values for const variable and c++ [duplicate]
This question already has an answer here:
I would like to create a const variable (of type: const size_t) that has a random value each time I run my code.
The following line
const size_t x = size_t(rand())
does not work.
Thank you in advance for your help
How to move rows in Qt (in QTableWidget)
It's really a shame that Qt devs skipped this really important part of a table... moving rows (probably the selected ones) with checks for collision and support for selections with gaps - now one has to implement it himself.
Luckily I spent pretty much the whole day creating such, self-contained function that can be easily modified to move anything related to tables/lists (currently it moves selected items - second line). And a more interesting part, I was able to easily (with about 3 lines more) add support for a direction argument instead of a separate function.
I haven't thought about it, but moving by more than 1 item at a time could be possible aswell - though I have no need for that.
Any suggestions and bug-testing is appreciated ~~enjoy.
zero length variadic expansion of ill-formed call
Question for standard gurus.
Trying to respond to another question, I came to doubt about the well-formedness of a code.
As far I know, the following code is ill-formed
int main ()
{
std::tuple<> a;
std::get<0>(a);
}
because a call to std::get<I>(t)
, when t
is a std::tuple<Ts...>
, is ill-formed when I
is outside the range [0, sizeof...(Ts)[
.
In this case sizeof...(Ts)
is zero, so the range [0, 0[
is empty, so std::get<I>(a)
is ill-formed for every index I
.
But when std::get<I>(a)
is expanded through an empty variadic pack?
I mean: the following code
#include <tuple>
template <typename ... Args>
void bar (Args const & ...)
{ }
template <std::size_t ... I>
void foo ()
{
std::tuple<> a;
bar( std::get<I>(a) ... );
}
int main ()
{
foo<>();
}
that uses a ill-formed (?) call (std::get<I>(a)
) but zero-time variadic expanded (sizeof...(I)
is zero), is well-formed or ill-formed?
Stop a c++ code from exiting and pass back control
I am using cling(CERN ROOT) for my project. I have an established an interactive c++ environment. I can execute a main() function from cling command line. However, I want to retain my variable for further processing from command line. All my variables would have been local to main and are freed at the closing brace of main(). Is there any way to execute all commands and not terminate instead pass back control to user with all the loaded environment/variables.
I am looking for something which which stop termination and give back control. Anything would be helpful(something equivalent to continue but out of loop and out of main as well)
Thanks in advance.
Calculate sum with mathematical indunction
In for function . How i do i to number from 2 to 2. I mean "for(i=1; i<=n; i++)" . At i++ it adds 1 but how to add 2 ? I tried 30 minutes to make that but i can't .. i tried for(i=; i<=n; i= i+2 ) or i+=2 .. i tried to add i+1 in for function .. but nothing worked .. How to do that ? Thanks.
$ int sum = 1;
for(int i=1; i<=n ; i+=2) {
sum = sum + i;
}
return sum;
or { int sum = 1;
for(int i=1; i<=n ; i= i +2) {
sum = sum + i;
}
return sum;
How to handle unused warnings caused by empty template parameter pack expansions?
An issue I keep facing is one where the compiler complains about an unused variable, even though the variable is used, but it's only used inside a parameter pack expansion that happens to be empty for a specific instantiation. For example:
template <std::size_t... I>
auto func1(std::index_sequence<I...>)
{
auto var = get_tuple();
return func2(std::get<I>(var)...);
}
auto a = func1(std::make_index_sequence<0>());
See live example (try changing the tuple at line 4, by adding an int inside <> to see the warning go away). I know I could add a (void)var;
line to make the warning go away, but it feels dirty to me, especially when the function is actually just a single line. I also don't want to disable this warning globally, because it does provide insight sometimes. I've encountered this issue for local function variables and also for lambda capture (-Wunused-lambda-capture).
How would you change a channel to root and then change to a subsystem SFTP?
According to RFC 4254, under "Starting a Shell or a Command", it sounds as though you can execute shell commands as either a subsystem or a shell. I need to su
into root and then change to a subsystem sftp.
LIBSSH2_CHANNEL * chen = libssh2_channel_open_session(_thisSession);
if(!chen){
std::cerr << "ERROR: " << err(libssh2_session_last_errno(_thisSession),0) << std::endl;
}
rc = libssh2_channel_exec(chen, "su -");
if(rc < 0){
std::err << "ERROR: " << err(rc, 0) << std::endl;
}
//stops working, for obvious reasons, but this is meant to reflect my intention.
rc = libssh2_channel_process_startup(chen, "shell", strlen("shell"), "sftp", strlen("sftp"));
if(rc < 0){
std::err << "ERROR: " << err(rc, 0) << std::endl;
}
What am I doing wrong? How do you switch to root and then switch to an SFTP subsystem?
cpp file not compiling in clang++ and g++
I have been working on C++ for few years now and have compiled stuff several times but the following issue is totally new to me and it just doesn't make sense.
Following are the steps i am following:
- using cygwin setup with g++ version:6.4.0 and clang++ version:4.0.1
- created a new cpp fie using sublime text added simple cout and compiled
with the command: clang++ -g -Wall -std=c++14 thread1.cpp -o thread, works fine. - added new contents maybe another cout, this time upon compilation i get a ton of errors stating its not utf-8 file.
- saved the file using utf-8 encoding in sublime text and also tried with utf-8 BOM encoding, still getting same not utf-8 file error.
- ran the file command in cygwin to check file encoding , file -i thread1.cpp, got output as thread1.cpp: text/x-c; charset=utf-8.
Any pointers to what might be going wrong here?
Nest template class method specialization
Before my question I'm posting absolute correct code that works:
template <class T>
struct Gen
{
void method()
{
std::cout << "I'm generic method\n";
}
};
template <>
void Gen<int>::method()
{
std::cout << "I'm dedicated for int method\n";
}
int main()
{
Gen<float> g1;
g1.method(); //generic method
Gen<int> g2;
g2.method(); //int method
}
So this declares method of template class that has special behavior for int
.
Now I'm trying to do absolutely the same with nested template class:
template <class T>
struct GenNest
{
template <class R>
struct Nest
{
void method()
{
std::cout << "I'm generic method\n";
}
};
};
template <class T>
template <>
void GenNest<T>::Nest<int>::method()
{
std::cout << "I'm dedicated for int method\n";
}
int main()
{
GenNest<float>::Nest<float> n1;
n1.method(); //generic method
}
And this case fails on compile time
- for vc++: error C2995: 'void GenNest::Nest::method(void)' : function template has already been defined
- for g++ error: invalid explicit specialization before '>' token
So dear community - what is wrong and how to fix it?
PulseAudio won't compile on cmake
I'm trying to write a simple program with PulseAudio lib. Everything is fine when it compiles under gcc (gcc -o name_one name_two.cpp -lpulse-simple -lpulse), but when I copy my program to cLion (under cmake) it throws up an error:
main.cpp:49: undefined reference to pa_simple_new
main.cpp:50: undefined reference to pa_strerror
main.cpp:78: undefined reference to pa_simple_drain
main.cpp:72: undefined reference to pa_simple_write
main.cpp:73: undefined reference to pa_strerror
main.cpp:79: undefined reference to pa_strerror
main.cpp:85: undefined reference to pa_simple_free
I've tried to add links (-lpulse-simple -lpulse) into my makeafile.txt like this:
add_compile_options(-lpulse-simple -lpulse)
but this is not working.
How to do it properly?
QT Closing QDialogs/QMessageBox opened from calling exec() when the parent window is closing
I am opening a QDialog/QMessageBox using exec() to get user input. But before the user selects Save or Discard from the message box, the parent window from which it was opened is closed.
When this happens the application crashed.
Can the QDialog/QMessageBox be closed when the parent is closed. ?
How to implement Dijkstra on imlicit graph?
How to implement Dijkstra on implicit graph ? Suppose we have a 2-D matrix 'A' of dimensions nXn and we have to find the shortest way to reach A[n-1][n-1] from A[0][0].
Is it a bad idea to use std::valarray in C++ programming?
I read about std::valarray
in C++ book writen by Nicolai M. Josuttis. He writs in his book The C++ Standard Library, chapter 17.4:
The valarray classes were not designed very well. In fact, nobody tried to determine whether the final specification worked. This happened because nobody felt “responsible” for these classes. The people who introduced valarrays to the C++ standard library left the committee long before the standard was finished. As a consequence, valarrays are rarely used.
So, is it a bad idea to use std::valarray
in C++ programming?
How to block thread until a function returns in another thread?
If I have a main thread and a separate, permanent worker QThread:
// Main thread where the event loop and QCoreApplication runs.
class NetworkController : public QObject {
public:
Q_OBJECT
void connect_to_ap()
{
WifiAP *myAP = netMgr.get_best_ap();
myAP->connect("my_psk_password");
}
// This is a class from a 3rd-party library, which contains, owns
// and manages the lifetime of "WifiAP" instances.
NetworkManager netMgr;
};
// Separate thread where a state machine runs.
class StateMachineWorker : public QObject {
public:
Q_OBJECT
void on_ready_to_connect_event()
{
// HERE: How to trigger NetworkController::connect_to_ap() and
// *block* until it returns.
}
NetworkController *pNetCtrlr;
}
When the state machine class enters a certain state it should connect to an AP (Access Point). The NetworkController
has the functionality to connect to an AP.
I am trying to figure out a way that the state machine can do this in a thread-safe way. The problem is NetworkManager
is always updating its list of WifiAP
instances: they are created and destroyed often. It would not be thread-safe for StateMachineWorker
to call pNetCtrlr->connect_to_ap()
directly (as the NetworkManager
in the NetworkController
thread could at the same time delete the WifiAP
instance).
So what I would like is in StateMachineWorker::on_ready_to_connect_event()
to somehow signal the NetworkController
to run its connect_to_ap()
method in NetworkController
's own thread, and to block the StateMachineWorker
thread until connect_to_ap()
has finished doing its stuff. The reason I want the state machine to be blocked is if I did not block and let it enter the event loop, it could receive some event that would make it transition to another state before connect_to_ap()
has finished executing; this must not happen.
Mutex locks to protect the list of WifiAP
in NetworkManager
would not work as they would need to be inserted inside the 3rd-party library.
Convert from std::vector
I have std::vector in C++ which represents voxels in x,y,z dimensions each cv::Mat in the vector is a cross section or a slice of the volume. Unfortunately OpenCV doesn't offer any wrapper to this data type, so I decided to use non-supported module from Eigen library called Tensor. I cannot see any constructor in the documentation that would allow me efficient conversion from vector of cv::Mat to eigen tensor without the need to reallocate data.
What is the most efficient way to convert from std::vector to Eigen::Tensor
How to open more than one ".html" file at a time
I am working in Qt. I have an Icon that has to open ".html". I can directly open the .html file using QUrl but I have a base folder as Doc, it contains some sub folders each folder has its own ".html". I have to open all at a single click(the Icon which I set for). what could be the best way to do
Memory fault(coredump) in SQL query
I am trying to read a single row from database:
This statement is working fine
stmt = conn->createStatement("SELECT * from Customer");
rs = stmt->executeQuery();
While this is showing Memory fault(coredump)
stmt->setSQL("SELECT * from :1");
stmt->setString(1,"Customer");
rs = stmt->executeQuery();
Passing string as a parameter
Want to pass as a reference. So that i can modify the string inside the function.
void shift(string &s,int i){
int len=strlen(s);
for(;s[len]>i;len--){
s[len]=s[len-1];
}
}
mercredi 27 septembre 2017
FLTK SIGSEGV Segmentation Fault when calling fl_line()
Calling fl_line() in my program immediately returns an SIGSEGV exception after drawing 1 line on the screen. I've checked vectors offset, nothing out of bounds:
Here's how it looks like when it crashes
Why is fl_line() called with parameters but not Fl_graphics_driver::line() ?
Here's my program, it was to draw a simple polygon out of 4 points:
#include <iostream>
#include <FL/Fl.H>
#include <FL/Fl_draw.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Widget.H>
#include <initializer_list>
#include <vector>
#include <functional>
//#include <cmath>
//#include <math.h>
struct Point {
int x,y;
Point(int xx, int yy) : x(xx), y(yy) { }
};
class Shape: public Fl_Widget{
public:
Shape(int x, int y, int w, int h) : Fl_Widget(x,y,w,h) {}
Point point(int idx) const {
return (points[idx]);
}
unsigned int points_size() const {
return points.size();}
void draw() override{
draw_lines();
}
void line(int x, int y, int x1, int y1) const {fl_line(x,y,x1,y1);}
void add(Point p){ points.push_back(p); }
protected:
virtual void draw_lines() const{}
private:
std::vector<Point> points;
};
class ClosedPolyline: public Shape {
public:
/*ClosedPolyline(std::initializer_list<Point> pp) {
if (pp.size() > 0) {
for (Point p: pp)
add(p);
}
}
*/
ClosedPolyline(Point a1, Point a2, Point a3, Point a4) : Shape(a1.x,a1.y,a3.x-a1.x,a2.y-a1.x) {
add(a1); add(a2); add(a3); add(a4);
}
protected:
void draw_lines() const override{
for (unsigned int i=1; i<points_size(); ++i){
std::cout << point(i-1).x << " " << point(i-1).y << " to " << point(i).x << " " << point(i).y << std::endl;
}
/*
for (unsigned int i=1; i<points_size(); ++i){
fl_line(point(i-1).x, point(i-1).y, point(i).x, point(i).y);
}
*/
line(point(0).x, point(0).y, point(1).x, point(1).y);
line(point(1).x, point(1).y, point(2).x, point(2).y);
line(point(2).x, point(2).y, point(3).x, point(3).y);
line(point(1).x, point(1).y, point(2).x, point(2).y);
}
};
class MyWindow: public Fl_Window {
public:
MyWindow(int x, int y, int w, int h, const char* title = 0)
: Fl_Window(x, y, w, h, title) {}
void Attach(Shape &s) {
shapes.push_back(&s);
//shapes.push_back(s);
//draw();
}
//void draw_shapes(){draw();}
protected:
void draw() override{
for(Shape * s: shapes) {
s->draw();
//s.draw();
}
}
private:
std::vector<Shape*> shapes;
};
/*
class Circle: public Shape {
public:
Circle(Point p, double r): radius(r) {
add(Point{p.x - r, p.y - r});
}
protected:
void draw_line() {
fl_arc(point(0).x, point(0).y, radius + radius,radius + radius, 0, 360);
}
private:
double radius;
};
void Function(T f, double r1, double r2,
Point xy, int count = 100, double xscale = 25, double yscale = 25) {
double dist = (r2-r1)/count;
double r = r1;
for (int i = 0; i<count; ++i) {
add(Point(xy.x+int(r*xscale), xy.y-int(f(r)*yscale)));
r += dist;
}
}
};
class CosFunction {
public:
double (double x) {
return cos(x * M_PI / 180);
}
};
*/
typedef double Fct(double);
int main() {
MyWindow win(100, 100, 600, 400, "C++ Test task");
ClosedPolyline p{Point{100, 100}, Point{100, 200}, Point{500, 100}, Point{500, 200}};
/*
Function<std::function<double(double)>> f1 {[] (double x) -> double { return x * x; }, -100, 100, Point {300, 300}, 100, 20, 5};
Function<Fct> f2 {sin, -360, 360, Point{300, 300}, 200, 1, 25};
Function<CosFunction> f3{CosFunction(), -360, 360, Point{300, 300}, 200, 1, 25};
Circle c1{Point{300, 50}, 30};
*/
win.Attach(p);
/*
win.Attach(f1);
win.Attach(f2);
win.Attach(f3);
win.Attach(c1);
*/
win.end();
win.show();
return (Fl::run());
}
What is "&&" in VoidName( vector
This question already has an answer here:
I have recently encountered this code
struct HLD
{
//typdef vector< vector<long> > dsk;
dsk ke;
vector<long> par;
HLD(dsk &&ke):ke(ke), par(n+1)
{
//
}
};
What is "&&" stand for (i've already know & is taking the address) and what does HLD(dsk &&ke):ke(ke), par(n+1)
do ?
Segmentation Fault due to Erase (Vector)
When I try to use the erase function within vector to erase a 'list', I get a segmentation fault. I am using clang++, c++11. The line of code I am struggling with is:
studentEntries.erase(std::find(studentEntries.begin(), studentEntries.end(), it));
studentEntries is a vector of lists of strings. ie:
std::vector<std::list<std::string>> studentEntries;
If more context would be helpful I also uploaded my project to pastebin (57 lines total). The problem is on line 27.
Thank you all so much for your help!!
std::set of unique ptr range insert
I have 2 data structures which hold a set of unique_ptr like so
std::vector<std::unique_ptr<Entity>> tmpEnts;
std::set<std::unique_ptr<Entity>> tmpSet;
I am trying to perform an insert as shown below but i get errors when i compile. I am new to smart pointers.
tmpSet.insert(tmpEnts.begin(), tmpEnts.end());
tmpEnts is actually a simplification, it actually resides in a std::map<uint, std::vector<std::unique_ptr<Entity>>> entities
How do I walk a bidirectional iterator backwards in clean code?
Suppose I have an std::map and want to do something to the item with key X and every item with a higher key (remember, this is an ordered map). The code is obvious and clear:
auto iter = mymap.find(X);
while (iter != mymap.end()) {
process(*iter);
iter++;
}
or, possibly better, std::for_each(mymap.find(X), mymap.end(), process)
.
But if my task is to perform processing on the item with key X and every item with a lower key, in that order, I can't find a clean coding pattern that expresses intent.
auto iter mymap.find(x);
if (iter != mymap.end()) {
iter++; // Go forward...
while (iter != mymap.begin()) {
iter--; // ... so we can go backwards
process(*iter);
}
}
If I didn't want to do them in reverse order, it would be easy enough to increment the iterator returned by std::map::find() and then use std::for_each(mymap.begin(), incremented_iter, process).
Bidirectional iterators aren't reverse iterators, so I can't use mymap.rend()
as the "off the beginning" to compare against in a while() loop.
Is there a clean way to do this in C++11 (or in +14 or +17, so I'll have something to look forward to)?
Is it always the case that sizeof(T) >= alignof(T) for all types T?
For any type T
is it always the case that sizeof(T)
is at least as large as alignof(T)
?
Intuitively it seems so, since even when you adjust the alignment of objects like:
struct small {
char c;
};
that would normally be small, their "size" is also adjusted upwards so that the relationship between objects in an array makes sense while maintaining alignment. For example:
struct alignas(16) small16 {
char c;
};
Has both a size and alignment of 16.
How to get the string to be run through the loop a second time with the adjusted string index?
Trying to write code that will take an input string and "abbreviate" it. for example if aabb is given then the output should be bc. Basically if there's any double letters it goes up to the next letter in the alphabet so aa = b and so on. This works fine for the first run through but it won't loop through until completion. if the given string is aaaa the output should be c but instead the code outputs bb. how can I adjust my code to run the string an appropriate amount of times?
string abbreviate (string loc){
int loopCount;
sort(loc.begin(), loc.end());
for ( unsigned int i = 0; i < loc.length() ; i++){
if(loc[i] == loc[i+1]) {
if(loc[i] == 'a'){
loc[i] = 'b';
loc[i+1] = 0;
}else if(loc[i] == 'b'){
loc[i] ='c';
loc[i+1]= 0;
}else if(loc[i] == 'c'){
loc[i] ='d';
loc[i+1]= 0;
}else if(loc[i] == 'd'){
loc[i] = 'e';
loc[i+1]= 0;
}else if(loc[i] == 'e'){
loc[i] ='f';
loc[i+1]= 0;
}else if(loc[i] == 'f'){
loc[i] ='g';
loc[i+1]= 0;
}else if(loc[i] == 'g'){
loc[i] ='h';
loc[i+1]= 0;
}else if(loc[i] == 'h'){
loc[i] ='i';
loc[i+1]= 0;
}else if(loc[i] == 'i'){
loc[i] ='j';
loc[i+1]= 0;
}else if(loc[i] == 'j'){
loc[i] ='k';
loc[i+1]= 0;
}else if(loc[i] == 'k'){
loc[i] ='l';
loc[i+1]= 0;
}else if(loc[i] == 'l'){
loc[i] ='m';
loc[i+1]= 0;
}else if(loc[i] == 'm'){
loc[i] ='n';
loc[i+1]= 0;
}else if(loc[i] == 'n'){
loc[i] ='o';
loc[i+1]= 0;
}else if(loc[i] == 'o'){
loc[i] ='p';
loc[i+1]= 0;
}else if(loc[i] == 'p'){
loc[i] ='q';
loc[i+1]= 0;
}else if(loc[i] == 'q'){
loc[i] ='r';
loc[i+1]= 0;
}else if(loc[i] == 'r'){
loc[i] ='s';
loc[i+1]= 0;
}else if(loc[i] == 's'){
loc[i] ='t';
loc[i+1]= 0;
}else if(loc[i] == 't'){
loc[i] ='u';
loc[i+1]= 0;
}else if(loc[i] == 'u'){
loc[i] ='v';
loc[i+1]= 0;
}else if(loc[i] == 'w'){
loc[i] ='x';
loc[i+1]= 0;
}else if(loc[i] == 'x'){
loc[i] ='y';
loc[i+1]= 0;
}else if(loc[i] == 'y'){
loc[i] ='z';
loc[i+1]= 0;
}
}
}
return loc;
}
How can std::aligned_storage expose correctly aligned storage for any object?
The std::aligned_storage
structure provides a type
typedef that at least according to cppreference:
Provides the member typedef type, which is a PODType suitable for use as uninitialized storage for any object whose size is at most Len and whose alignment requirement is a divisor of Align.
The default value of Align is the most stringent (the largest) alignment requirement for any object whose size is at most Len.
In particular, with the default value of Align
, the suitably aligned for any object whose size is at most Len.
Note that there are no caveats or exceptions for over-aligned types (and in any case the platform I'm using, gcc, supports at least some over-aligned types).
How can such an implementation actually work? To satisfy the requirement of "any object" it would seem that it would either:
- On a platform where
alignof(T) <= sizeof(T)
for typesT
, need to always align to roughlyLen
bytes, since an object of sizeLen
could have an alignment of up toLen
. Of course, this would waste a lot of memory for largeLen
! - On a platform where
alignof(T)
may be larger than thansizeof(T)
, I don't see how it could be implemented at all. However, it isn't clear to me that such a type can even exist.
Based on my testing, for default Align
values, gcc
simply always aligns to 16, regardless of len. This means the storage is not suitable for any object, but only objects of fundamental alignment (alignof(max_align_t) == 16
on this platform).
Why does std::(multi)set provide non const iterator methods
Why do the sets (std::set
and std::multiset
) in the C++ standard library provide non const iterator methods (http://ift.tt/2wVgDpT and http://ift.tt/2yIz7qV)?
Access to the keys through iterators is always const, does not matter if the set itself is const or not, then why introduce those extra overloads?
‘get_time’ is not a member of ‘std' and ‘std::get_time’ has not been declared
I am using get_time() and mtkime() to convert the values of an object of my DateTime class to a unix timestamp so that I can easily compare two instances of my DateTime class. Here is my code for generating the time stamp
void DateTime::setTimeStamp()
stringstream date_ss1;
date_ss1 << (*this);
istringstream date_iss(date_ss1.str());
struct tm date;
date_iss >> get_time( &date, "%Y/%m/%d-%H:%M" );
timestamp = mktime( &date );
This code compiles and works perfectly on my Mac. BUT it gives this as the only error when compiling it on a remote server.
DateTime.h:40:12: error: ‘std::get_time’ has not been declared
using std::get_time;
The server's compiler has no problem finding mtkime in case that info is of help.
My Mac compiler version
Configured with: --prefix=/Applications/http://ift.tt/1d5DwEL --with-gxx-include-dir=/usr/include/c++/4.2.1 Apple LLVM version 9.0.0 (clang-900.0.37) Target: x86_64-apple-darwin16.7.0 Thread model: posix InstalledDir: /Applications/http://ift.tt/1z8WHIF
Server GNU compiler version
gcc (GCC) 5.3.1 20160406 (Red Hat 5.3.1-6)
I got the version of the compilers on both my Mac and the remote server by running
gcc --version
DateTime.h
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <sstream>
#include <ctime>
#include <exception>
using std::ostream;
using std::istream;
using std::string;
using std::setfill;
using std::setw;
using std::endl;
using std::stringstream;
using std::istringstream;
using std::cout;
using std::invalid_argument;
using std::exit;
using std::get_time;
/*code*/
Please let me know if you need me to include more info to get to the bottom of this. Appreciate your help!
Is there overhead in replacing call stack with local stack?
I want change recursive call of same function into loop call. To implement this I use std::stack.
Compile a static librery with standard library static
I'm trying to compile a static library (let's call it library.a). This library consumes resources of standard libraries. There is some way that the library can statically link a standard library.
I have proven something like:
g++ -c library -static-libstdc++ -o library.o
ar rcs library.o library.a
But if I do so there is no link to the standard libraries.
Then I have proved this way:
g++ library -static-stdlib -o library.o
ar rcs library.o library.a
But ask me to add a main function.
Is there any possibility of creating a static library by statically linking also standard libraries (std :: string, std :: vector, std :: cin, etc ...).
Thanks :)
Another void* topic; I just have to ask because I am confused
Ok, muddling though Stack on the particulars about void*
, books like The C Programming Language (K&R)
and The C++ Programming Language (Stroustrup)
. What have I learned? That void*
is a generic pointer with no type inferred. It requires a cast to any defined type and printing void*
just yields the address.
What else do I know? void*
can't be dereferenced and thus far remains the one item in C/C++
from which I have discovered much written about but little understanding imparted.
I understand that it must be cast such as *(char*)void*
but what makes no sense to me for a generic
pointer is that I must somehow already know what type I need in order to grab a value. I'm a Java programmer; I understand generic types but this is something I struggle with.
So I wrote some code
typedef struct node
{
void* data;
node* link;
}Node;
typedef struct list
{
Node* head;
}List;
Node* add_new(void* data, Node* link);
void show(Node* head);
Node* add_new(void* data, Node* link)
{
Node* newNode = new Node();
newNode->data = data;
newNode->link = link;
return newNode;
}
void show(Node* head)
{
while (head != nullptr)
{
std::cout << head->data;
head = head->link;
}
}
int main()
{
List list;
list.head = nullptr;
list.head = add_new("My Name", list.head);
list.head = add_new("Your Name", list.head);
list.head = add_new("Our Name", list.head);
show(list.head);
fgetc(stdin);
return 0;
}
I'll handle the memory deallocation later. Assuming I have no understanding of the type stored in void*
, how do I get the value out? This implies I already need to know the type, and this reveals nothing about the generic nature of void*
while I follow what is here although still no understanding.
Why am I expecting void*
to cooperate and the compiler to automatically cast out the type that is hidden internally in some register on the heap or stack?
difference between std::mutex and std::shared_mutex
I came across std::shared_mutex in C++17. what exactly is shared_mutex and how it is different from std::mutex.
Confusion regarding range-based for loop in C++
This code takes a string and then write outs the even and odd-positioned characters of the string as 2 separate strings separated by a space. I have solved the problem using standard for loop. But I am trying to use range-based for loop in it instead of the normal for loop (after getting fired up by Bjarne's 2017 CPPCON keynote). The normal for loop works fine and I have commented it in the following code-block.
Problem is: The code compiles with g++ -std=c+11 command, but the even and odd strings are coming out garbled and reads like binary files. Can you please explain what I am doing wrong and exactly what is happening here? A clear explanation will be much appreciated. Thank you.
string S,even,odd;
cout << "Enter a string:\n";
cin.ignore(); // So that getline does not catch
//the eol character
getline(cin,S);
// for (int j=0; j<S.length(); j++){
// if(j==0 || j%2==0){even.push_back(S[j]);}
// else {odd.push_back(S[j]);}
// }
for (auto j : S){
if(j==0 || j%2==0){even.push_back(S[j]);}
else {odd.push_back(S[j]);}
}
cout << "You wrote: " << S <<'\n';
cout << "Even(including 0) positioned character(s)
of " << S << " is(are) " << even <<'\n';
cout << "Odd positioned character(s) of " << S <<
" is(are) " << odd <<'\n';
What is the difference between btree* tree = new btree; and btree* tree = new btree();
I am trying to implement tree data-structure in c++. Being a newbie I am not getting the difference between the two. However while running my code both work exactly the same.
Undefined reference to xx:xx()
Believe me when I tell you that I searched online, but did not find the answer.
I have 5 files:
main.cpp
Game.cpp
Game.hpp
Window.cpp
Window.hpp
The content is below :
#include "Window.hpp"
#include "Game.hpp"
int main()
{
// Program entry point
Game game;
while (!game.GetWindow()->IsDone()){
// game loop here
game.HandleInput();
game.Update();
game.Render();
}
return 0;
}
This is the Game.cpp
#include "Window.hpp"
class Game {
public:
Game(): m_window("Chapter 2", sf::Vector2u(800,600)) {
m_mushroomTexture.loadFromFile("images.png");
m_mushroom.setTexture(m_mushroomTexture);
}
~Game(){}
void HandleInput() {
}
void Update() {
m_window.Update();
MoveMushroom();
}
void Render() {
m_window.BeginDraw();
m_window.Draw(m_mushroom);
m_window.EndDraw();
}
// Getting a point to the window
Window* GetWindow(){
}
private:
void MoveMushroom(){
sf::Vector2u l_windSize = m_window.GetWindowSize();
sf::Vector2u l_textSize = m_mushroomTexture.getSize();
if ((m_mushroom.getPosition().x > l_windSize.x - l_textSize.x and m_increment.x > 0) or \
(m_mushroom.getPosition().x < 0 and m_increment.x < 0)) {
m_increment.x = -m_increment.x;
}
if ((m_mushroom.getPosition().y > l_windSize.y - l_textSize.y and m_increment.y > 0) or \
(m_mushroom.getPosition().y < 0 and m_increment.y < 0)) {
m_increment.y = -m_increment.y;
}
m_mushroom.setPosition( m_mushroom.getPosition().x + m_increment.x, m_mushroom.getPosition().y + m_increment.y);
}
Window m_window;
sf::Texture m_mushroomTexture;
sf::Sprite m_mushroom;
sf::Vector2i m_increment;
};
Game.hpp
#pragma once
#include "Window.hpp"
#include <SFML/Graphics.hpp>
class Game {
public:
Game();
~Game();
void HandleInput();
void Update();
void Render();
// Getting a point to the window
Window* GetWindow();
private:
void MoveMushroom();
Window m_window;
sf::Texture m_mushroomTexture;
sf::Sprite m_mushroom;
sf::Vector2i m_increment;
};
Window.cpp
#include <SFML/Graphics.hpp>
#include <string>
class Window {
public:
// constructor
Window() {Setup("Window", sf::Vector2u(640,480));}
// we have 2 constructors because there 2 ways to instantiate a class
Window(const std::string& l_title, const sf::Vector2u& l_size) {
Setup(l_title, l_size);
}
~Window() { Destroy(); }
void BeginDraw(){
m_window.clear(sf::Color::Black);
}
void EndDraw(){
m_window.display();
}
void Update(){
sf::Event event;
while (m_window.pollEvent(event)) {
if (event.type == event.Closed) {
m_isDone = true;
} else if (event.type == sf::Event::KeyPressed and event.key.code == sf::Keyboard::F5){
ToggleFullscreen();
}
}
}
bool IsDone(){
return m_isDone;
}
bool IsFullscreen(){
return m_isFullscreen;
}
sf::Vector2u GetWindowSize() {
return m_windowSize;
}
void ToggleFullscreen(){
m_isFullscreen = !m_isFullscreen;
Destroy();
Create();
}
void Draw(sf::Drawable& l_drawable){
m_window.draw(l_drawable);
}
private:
void Setup(const std::string& l_title, const sf::Vector2u& l_size) {
m_windowTitle = l_title;
m_windowSize = l_size;
m_isFullscreen = false;
m_isDone = false;
Create();
}
void Destroy(){
m_window.close();
}
void Create() {
// the same as
// if (m_isFullscreen) {
// auto_style = sf::Style::Fullscreen;
// } else {
// auto_style = sf::Style::Default;
// }
auto style = (m_isFullscreen ? sf::Style::Fullscreen : sf::Style::Default);
m_window.create({m_windowSize.x, m_windowSize.y, 32}, m_windowTitle, style);
}
sf::RenderWindow m_window;
sf::Vector2u m_windowSize;
std::string m_windowTitle;
bool m_isDone;
bool m_isFullscreen;
};
Window.hpp
#pragma once
#include <SFML/Graphics.hpp>
#include <string>
class Window {
public:
// constructor
Window();
// we have 2 constructors because there 2 ways to instantiate a class
Window(const std::string& l_title, const sf::Vector2u& l_size);
~Window();
void BeginDraw();
void EndDraw();
void Update();
bool IsDone();
bool IsFullscreen();
sf::Vector2u GetWindowSize();
void ToggleFullscreen();
void Draw(sf::Drawable& l_drawable);
private:
void Setup(const std::string& l_title, const sf::Vector2u& l_size);
void Destroy();
void Create();
sf::RenderWindow m_window;
sf::Vector2u m_windowSize;
std::string m_windowTitle;
bool m_isDone;
bool m_isFullscreen;
};
The problem is that when i try to build my project i get a linker error.
/tmp/ccxbe5nA.o: In function `main':
main.cpp:(.text+0x26): undefined reference to `Game::Game()'
main.cpp:(.text+0x35): undefined reference to `Game::GetWindow()'
main.cpp:(.text+0x3d): undefined reference to `Window::IsDone()'
main.cpp:(.text+0x53): undefined reference to `Game::HandleInput()'
main.cpp:(.text+0x62): undefined reference to `Game::Update()'
main.cpp:(.text+0x71): undefined reference to `Game::Render()'
main.cpp:(.text+0x87): undefined reference to `Game::~Game()'
main.cpp:(.text+0xac): undefined reference to `Game::~Game()'
collect2: error: ld returned 1 exit status
I am compiling first with the following command :
g++ -std=c++11 -c main.cpp Window.cpp Game.cpp
No errors during the compilation stage. When I try to link it, I get the error message from above. The command used is this :
g++ main.o Game.o Window.o -o sfml-app -lsfml-graphics -lsfml-window -lsfml-system
Attribute presence generic check
My requirement is to parse on XML and populate an object. How do I automatically track if attribute xyz is present once the object is populated from the Xml. Please note that I will no longer have access to the parsed buffer after the object is populated. Hence I need some mechanism to know whether the attribute was present in XML and the same is populated in the object.
I have the below solution in my mind but not sure if anything more efficient possible. Also I am looking for a generic solution for this problem.
-
define a bit for each of the attribute in a class.
-
setter function should set that bit while parsing XML when attribute is present
-
getter function should check the bit before returning the attribute value by reference . It should return false when bit is not set
behavior of synthesised move constructor
I am reading 5th edition and get the following problems. The book lists several cases that a synthesized move operation is defined as deleted. One of which is "Unlike the copy constructor, the move constructor is defined as deleted if the class has a member that defines its own copy constructor but does not also define a move constructor, or if the class has a member that doesn't define its own copy operations and for which the compiler is unable to synthesize a move constructor. Similarly for move-assignment." and also provide an demo code as following:
// assume Y is a class that defines its own copy constructor but not a move constructor
struct hasY {
hasY() = default;
hasY(hasY&&) = default;
Y mem; // hasY will have a deleted move constructor
};
hasY hy, hy2 = std::move(hy); // error: move constructor is deleted
However, for both gcc 7.2.1 and clang-900.0.37, the code is runnable, is the book wrong?
Here is the complete test code:
#include <iostream>
struct Y {
Y() { std::cout << "Y()" << std::endl; }
Y(const Y&) { std::cout << "Y(const Y&)" << std::endl; }
//Y(Y&&) { cout << "Y(Y&&)" << endl; }
};
// assume Y is a class that defines its own copy constructor but not a move constructor
struct hasY {
hasY() = default;
hasY(hasY&&) = default;
Y mem; // hasY will have a deleted move constructor
};
int main() {
hasY hy, hy2 = std::move(hy); // error: move constructor is deleted
return 0;
}
Is there any point in using `override` when overriding a pure virtual function?
For example:
class Base {
virtual my_function() = 0;
};
class Derived : Base {
my_function() override;
};
From what I read, the override
keyword is used to make sure that we have the correct signature in the function that we are overriding, and it seems to be its only use.
However, in the case of a pure virtual function, the compiler would throw an error if we used an incorrect signature in the Derived class (or Base class, depending on how one see things). So, is there any point in adding override
at the end of Derived::my_function()
declaration?
Rcpp with c++11 flag in Windows: unrecognized command line option -std=c++11
I wrote a Rcpp code which works fine in linux, But When I want to run it on University labs which have Windows machines. I get this error:
error: unrecognized command line option '-std=c++11'
As in this answer I used -std=c++0x
, But it not working on my code.
Question is: How Can I update g++ in windows. Any other suggestion?
What is a fast integer ? What defines how fast an integer is?
I am not a c++ expert but I started learning through www.learncpp.com which is great btw and I suggest for any new c++ learner and in this topic:
it was mentioned that
The fast type (int_fast#_t) gives you an integer that’s the fastest type with a width of at least # bits (where # = 8, 16, 32, or 64). For example, int_fast32_t will give you the fastest integer type that’s at least 32 bits.
What does he mean by the fastest integer type ? what defines the speed ?
I assume that not all integers are accessed the same way, some are easier to access than the others but what I need to know what could lead to that speed of access ?
I have read in one question that:
On some processors, if a variable gets stored in a register which is longer, the compiler may have to add extra code to lop off any extra bits. For example, if uint16_t x; gets stored in a 32-bit register on the ARM7-TDMI, the code x++; may need to be evaluated as x=((x+1)<<16)>>16);. On compilers for that platform, uint_fast16_t would most likely be defined as synonymous with uint32_t to avoid that.
What makes that faster ? As in either case 32 bits will be looped over in the register level.
std::cin error for large file
I was benchmarking some I/O code with large input( 1Mb text file of integer, separated by tab, spaces or endline) then the normal cin method
int temp;
cin >> temp;
while(temp!=0){ cin >> temp;}
Got into an infinite loop with temp value at 15 , there is no such long sequences in the input file however
The cooked up integer parsing method, with fread however did just fine with a clock time of around 0.02ms
void readAhead(size_t amount){
size_t remaining = stdinDataEnd - stdinPos;
if (remaining < amount){
memmove(stdinBuffer, stdinPos, remaining);
size_t sz = fread(stdinBuffer + remaining, 1, sizeof(stdinBuffer) - remaining, stdin);
stdinPos = stdinBuffer;
stdinDataEnd = stdinBuffer + remaining + sz;
if (stdinDataEnd != stdinBuffer + sizeof(stdinBuffer)){
*stdinDataEnd = 0;
}
}
}
int readInt(){
readAhead(16);
int x = 0;
bool neg = false;
// Skipp whitespace manually
while(*stdinPos == ' ' || *stdinPos == '\n' || *stdinPos == '\t'){
++stdinPos;
}
if (*stdinPos == '-') {
++stdinPos;
neg = true;
}
while (*stdinPos >= '0' && *stdinPos <= '9') {
x *= 10;
x += *stdinPos - '0';
++stdinPos;
}
return neg ? -x : x;
}
Any direction on how might cin get stuck ?
copy object behind shared pointer containing a list of shared pointers
I have a shared_ptr<Tree> tree
and a shared_ptr<TreeNode> node
that contains a list of childrens as shared pointers.
class TreeNode
{
protected:
std::weak_ptr<TreeNode> parent;
/**
A list containing the children of this node
*/
std::shared_ptr<std::vector<std::shared_ptr<TreeEdge>>> children;
...
A Tree needs only to be given a TreeNode as its root.
Tree::Tree(const shared_ptr<TreeNode> root)
: root(root)
{}
So to create that sub Tree I try to get a TreeNode and call the Tree constructor with it.
shared_ptr<TreeNode> treeNode = oldTree->getASpecialNode();
shared_ptr<Tree> newTree = make_shared<Tree>(treeNode);
Now the root of newTree
is treeNode
. But the problem is, every TreeNode is pointing to its parent. So does treeNode
.
weak_ptr<TreeNode> TreeNode::getParent() const
{
return parent;
}
When calculating the root by going through the parents of any TreeNode in newTree
, we will reach a different root node than newTreeNode
, because newTreeNode
itself has a parent.
Deleting that parent is no solution, because the object is shared and we will need it in the original Tree. So the only solution I see is to copy the TreeNode and copy all it's members.
How can I do that?
Based on other answers on SO I tried this:
std::shared_ptr<TreeNode> TreeNode::clone() const
{
auto clone = new TreeNode (*this );
clone->setParent(weak_ptr<TreeNode>());
return shared_ptr<TreeNode>(clone);
}
But still calculating the parents will lead to the original root node. So I wasn't able to create a sub tree.
I have the feeling that it's wrong to use shared_ptr
for Tree
and TreeNode
, but it's not my code. I just need to add a feature.
Measure of uniformity / homogeniy in an Image c++, opencv
I would like to use a metric which would be a good representation of the homogeneity / uniformity in a Gray - Scale image.
This is an example of a non uniform image:
This is an example of a uniform image:
any thoughts on how should I approach this problem ??
Need help on reading lines of an xml file with c++
Does someone knows how I can read an XML file. I need to read lines by their Id . Thank you
<model:process id="_bKz-cGFkEee5cJFFBmbIGQ" name="Patient">
<model:ioSpecification id="_rEuOsmFqEee5cJFFBmbIGQ">
<model:inputSet id="_rEuOs2FqEee5cJFFBmbIGQ"/>
<model:outputSet id="_rEuOtGFqEee5cJFFBmbIGQ"/>
</model:ioSpecification>
OpenGL intersection between vector and face
I have a terrain and an object which should moves over the terrain so I made a function that can detect which face is the origin of the object locate above so I should set the Y of the object with the accurate height of the intersection point between the vector from the object origin perpendicular with the face, I have the three vertices of the face so I can calculate its normal and its origin and maximum and minimum pointes (bounded box).
expected primary-expression before '...' token calling templated method of templated class
I have a templated static method in a templated class, and I'm calling it from a templated function. Compilation fails with the error error: expected primary-expression before '...' token
.
Here's a sample code. It has some unused template parameters, but fails exectly the same as my real code, where these parameters are important.
temp late<typename T>
class Run {
public:
template<typename ...Args>
static void run(Args... args) {}
};
template <typename T, typename ...Args>
void
run2(Args ...args)
{
Run<int>::run<Args...>(args...); // OK
Run<T>::run<Args...>(args...); // Fail on first . in Args...
}
int main() {
run2<int>(1, 2, 3);
return 0;
}
Compilation errors:
% g++ -std=gnu++11 -o try try.cc
try.cc: In function 'void run2(Args ...)':
try.cc:13:21: error: expected primary-expression before '...' token
Run<T>::run<Args...>(args...); // Fail on first . in Args...
^
try.cc:13:21: error: expected ';' before '...' token
Used gcc 4.8.5 on Ubuntu. Also reproduces with gcc 6.3
Any idea what's going on? The difference between the working line (with <int
>) and the failing line (with <T>
) is particularly confusing.
What exactly is std::labs() there for?
I read about the std::abs()
function from using cppreference.
On that page I have also seen a std::labs()
function. Which has the same prototype as one of the std::abs()
overloads (the one for long
).
long abs( long n );
long labs( long n );
and
long long abs( long long n );
long long llabs( long long n );
So,
- What exactly does
std::labs()
? - Where and When I use
std::labs()
? - What is the difference between
std::abs()
andstd::labs()
?
template function specialization with static keyword
I have this kind of code that worked fine with gcc 4.14 and VS but when I compile with C++11 compiler it is giving following error. "explicit template specialization cannot have a storage class". If i remove the static keyword it works perfectly fine. is there any other way so that i don't have to remove the static keyword?.
#include <iostream>
using namespace std;
namespace Asad{
template <typename T>
static void foo(const T param)
{}
template <>
static void foo<int>(const int param)
{}
template <>
static void foo<bool>(const bool param)
{}
}
int main() {
cout<<"aaaaaaaaaaaa"<<endl;
return 0;
}
mardi 26 septembre 2017
Assist me with a pointer based c++ data structure program please
I'm making a program using a custom data structure with 4 links and 4 variables each. The code is still incomplete, but what I expected from this much is not outputting the result. From what is written, if you choose a as first input, I expected to go ahead and traverse the map without energy depletion. However, all the if conditions are getting satisfied, thus outputting '>' 4 times an not showing the elements after the '>', which, for the first iteration, should be 'b'. Have a look at the code, and please help me out if you get what is glitching out.
#include <iostream>
#include <cstdlib>
using namespace std;
void dogwalk();
class map
{
public:
int d1,d2,d3,d4;
map* w1;
map* w2;
map* w3;
map* w4;
map()
{
d1=0;
d2=0;
d3=0;
d4=0;
}
}*start,*current;
map* mapbuilder()
{
map a[7];
start=&a[0];
a[0].d1=1;
a[0].d2=0;
a[0].d3=0;
a[0].d4=0;
a[0].w1=&a[1];
a[0].w2=&a[0];
a[0].w3=&a[0];
a[0].w4=&a[0];
a[1].d1=1;
a[1].d2=3;
a[1].d3=5;
a[1].d4=3;
a[1].w1=start;
a[1].w2=&a[2];
a[1].w3=&a[5];
a[1].w4=&a[6];
a[2].d1=3;
a[2].d2=4;
a[2].d3=7;
a[2].d4=0;
a[2].w1=&a[1];
a[2].w2=&a[3];
a[2].w3=&a[5];
a[2].w4=&a[2];
a[3].d1=4;
a[3].d2=3;
a[3].d3=6;
a[3].d4=0;
a[3].w1=&a[2];
a[3].w2=&a[3];
a[3].w3=&a[4];
a[3].w4=&a[3];
a[4].d1=6;
a[4].d2=5;
a[4].d3=0;
a[4].d4=0;
a[4].w1=&a[3];
a[4].w2=&a[5];
a[4].w3=&a[4];
a[4].w4=&a[4];
a[5].d1=5;
a[5].d2=3;
a[5].d3=3;
a[5].d4=5;
a[5].w1=&a[4];
a[5].w2=&a[6];
a[5].w3=&a[1];
a[5].w4=&a[2];
a[6].d1=3;
a[6].d2=3;
a[6].d3=0;
a[6].d4=0;
a[6].w1=&a[5];
a[6].w2=&a[1];
a[6].w3=&a[6];
a[6].w4=&a[6];
map* p=&a[0];
return p;
}
int main()
{
cout << "So you paid Miss Augustin a visit today. It\'s her 25th Anniversary. Her husband, Zack, is in Dubai,\nand cannot make it to home today.\n\nYou reach her place, and are standing at the doorway.\na>Ring the calling bell\nb>Turn back and go home.\n";
char c;
cin >> c;
if(c=='a')
{
cout << "She opens after exactly 32 seconds. You wonder why you were counting the seconds, but find no plausible reason.\nShe thanks you for the bouquet of yellow lillies you got for her, and welcomes you inside. However, after some tea, she tells you how her back is aching like anything, and she needs someone to walk Tommy, her dog, for the day. You and Tommy know each other, and you like him. Being a good guy, you volunteer to help. She says she\'ll treat you with a big slice of blueberry cheesecake that she\'s making today, once you return. You can\'t wait for it. So you put the leash on Tommy, and head towards the door.\n\n";
dogwalk();
}
else if(c=='b')
{
cout << "You are a mean person. You don\'t deserve to play this game.\n";
return 0;
}
else
{
cout << "Which part of the two choices, a and b, did you not get?";
main();
}
return 0;
}
int getIndex(map* a,map* b)
{
int x=-1;
for(int i=0;i<7;i++)
{
if ((a+i)==b)
{
x=i;
break;
}
}
return x;
}
int getIndex(char c, string p)
{
int x=-1;
for(int i=0;i<7;i++)
{
if(p[i]==c)
{
x=i;
break;
}
}
return x;
}
void dogwalk()
{
int energy=rand()%50+2;
char places[]={'a','b','c','d','e','f','g'};
cout << "You\'re standing in the front of her house.\nTommy has " << energy << " energy.\n\n";
map* a=mapbuilder();
cout << "The map of the town looks like this:\n";
cout << "f * * * * * e * * * * * * d"<<endl;
cout << "* * * *\n";
cout << "* * * * *\n";
cout << "* * * *\n";
cout << "g * * * b * * * c\n";
cout << " *\n";
cout << " a\n";
cout << "You start at a\n";
current=start;
int i=0,flag=1,dir=0;
string v;
while(true)
{
v="";
map* z=&a[0];
cout << "You can go to the following places: \n";
if(a[i].w1!=&a[i])
{
cout << ">" << places[getIndex(z,a[i].w1)]<< endl;
v=v+places[getIndex(z,a[i].w1)];
}
if(a[i].w2!=&a[i])
{
cout << ">" << places[getIndex(z,a[i].w2)]<< endl;
v=v+places[getIndex(z,a[i].w2)];
}
if(a[i].w3!=&a[i])
{
cout << ">" << places[getIndex(z,a[i].w3)]<< endl;
v=v+places[getIndex(z,a[i].w3)];
}
if(a[i].w4!=&a[i])
{
cout << ">" << places[getIndex(z,a[i].w4)]<< endl;
v=v+places[getIndex(z,a[i].w4)];
}
while(true)
{
char x;
cin >> x;
if(getIndex(x,v)==-1)
cout << "Invalid Input. Try again.\n";
else
{
current=&a[getIndex(x,v)];
cout << "Okay. Now you are at " << x << endl;
}
}
}
}