question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
69,546,592 | 69,546,613 | Non recursive fibonacci function | I was trying to write a non recursive fibonacci function in C++. Here is my code for it:
int fib(const int num)
{
std::vector<int> array{ 0, 1 };
for (int i = 2; i < num; ++i)
{
array[i] = (array[i - 1] + array[i - 2]);
}
return array[num];
}
int main()
{
const int n = 10;
for (int i = 0; i <= n; ++i)
{
cout << fib(i) << " ";
}
}
The compiler gives me a "Debug Assertion Failed" Error with an expression that vector subscript out of range. Could you please tell me what is here wrong? All indexes seemed to be in vector's range...
Thanks!
| You initialized array with only two members, so only the indexes 0 and 1 are valid. Your loop goes from 2 to n which goes beyond the allocated bounds of the array when you do array[i]. To add a new element into a vector you should use push_back() instead. It will allocate new space in the array:
array.push_back(array[i - 1] + array[i - 2]);
|
69,546,908 | 69,547,286 | C++ static class member with private constructor | Why can a private constructor be used in this case? I can't explain it to myself. In this case, I initialize the class field (the type of which is the same class) from the outside, since it is static.
Edit1:
I use C++ 17 (gcc 11.2).
#include <iostream>
using namespace std;
class MainMenu {
public:
MainMenu(const MainMenu& other) = delete;
MainMenu& operator=(const MainMenu& other) = delete;
static MainMenu& GetInstance() { return _instance; }
private:
static MainMenu _instance;
MainMenu() { cout << __PRETTY_FUNCTION__ << endl;}
};
// HERE HERE HERE!!
MainMenu MainMenu::_instance = MainMenu(); // Or just MainMenu MainMenu::_instance;
int main() {
MainMenu::GetInstance();
return 0;
}
Result:
MainMenu::MainMenu()
Process finished with exit code 0
| I would use the following mental model for it:
a. Note that your are instantiating the variable (it would have an incomplete type at the class's scope, so it cannot be inline withing the class's scope), not actually (re)assigning it
b. it is already declared global/static on class's scope so technically the constructor is called within the class. That's fine, even with the constructor being private, because it's called from exactly that privately accessible scope. True, the definition outside looks off, but that does not matter, as the declaration specifies its scope.
Excerpt from C++17 standard:
12.2.3.2 Static data members [class.static.data]
2 The declaration of a non-inline static data member in its class definition is not a
definition and may be of an incomplete type other than cv void. The
definition for a static data member that is not defined inline in the
class definition shall appear in a namespace scope enclosing the
member’s class definition. In the definition at namespace scope, the
name of the static data member shall be qualified by its class name
using the :: operator. The initializer expression in the definition of
a static data member is in the scope of its class (6.3.7)
And the example is your case exactly:
class process {
static process* run_chain;
static process* running;
};
process* process::running = get_main();
process* process::run_chain = running;
Any additional citations from the C++ standard to explain it in a better way are most welcome. :)
|
69,547,319 | 69,547,730 | Reference promotion for a derived class with no data members | I have an interesting problem involving a hierarchy of classes in a library that I maintain. A very simplified view of the situation is as follows:
class Base {
// private data + public interface to said data
};
class ClassA : public Base {
// Behaviour
};
class ClassB : public Base {
// Behaviour
};
So here I have a class that contains the data privately and has a consistent interface. In reality this is a templated class with lots of different storage models. The two derived classes ClassA and ClassB purely add different implementations of the same behaviour and do not contain any data. It should be within the realms of possibility to convert a reference to an instance of ClassA to one of ClassB without invoking any copies. Of course, one can use
ClassA a;
B& a_bref = *reintepret_cast<B*>(&a);
But this breaks all the rules. My question: Is there a safe way to implement such a conversion operator?
| Multiple inheritance
One way to achieve your goal is through multiple inheritance.
class A : virtual public Base {
//...
};
class B : virtual public Base {
//...
};
class AorB : public A, public B {
//...
};
With virtual inheritance, you only have one Base instance that is shared between the A and B that make up AorB. This approach means you need to create a class that knows which subtypes you might want to flip through. This may or may not be a problem for you, depending on your use case.
Strategy
A more flexible approach may be to treat A and B as strategies, and treat Base as the context. In this method, you would not use inheritance. You can separate the data from the interface, so that A and B can inherit the accessor methods, but reference the data.
class Base {
friend class Base_Interface;
//...
};
class Base_Interface {
Base &context_;
//...
Base_Interface (Base &context) : context_(context) {}
template <typename X> operator X () { return context_; }
};
class A : public Base_Interface {
//...
A (Base &context) : Base_Interface(context) {}
};
class B : public Base_Interface {
//...
B (Base &context) : Base_Interface(context) {}
};
Perhaps lazily, there is a template conversion method to allow users of the Base_Interface to convert to some other class that accepts the Base in its constructor. It works out if Base has no public members, with Base_Interface as its only friend.
|
69,547,984 | 69,548,262 | How to get clang to warn about very simple narrowing | If I am using clang tools, what is the recommended way to get clang or some part of the clang toolchain to tell me that e.g. passing an int to a function that takes a short might be a bad idea?
Given this very simple program
static short sus = 0;
void foo(short us) {
sus = us;
}
int main() {
int i = 500000;
foo(i); // any indication from clang this might be a bad idea
return 0;
}
I've tried -Wall and -Wextra,
I've tried clang-tidy with cppcoreguidelines-narrowing-conversions
I've tried clang -analyze
I must be missing something very simple here, right?
| The -Weverything option is useful in situations like this. It enables every warning option that clang has, including many that -Wall -Wextra doesn't include. Many of them are useless or counterproductive, but if there is one that warns on the code you consider problematic, this will let you find it, and tell you which option would enable it specifically. Try it on godbolt.
In this case, using -Weverything shows us:
<source>:8:7: warning: implicit conversion loses integer precision: 'int' to 'short' [-Wimplicit-int-conversion]
foo(i); // any indication from clang this might be a bad idea
~~~ ^
So the option you want is -Wimplicit-int-conversion.
|
69,548,441 | 69,548,463 | Error: Operand of '*' must be a pointer but has type "double" | I know this question has been asked before, but the answers there don't seem to be related to the issue I'm having.
Here's my code
#include <iostream>
int main()
{
double E;
double R;
double t;
double C;
std::cout << "This program will calculate the current flowing through an RC curcuit!\n\n";
std::cout << "Please enter the power source voltage value in Volts: ";
std::cin >> E;
std::cout << "\n\n";
std::cout << "Please enter the total resistance value in Ohms: ";
std::cin >> R;
std::cout << "\n\n";
std::cout << "Please enter the time elapsed after the switch closed Seconds: ";
std::cin >> t;
std::cout << "\n\n";
std::cout << "Please enter the total capacitance value in Farads: ";
std::cin >> C;
std::cout << "\n\n";
double RC = R * C;
double ER = E / R;
double pow = -t / RC;
double expo = 2.71828 ** pow; //this line is the problem...
double I = ER * expo;
std::cout << "The current flowing through this circuit is: " << I;
return 0;
}
I really don't know what this means, despite looking it up on Google... Can someone please explain, generally, how to avoid this type of error and not just solve this particular instance of it?
| C++ doesn't have a ** operator like some languages do. You need to use the std::pow function to do exponents, or std::exp for the particular case of raising the mathematical constant e to a power.
#include <cmath>
...
double expo = std::exp(pow);
|
69,548,632 | 69,608,716 | How to call a void function within if statement (Arduino) | I wrote a code supposed to do the following: if I press one button while in loop void btnpress(), the program is sent to another function void blink2(), and then one led goes on and after 3 secs the led should go off, and it should also return to void btnpress() again via btnpress();.
The issue is that if i press the button and release, the led goes on and stay still infinitely on, program seems not to execute the following last parts digitalWrite(LED_BUILTIN, LOW); and btnpress();.
const int btnpin = 9;
int btnstate = 0;
unsigned long currentTime;
unsigned long previousTime;
const long period = 3000;
// the setup
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
pinMode(btnpin, INPUT);
Serial.begin(9600);
}
// the loop
void loop()
{
btnpress();
}
void btnpress()
{
Serial.println("Press button");
delay(500);
btnstate = digitalRead(btnpin);
if (btnstate == HIGH) {
previousTime = millis();
blink2();
}
}
void blink2()
{
if (currentTime - previousTime >= period) {
Serial.println("Led on");
previousTime = currentTime;
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on
}
else {
Serial.println("Led off");
digitalWrite(LED_BUILTIN, LOW);
btnpress();
}
}
|
if I press one button while in loop void btnpress(), the program is
sent to another function void blink2(), and then one led goes on and
after 3 secs the led should go off, and it should also return to void
btnpress() again via btnpress();
According to this statement, I can suggest you to use the following code just to be sure if your functions are working according to your reqirement.
const int btnpin = 9;
int btnstate = 0;
//unsigned long currentTime;
//unsigned long previousTime;
const long period = 3000;
// the setup
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
pinMode(btnpin, INPUT);
Serial.begin(9600);
}
// the loop
void loop()
{
btnpress();
}
void btnpress()
{
Serial.println("Press button");
delay(500);
btnstate = digitalRead(btnpin);
if (btnstate == HIGH) {
// previousTime = millis();
blink2();
}
}
void blink2()
{
Serial.println("Led on");
digitalWrite(LED_BUILTIN, HIGH);
delay(3000);
Serial.println("Led off");
digitalWrite(LED_BUILTIN, LOW);
//btnpress(); It's already inside the Void loop
}
If it's working well then function call is okay.
And there has no issue with "How to call a void function within if statement (Arduino)"
The problem may be inside your if statement,
if (currentTime - previousTime >= period) {
Serial.println("Led on");
previousTime = currentTime;
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on
}
here, the currentTime is not Defined.
|
69,549,382 | 69,559,855 | What trait makes uninitialized_copy(_n) sustituable by copy(_n)? | I am trying to understand the meaning of the types properties and supported operations, https://en.cppreference.com/w/cpp/types .
I have a library that implements in terms of low level functions things similar to std::copy_n, of course I would have to implement uninitialized_copy as well, but for many of the types, that are in some sense trivial, I don't want to repeat code and delegate one to the other.
What property makes uninitialized_copy(_n) semantically substitutable by copy(_n)?
My guess is that it is std::is_trivially_default_constructible<T>::value, but I am not sure.
The justification is that if something is trivially default constructible I can skip the initialization before the assignment.
(Initially I though it could be std::is_trivially_assignable<TSource, T>::value)
Of course I could play safe and ask for std::is_trivial<T>::value, but I want to be more targeted.
I know there are could be Machiavellian or misleading definitions of these traits, but suppose I want to trust them.
Example code:
template<class... As, class... Bs>
auto uninitialized_copy_n(
my_iterator<As...> first, Size count,
my_iterator<Bs...> d_first
)-> my_iterator<Bs...> {
using T1 = typename my_iterator<As...>::value_type;
using T2 = typename my_iterator<Bs...>::value_type;
if constexpr(std::is_trivially_constructible<T2>::value){
return copy_n(first, count, d_first);
}
... another implementation or abort
}
| To replace uninitialized_copy with copy, the two actions must be equivalent:
uninitialized_copy: construct a new object of type Destination from an object of type Source
copy: assume an object of type Destination exists and assign to it from an object of type Source
One must put sufficient requirements on the type such that the destination object exists and that construction and assignment give the same value.
is_trivially_default_constructible is neither necessary nor sufficient to assume an object exists at a memory location. Instead, the destination type must be an implicit lifetime type. That is not a recursive condition, so we must require the type be an implicit lifetime type, and recursively all members or subobjects are implicit lifetime types.
For example, scalars or classes with trivial default constructor and trivial destructor will work.
Secondly, we need construction and assignment to give the same result. This is impossible if these operations aren't trivial. But in C++, the value of an object is only guaranteed to be unchanged by such operations for trivially copyable types, which tie the value to the representation. Therefore, we probably want the destination to be trivially copyable.
This gives us:
std::is_trivially_default_constructible_v<Destination>
std::is_trivially_destructible_v<Destination>
std::is_trivially_constructible_v<Destination, const Source&>
std::is_trivially_assignable_v<Destination&, const Source&>
std::is_trivially_copyable_v<Destination>
This simplifies to:
std::is_trivial_v<Destination>
std::is_trivially_constructible_v<Destination, const Source&>
std::is_trivially_assignable_v<Destination&, const Source&>
Note that libstdc++ requires both types to be trivial and the Destination assignable and constructible from the Source. The comment references a slightly different condition on the ranges algorithm instead.
The libstdc++ requirement has observable differences. See this example. value should be 1 (from construction) but is being populated with 2 (from assignment). I cannot find any license given to implementations to differ in this way.
The libstdc++ logic was recently found to be buggy and likely still is.
|
69,549,493 | 69,549,546 | c++ Type error for fixed-size array being passed to template requesting array pointer | I have a template function like the following:
template<typename T>
T foo(byte* &buffer){
...
}
When I try to access it with a fixed-size array I get an error:
byte buffer[100] = {};
foo<int>(buffer);
However, when I create a new variable from buffer and pass that, no error:
byte buffer[100] = {};
auto b = buffer;
foo<int>(b);
What is the type of buffer? Is it not a byte*? Is there a way to cast it to a byte*? This only happens with a template function, otherwise it works as expected.
| The error in the first case is because the array buffer does not decay because you have passed it be reference. That is you cannot bind a reference to a pointer to byte to an array of byte.
While in the second case b is a pointer which you can pass by reference.
Solution 1
One way to solve this is by removing the reference from the function parameter i.e., by the argument by value. So passing by value looks like:
template<typename T>
T foo(byte* buffer){//note pass by value
...
}
Note in solution 1 you can modify the array from inside the function through the pointer. One disadvantage of solution 1 is that here you can also pointer other pointers(like pointer to int) so you have to take care by yourself that you don't try to access anything that is out of bound of the array. Other alternative would be to just pass the array by reference as you originally intended as shown in Solution 2.
Solution 2 Pass the array by reference
template<typename T, std::size_t N>
T foo(byte (&buffer)[N])//this time you're passing the actual array by reference and not the pointer to its first element
{
}
Now in solution 2 you have passed the array by reference and you can modify it directly inside the function template. Now foo<int>(buffer); will work.
|
69,549,923 | 69,549,980 | Result of method used to call another method yields inconsistent results | I currently have to write a program that allows a user to pick between two objects to test.
This isn't the same program exactly but it's the same premise.
class defined by header file
#include <iostream>
class example {
private:
int x;
public:
example() {
x = 10;
}
void setNum(int input) {
x = input;
}
int getNum() {
return x;
}
};
Test main and selectObj method
#include <iostream>
#include "Header.h"
example selectObj(example A, example B) {
int selection;
std::cout << "Select object 1 or 2: ";
while (true) {
std::cin >> selection;
if (selection == 1)
return A;
else if (selection == 2)
return B;
else
std::cout << "Inavlid option, try again: ";
}
}
int main() {
example test1, test2;
selectObj(test1, test2).setNum(25);
std::cout << selectObj(test1, test2).getNum();
return 0;
}
selectObj is supposed to return an object. It runs but it isn't doing what setNum is supposed to do.
Suppose you choose option 1 for both calls of selectObj. It looks something like this.
Select object 1 or 2: 1
Select object 1 or 2: 1
10
It should have printed out 25 but instead, setNum isn't really changing the value of test1.
However, if I write
test1.setNum(25);
std::cout << test1.getNum();
Then it does indeed set test1's x value to 25.
Again, this isn't exactly like the program I had written (it is changed now and wouldn't like to rewrite that). However, it is an identical representation of the same concept.
| The problem is that you're passing and returning the arguments by value instead of reference. To solve this you can pass and return the arguments by reference as shown in the below modified code:
main.cpp
#include <iostream>
#include "Header.h"
//return and pass by reference
example& selectObj(example &A, example &B) {
int selection;
std::cout << "Select object 1 or 2: ";
while (true) {
std::cin >> selection;
if (selection == 1)
return A;
else if (selection == 2)
return B;
else
std::cout << "Inavlid option, try again: ";
}
}
int main() {
example test1, test2;
selectObj(test1, test2).setNum(25);//this sets the value of x member of the object that the user chooses
std::cout << selectObj(test1, test2).getNum();
return 0;
}
The output of the above program when the user enters option 2 is:
Select object 1 or 2: 1
Select object 1 or 2: 1
25
|
69,550,242 | 69,552,124 | Question about C++ global variable in JNI on android | Is using C++ global variable in JNI on android acceptable?
If so, I'd like to know the life-cycle of it.
When a.cpp is connected to b.java and instance of b is created(is global variable initialized at this point?) and destroyed(is global variable destroyed at this point?).
In a nutshell, global variable in C++ side share it's won life-cycle with connected Java instance?
| The lifetime of native objects is tied to the lifetime of the native library that hosts them.
This, in turn, is governed by the lifetime of the Java ClassLoader that loaded the library:
In addition, native libraries can be unloaded when their corresponding class loaders are garbage collected.
In Android applications that will never happen, so you can assume that your native objects survive as long as the application does.
|
69,550,341 | 69,555,300 | Allocating an object of abstract class type in OMNET ++ define_module | I build OMNET project. The main codes as follow:
Routing.h
class INET_API Routing : public cSimpleModule, public ILifecycle, public cListener { }
Routing.ned
simple Routing like IManetRouting{ }
Routing.cc
Define_Module(Routing);
When I build the project, the error- Allocating an object of abstract class type Routing.
| And this is correct. You cannot create an instance of an abstract class. You MUST implement all the methods defined by ILifecycle and cListener otherwise the behavior of the class is undefined and it is considered abstract.
|
69,550,439 | 69,550,509 | In-place creation of std::optional<MyStruct> | Assume the following code snippet:
#include <optional>
struct MyStruct
{
// MyStruct(int a) : a(a) {}
int a;
};
int main()
{
std::optional<MyStruct> ms1 = std::make_optional<MyStruct>(1);
std::optional<MyStruct> ms2{2};
std::optional<MyStruct> ms3;
ms3.emplace(3);
std::optional<MyStruct> ms4(std::in_place, 4);
}
This works as intended using c++20 with gcc 11.2, all of those four creation methods fail compilation on clang (Compiler explorer link)
To make it work with clang, I need to uncomment the constructor.
My main question is: Which compiler is correct, clang or gcc?
Follow-up question: If clang is correct, is there any way to create a struct without constructor in an optional, without copying the struct into it, e.g. std::optional<MyStruct> ms{MyStruct{3}}?
|
My main question is: Which compiler is correct, clang or gcc?
GCC is correct. Since Clang has not yet implemented P0960, this will cause the following assert to fail and disable the optional's constructor:
static_assert(std::is_constructible_v<MyStruct, int>);
is there any way to create a struct without constructor in an
optional, without copying the struct into it?
Before Clang completes the P0960, I think there is no way. But since MyStruct{3} is an rvalue, it will move into optional.
|
69,550,614 | 69,560,240 | Rotating an image using Borland C++ Builder and Windows API functions | I built this example to quickly rotate images 90 degrees but I always get a cut of the image on the sides. After many tests, unfortunately I still don't understand the cause of the problem.
void rotate()
{
Graphics::TBitmap *SrcBitmap = new Graphics::TBitmap;
Graphics::TBitmap *DestBitmap = new Graphics::TBitmap;
SrcBitmap->LoadFromFile("Crayon.bmp");
DestBitmap->Width=SrcBitmap->Width;
DestBitmap->Height=SrcBitmap->Height;
SetGraphicsMode(DestBitmap->Canvas->Handle, GM_ADVANCED);
double myangle = (double)(90.0 / 180.0) * 3.1415926;
int x0=SrcBitmap->Width/2;
int y0=SrcBitmap->Height/2;
double cx=x0 - cos(myangle)*x0 + sin(myangle)*y0;
double cy=y0 - cos(myangle)*y0 - sin(myangle)*x0;
xForm.eM11 = (FLOAT) cos(myangle);
xForm.eM12 = (FLOAT) sin(myangle);
xForm.eM21 = (FLOAT) -sin(myangle);
xForm.eM22 = (FLOAT) cos(myangle);
xForm.eDx = (FLOAT) cx;
xForm.eDy = (FLOAT) cy;
SetWorldTransform(DestBitmap->Canvas->Handle, &xForm);
BitBlt(DestBitmap->Canvas->Handle,
0,
0,
SrcBitmap->Width,
SrcBitmap->Height,
SrcBitmap->Canvas->Handle,
0,
0,
SRCCOPY);
DestBitmap->SaveToFile("Crayon2.bmp");
delete DestBitmap;
delete SrcBitmap;
}
| If rotating the whole image, the width and height for destination image should be flipped:
DestBitmap->Width = SrcBitmap->Height;
DestBitmap->Height = SrcBitmap->Width;
The transform routine was centering the image based on original width/height. We want to adjust x/y position to push the starting point to left/top for BitBlt
int offset = (SrcBitmap->Width - SrcBitmap->Height) / 2;
BitBlt(DestBitmap->Canvas->Handle, offset, offset, SrcBitmap->Width, SrcBitmap->Height,
SrcBitmap->Canvas->Handle, 0, 0, SRCCOPY);
|
69,550,687 | 69,550,770 | Using recursion in C++ class - Passing its own data member | I am writing a pre-order traversal for Tree class:
class Tree {
public:
...
void preOrder(TreeNode* root)
{
if (root != nullptr)
{
cout << root->key << " ";
preOrder(root->left);
preOrder(root->right);
}
}
private:
TreeNode* root = nullptr;
}
I want to pass Tree's root data member to preOrder so that in main.cpp, I call the function like this:
Tree.preOrder();
So I code like this
void preOrder(TreeNode* root = this->root)
but compiler generate error
'this' may only be used inside a nonstatic member function
Is there anyway to fix this? Or I am going to use iterative instead of recursive traversal.
| Like the error message says, you can't use this in a method parameter. Just define a 0-parameter overload of preOrder() that calls the 1-parameter version.
class Tree {
public:
...
void preOrder()
{
preOrder(root);
}
void preOrder(TreeNode* aRoot)
{
if (aRoot)
{
cout << aRoot->key << " ";
preOrder(aRoot->left);
preOrder(aRoot->right);
}
}
private:
TreeNode* root = nullptr;
};
|
69,551,486 | 69,553,340 | Problem on finding the number of leave node in a binary tree in C++ using array | I am working on a C++ code to find out the number of leave node in a binary tree using array input
my code is:
int leaf(int data[],int size) {
int result = 0;
for (int i = 0; i <= size; i++) {
if (data[i] == -1)
i++;
if (((data[(2*i)+1] == -1) && (data[(2 * i) +2] == -1)) || ((data[(2 * i) +1] == NULL) && (data[(2 * i) +2] == NULL)))
result++;
}
return result;
}
int main(){
int data[]= { 1,9, 6, 8 ,12, 2,-1 ,10, -1 ,-1 ,-1, 5 };
int size = 12;
cout << "count of leave node: " << leaf(data, size)<< endl;
}
In the array, the element -1 is the empty node.
The tree is like:
1
/ \
9 6
/ \ /
8 12 2
/ /
10 5
The total number of the leave node should be 3 which is (12,10,5), but the result of my code is 2.
Can I know what wrong with my code and how to fix it.
Big Thanks!
| Some issues:
When the for loop variable gets to equal size you will have an out of bounds index-access to data. The loop should exit in that case -- size is an invalid index, so use i < size as loop condition.
Your for loop increments the loop variable with i++; there should be no reason to increment i on top of that when you find a -1 value in the data. What if i will be out of bounds by doing that? What if the next data element also has a -1 value? In either case your code goes wrong. Instead use data[i] != -1 as a condition for the rest of the logic in the loop's body.
You should check that the index you use for data is not out of bounds, before actually making that index access. It is not safe to compare an out of bounds data entry with NULL: the value of an out of bounds access is undefined and int should never have to be compared with NULL. NULL is used in the context of pointers.
You should also foresee the case where the left child is -1 and the right child is out of bounds.
Here is a fix for those issues:
int leaf(int data[], int size) {
int result = 0;
for (int i = 0; i < size; i++) {
if ( data[i] != -1 &&
(2*i+1 >= size || data[2*i+1] == -1) &&
(2*i+2 >= size || data[2*i+2] == -1) )
result++;
}
return result;
}
This logic assumes that the array will be organised like a complete tree. Some array encodings like this will not have two -1 entries for filling up the "children" of another -1 entry, but just omit them, making the formula 2*i+1 and 2*i+2 invalid.
Take for example this tree:
1
\
2
\
3
If the encoding is a complete tree encoding, then it will be {1, -1, 2, -1, -1, -1, 3}. If it is the more compact encoding where -1 entries will not have children entries, then it will be {1, -1, 2, -1, 3}.
Your example does not show which of the two encodings you are dealing with as it would turn out to be the same array for your example tree. If it is the later encoding, you need a different algorithm altogether.
|
69,551,783 | 69,551,885 | Extend from 3 hour slot to N days | I want to set up params.arrival_rate every 3 hours of sim_time. This comprises a day but I would like to extend to N days. So, each time slot of 3 hours (in the code below is in minutes) of this N day, params.arrival_rate takes a value. Any optimal function to do so?
My actual code looks like this:
if(sim_time >= 0 && sim_time <= 180) //00:00 - 03:00
{
params.arrival_rate = 10;
}
else if(sim_time > 180 && sim_time <= 360) //03:00-06:00
{
params.arrival_rate = 9;
}
else if(sim_time > 360 && sim_time <= 540) //06:00-09:00
{
params.arrival_rate = 10.5;
}
else if(sim_time > 540 && sim_time <= 720) //09:00-12:00
{
params.arrival_rate = 12;
}
else if(sim_time > 720 && sim_time <= 900) //12:00-15:00
{
params.arrival_rate = 11.5;
}
else if(sim_time > 900 && sim_time <= 1080) //15:00-18:00
{
params.arrival_rate = 11;
}
else if(sim_time > 1080 && sim_time <= 1260) //18:00-21:00
{
params.arrival_rate = 10.5;
}
else if(sim_time > 1260 && sim_time <= 1440) //21:00-24:00
{
params.arrival_rate = 9;
}
else //by default
{
params.arrival_rate = 9;
}
Many thanks.
| Assuming you want the same pattern every day, it suffices to take the time modulo 1440 minutes:
int day_time = sim_time % 1440;
int day_no = sim_time / 1440;
Now you can use day_time to get the time in the current day and use that to calculate params.arrival_rate. day_no will contain the day number (starting from 0).
As a further enhancement, consider using an array for your arrival rates instead of a long if-elseif chain:
const double arrival_rates[] = { 10, 9, 10.5, 12, 11.5, 11, 10.5, 9 };
params.arrival_rate = arrival_rates[day_time / (3 * 60)];
The calculation inside the brackets will round down the day_time to the start of the nearest three-hour block.
|
69,552,216 | 69,552,376 | A Problem with Recursive Void Lambda Expressions in C++ | I would like to implement recursive void lambda expressions inside a function. I have created the C++ snippet below to illustrate my problem. Lambda is the recursive void lambda expression I would like to build inside Func1. However, when I compile with g++, I run into the following compiler errors:
Lambda_void.cpp: In function ‘void Func1(std::vector<int>&)’:
Lambda_void.cpp:6:10: error: variable or field ‘Lambda’ declared void
void Lambda = [](std::vector<int> &A)
^~~~~~
Lambda_void.cpp: In lambda function:
Lambda_void.cpp:11:13: error: ‘Lambda’ was not declared in this scope
Lambda(A);
^~~~~~
Lambda_void.cpp:11:13: note: suggested alternative: ‘__lambda0’
Lambda(A);
^~~~~~
__lambda0
Lambda_void.cpp: In function ‘void Func1(std::vector<int>&)’:
Lambda_void.cpp:14:5: error: ‘Lambda’ was not declared in this scope
Lambda(A);
^~~~~~
Changing to the lambda variable declaration from void to auto does not solve anything as the compiler has not identified the variable type before the first recursion. Are there any possible workarounds here? And why doesn't g++ allow to do this?
#include <iostream>
#include <vector>
void Func1(std::vector<int> &A)
{
void Lambda = [](std::vector<int> &A)
{
while (A.size() < 5)
{
A.push_back(1);
Lambda(A);
}
};
Lambda(A);
}
int main()
{
std::vector<int> C;
Func1(C);
for (auto& i : C) {std::cout << i << " ";}
std::cout << std::endl;
return 0;
}
| See this question for recursive lamda-functions explanation. You can declare your Lambda as std::function<void(std::vector<int>&)> and capture it inside lambda:
std::function<void(std::vector<int>&)> Lambda;
Lambda = [&Lambda](std::vector<int>& A) {
while (A.size() < 5) {
A.push_back(1);
Lambda(A);
}
};
Lambda(A);
|
69,552,348 | 69,552,582 | Understanding macro code statement with lambda and __attribute__ | My program(C++) is defining a macro for throw statements. It is something like:
#define FOO_THROW(some-exception-type, some-error-message) \
do \
{ \
[&]() __attribute__((cold, noinline)) \
{ \
using exception_type = some-exception-type; \
std::ostringstream ss; \
ss << some-error-message << ""; \
throw exception_type(ss.str()); \
} \
(); \
} \
while (0);
Then, it is getting called in the program, something like:
FOO_THROW(std::runtime_error, "error specfic message here")
I can see that we use do...while(0) structure with the macro, what I want to understand is the use of lambda and __attribute__ here, can someone explain that in simple words?
Basically, my focus is what is the need of lambda function here, when it can be done without it, is there can be any specific advantage of it here?
I am a beginner in C++, so any hint in the right direction will do as well!
| do...while(0) allows the macro to by called with semicolon at the end, i.e. macro(x,y,z); (note the semicolon at the end), that's an old trick back from C, you can look it up separately.
As for the rest... it defines a lambda (immediate function object) capturing everything by reference (not sure why) that throws exception of a given type with a given message and calls it immediately, effectively throwing an exception.
The attributes signify the lambda is unlikely to be called (cold) and prevent from inlining (noinline), see: https://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Function-Attributes.html
|
69,552,467 | 69,704,068 | clang format: break before braces, empty line after opening brace and empty line before closing brace | I'm trying to format classes inside namespaces in the following way (BreakBeforeBraces: Allman):
namespace test_a::test_b
{
struct A
{
int a;
int b;
};
} // namespace test_a::test_b
but clang format keeps changing it to
namespace test_a::test_b
{
struct A
{
int a;
int b;
};
} // namespace test_a::test_b
The workaround in this question works only with configurations like BasedOnStyle: Google no brakes before opening braces for example
namespace test_a::test_b {
struct A {
int a;
int b;
};
} // namespace test_a::test_b
Same for this answer
I want clang-format to always add an empty line after namespace opening brace and before closing brace, is that possible?
For clarity, this is the clang-format I use
---
BasedOnStyle: Google
AccessModifierOffset: -4
AlignConsecutiveDeclarations: 'true'
BinPackArguments: 'false'
BinPackParameters: 'false'
IndentWidth: '4'
AlignConsecutiveAssignments: 'true'
ColumnLimit: 120
BreakBeforeBraces: Allman
AllowShortIfStatementsOnASingleLine: false
...
| clang format can't do that specifically for namespace for the moment, but you can use KeepEmptyLinesAtTheStartOfBlocks to put empty line for all blocks. what if you use BreakBeforeBraces: Custom ?
|
69,552,769 | 69,554,437 | C++: Alternative to the CHtmlVIew to show PDF/HTML files in MFC based application | Are the any alternatives how to display PDF/HTML file in the MFC based application without using ActiveX elements like CHtmlView?
Thanks in advance.
| The alternative would be WebView2. It uses the Microsoft Edge (Chromium) browser engine, unlike CHtmlView that's based on IE.
If the reason you are looking for an alternative is, that you need a more up-to-date browser implementation, then WebView2 delivers. If, on the other hand, you are looking for an alternative, that's easier to use, then not a whole lot changes. Either one expects very intimate familiarity with COM and C++.
|
69,552,907 | 69,553,029 | C++ passing data from object of class A to object of derived class B | For the sample code below, I'm trying to pass (or attribute, if that suits you better) the data from object of class A to the object of derived class B. What I don't understand so far, is how do I transfer the data from the parent class object, to the derived class object.
The "code" below expresses how I've tried to do that.
class Foo {
protected:
string Name, Surname;
public:
void readData()
{
cin >> Name >> Surname >> ;
}
}
class Bar : public Foo {
public:
Bar(Foo a)
{
Name = Name;
Surname = Surname;
}
void printData()
{
//code
}
}
int
main()
{
Foo a;
a.readData();
Bar b(a);
b.printData()
}
| Minimal changes to make your code compile is using Foos copy constructor and simply access the inherited members in Bar::printData:
#include <string>
#include <iostream>
class Foo{
protected:
std::string Name, Surname;
public:
void readData()
{
std::cin >> Name >> Surname;
}
};
class Bar : public Foo
{
public:
Bar (const Foo& a) : Foo(a) { }
void printData()
{
std::cout << Name << " " << Surname;
}
};
int main()
{
Foo a;
a.readData();
Bar b(a);
b.printData();
}
|
69,553,402 | 69,553,448 | C++: Return the iterator pointing to element equally to the target | I want to find out the iterator pointing to an element equal to the target.
The following code does not work for me, what's wrong with this code?
#include <iostream>
#include <vector>
template <typename T>
typename std::vector<T>::iterator find_it(std::vector<T> vec, const int target){
std::vector<T>::iterator it = vec.begin();
while(it != vec.end() ){
if(*it == target) return it;
it++;
}
return vec.end();
}
int main() {
std::vector<int> vec {1,2,3,4,10};
std::vector<int>::iterator res = find_it(vec, 1);
std::cout << *(*res) << std::endl;
return 0;
}
| vec is passed by-value, it'll be destroyed when find_it returns, the returned iterator to it is dangling, dereference on the iterator leads to UB.
You can change it to pass-by-reference.
template <typename T>
typename std::vector<T>::iterator find_it(std::vector<T>& vec, const int target){
typename std::vector<T>::iterator it = vec.begin();
while(it != vec.end() ){
if(*it == target) return it;
it++;
}
return vec.end();
}
|
69,553,581 | 69,554,328 | Does calling std::terminate violate noexcept? | Suppose I have a function which may call std::terminate:
int my_fun(int i) noexcept {
if(i==0) std::terminate();
return 3/i;
}
Am I allowed to declare this noexcept? Nothing is 'thrown' as far as I can tell...
| You are correct and can safely define your function noexcept.
The function std::terminate itself is noexcept and does not throw anything. It just terminates your program, and your program will never reach the return statement or reach the end of the function scope.
As the behaviour of std::terminate() can be overridden with std::terminate_handler, it is advised to use std::abort() instead, to ensure proper abortion of your program.
If you would invoke a function that throws an exception, this would be checked at the end of your function scope, in which it will terminate your program.
|
69,553,669 | 69,553,863 | New operator followed by address? | What is the following code doing?
int a;
int *b;
b = new (&a) int(5);
is it equivalent to:
int a;
int *b;
a = 5;
b = new int(a);
?
| They are NOT equivalent. The second one allocates memory and constructs an object of the given type in that memory, then returns the address of that memory. In your example, that address is stored in b.
The first variant is called placement new and assumes that storage has already been allocated at the address pointed to by the parameter (&a in your case) and will then construct an object of the given type at that address. It will return &a. Also, to destruct an object constructed by placement new, the destructor must manually be called.
So the first variant allocates memory and constructs an object, whereas the second only constructs an object in previously allocated memory.
See here for details: https://en.cppreference.com/w/cpp/language/new
|
69,553,909 | 69,557,069 | How can I get z position of hector_quadrotor in ROS? | I am trying to get z position of hector_quadrotor in simulation. I can get X and Y axis coordinates but I couldn't get Z coordinate. I tried to get it by using GPS but the values are not correct. So I want to get Z coordinate by using barometer or another sensor.
Here the a part of pose_estimation_node.cpp (You can find full version on github source):
void PoseEstimationNode::gpsCallback(const sensor_msgs::NavSatFixConstPtr& gps, const
geometry_msgs::Vector3StampedConstPtr& gps_velocity) {
boost::shared_ptr<GPS> m = boost::static_pointer_cast<GPS>(pose_estimation_->getMeasurement("gps"));
if (gps->status.status == sensor_msgs::NavSatStatus::STATUS_NO_FIX) {
if (m->getStatusFlags() > 0) m->reset(pose_estimation_->state());
return;
}
GPS::Update update;
update.latitude = gps->latitude * M_PI/180.0;
update.longitude = gps->longitude * M_PI/180.0;
update.velocity_north = gps_velocity->vector.x;
update.velocity_east = -gps_velocity->vector.y;
m->add(update);
if (gps_pose_publisher_ || sensor_pose_publisher_) {
geometry_msgs::PoseStamped gps_pose;
pose_estimation_->getHeader(gps_pose.header);
gps_pose.header.stamp = gps->header.stamp;
GPSModel::MeasurementVector y = m->getVector(update, pose_estimation_->state());
if (gps_pose_publisher_) {
gps_pose.pose.position.x = y(0);
gps_pose.pose.position.y = y(1);
gps_pose.pose.position.z = gps->altitude - pose_estimation_->globalReference()- >position().altitude;
double track = atan2(gps_velocity->vector.y, gps_velocity->vector.x);
gps_pose.pose.orientation.w = cos(track/2);
gps_pose.pose.orientation.z = sin(track/2);
gps_pose_publisher_.publish(gps_pose);
}
sensor_pose_.pose.position.x = y(0);
sensor_pose_.pose.position.y = y(1);
"""I add it here"""
}
}
If I add -----> sensor_pose_.pose.position.z = gps->altitude,
I can get a Z coordinate on RVIZ simulation or gnome-terminal. But as I said, the values are very meanless (negative values).
Also ------> gps_pose.pose.position.z = gps->altitude - pose_estimation_->globalReference()-
>position().altitude;
It is not working because position().altitude return NAN.
There are another measurement method in pose_estimation_node.cpp like barometer. How can I use barometer value.
Here the another part of pose_estimation_node.cpp:
#if defined(USE_HECTOR_UAV_MSGS)
void PoseEstimationNode::baroCallback(const hector_uav_msgs::AltimeterConstPtr&
altimeter) {
boost::shared_ptr<Baro> m = boost::static_pointer_cast<Baro>(pose_estimation_->getMeasurement("baro"));
m->add(Baro::Update(altimeter->pressure, altimeter->qnh));
}
#else
void PoseEstimationNode::heightCallback(const geometry_msgs::PointStampedConstPtr&
height) {
boost::shared_ptr<Height> m = boost::static_pointer_cast<Height>(pose_estimation_->getMeasurement("height"));
Height::MeasurementVector update;
update(0) = height->point.z;
m->add(Height::Update(update));
if (sensor_pose_publisher_) {
sensor_pose_.pose.position.z = height->point.z - m->getElevation();
}
}
#endif
void PoseEstimationNode::magneticCallback(const geometry_msgs::Vector3StampedConstPtr& magnetic) {
boost::shared_ptr<Magnetic> m = boost::static_pointer_cast<Magnetic>(pose_estimation_->getMeasurement("magnetic"));
Magnetic::MeasurementVector update;
update.x() = magnetic->vector.x;
update.y() = magnetic->vector.y;
update.z() = magnetic->vector.z;
m->add(Magnetic::Update(update));
if (sensor_pose_publisher_) {
sensor_pose_yaw_ = -(m->getModel()->getTrueHeading(pose_estimation_->state(), update) - pose_estimation_->globalReference()->heading());
}
}
| To use a barometer you need to actually add that sensor to your robot. What you're looking at is only the callback meaning such messages are supported. If you want to add a new sensor to your robot I'd suggest looking at this tutorial.
All that being said, if you're getting incorrect altitude values you need to go back and recheck your transforms because the localization built into hector should work fine.
|
69,554,555 | 69,554,697 | Storing value in 2d array variable during runtime in c++ | My main code is .ino file for STM32F103C8T6 with STM32 official core. I have also included my library files of .h file and .cpp file.
I want store a values in 2d array called uint32_t Page[15][14]; in .h file of my library
How to store a value in 2d array variable during runtime. I have posted my code below. For me the code below is perfect, but still did not print the value stored in the array by calling the function HatriX_Signal with correct parameters. Kindly let me know what is wrong in my code below.
// .ino file
#include "HATRIX.h"
HATRIX Hatrix;
void setup()
{
Hatrix.HATRIX_INIT(115200);
}
void loop()
{
Hatrix.HatriX_Signal(Temperature_Signal, 0x66, Page[2][0]);
Serial.println(Page[2][0]);
Serial.println((float)Page[2][0] / 100);
}
// .h file
#ifndef HATRIX_H
#define HATRIX_H
#include "Arduino.h"
#include "Thermo_Couple_Input.h"
#define Number_of_Pages 15
#define Number_of_Bytes_Per_Page 64
static Thermo_Couple_Input TC_IN;
static uint32_t Page[Number_of_Pages][(Number_of_Bytes_Per_Page / 4) - 2];
enum Signal { Temperature_Signal,
Pressure_Signal,
Co2_Signal,
Analog_Industrial_Input_Signal,
General_Purpose_Output_Signal,
PWM_Power_Signal,
PWM_Voltage_Signal
};
class HATRIX
{
public:
void HATRIX_INIT(uint32_t bauderate);
void HatriX_Signal(uint8_t Signal, uint8_t I2C_Address, uint32_t Page);
};
#endif
// .cpp file
#include "HATRIX.h"
void HATRIX::HATRIX_INIT(uint32_t bauderate)
{
Serial.begin(bauderate);
}
// \brief Note: The value we get from Thermocouple is float value. So, we multiply the value with 100 and store it in specified static uint32_t Page by user.
// \param enum_Signal choose accordingly from enum signal: { Temperature_Signal ,
// Pressure_Signal ,
// Hatrix.Co2_Signal ,
// Analog_Industrial_Input_Signal ,
// General_Purpose_Output_Signal ,
// PWM_Power_Signal ,
// PWM_Voltage_Signal };
// \param I2C_Address Address of I2C to get the temperature from desired Thermocouple.
// \param Page Give the Page details to store your value. example: Hatrix.Page[4][3]
void HATRIX::HatriX_Signal(uint8_t signal, uint8_t I2C_Address, uint32_t Page)
{
if(signal == Temperature_Signal);
{
TC_IN.Thermo_Couple_Input_Channel(I2C_Address);
Serial.println("Page");
Page = fThermocoupleTemperature * 100;
Serial.println(Page);
}
}
| When calling HATRIX::HatriX_Signal(...), you pass a copy of a uint32_t of the multidimensional array Hatrix.Page to the function.
Inside the HATRIX::HatriX_Signal(...) function, you assign a new value to this variable called Page. But since it's just a copy of the value from the array, the array itself won't be effected by this.
In order to get the value of the function you can either use a pointer to the value in the array or a reference to the value in the array, preferably, return the value directly.
Your function could either look like this using a pointer:
void HATRIX::HatriX_Signal(uint8_t signal, uint8_t I2C_Address, uint32_t* Page)
{
if(signal == Temperature_Signal);
{
TC_IN.Thermo_Couple_Input_Channel(I2C_Address);
TC_IN.fThermocoupleTemperature = TC_IN.fThermocoupleTemperature * 100;
Serial.println("Page");
*Page = TC_IN.fThermocoupleTemperature;
Serial.println(*Page);
}
}
and called like:
Hatrix.HatriX_Signal(Hatrix.Temperature_Signal, 0x66, &Hatrix.Page[2][0]);
or look like this using a reference:
void HATRIX::HatriX_Signal(uint8_t signal, uint8_t I2C_Address, uint32_t& Page)
{
if(signal == Temperature_Signal);
{
TC_IN.Thermo_Couple_Input_Channel(I2C_Address);
TC_IN.fThermocoupleTemperature = TC_IN.fThermocoupleTemperature * 100;
Serial.println("Page");
Page = TC_IN.fThermocoupleTemperature;
Serial.println(Page);
}
}
and called like:
Hatrix.HatriX_Signal(Hatrix.Temperature_Signal, 0x66, Hatrix.Page[2][0]);
or alternatively, as I would advice, look like this:
uint32_t HATRIX::HatriX_Signal(uint8_t signal, uint8_t I2C_Address)
{
if(signal == Temperature_Signal);
{
TC_IN.Thermo_Couple_Input_Channel(I2C_Address);
TC_IN.fThermocoupleTemperature = TC_IN.fThermocoupleTemperature * 100;
Serial.println("Page");
uint32_t page = TC_IN.fThermocoupleTemperature;
Serial.println(page);
return page;
}
}
and called like:
Hatrix.Page[2][0] = Hatrix.HatriX_Signal(Hatrix.Temperature_Signal, 0x66);
|
69,554,728 | 69,561,620 | Can multiple readers synchronize with the same writers with acquire/release ordering? | After reading "Concurrency in action" I could not find an answer to one question - are there guarantees in the standard for reading side effects when we have one store(release) and many loads(acquire) on one atomic variable?
Suppose we have:
int i{};
atomic<bool> b{};
void writer(){
i=42;
b.store(true,memory_order_release);
}
void reader(){
while(!b.load(memory_order_acquire))
this_thread::yield();
assert(i==42);
}
//---------------------
thread t1{writer},t2{reader},t3{reader};
If we had only one reader, all ok, but can we have failed assertion in t2 or t3 thread?
| This is a text-book example of a happens-before relationship between the store to i in writer and the load from i in both reader threads.
That multiple readers are involved does not matter. The store to b synchronizes with all readers that observe the updated value (which will eventually happen thanks to the loop).
I think the quote you're looking for is:
An atomic operation A that performs a release operation on an atomic object M synchronizes with an atomic
operation B that performs an acquire operation on M and takes its value from any side effect in the release
sequence headed by A.
It does not say that this is limited to a single load operation
|
69,555,386 | 69,559,276 | boost odeint gives very different values from Python3 scipy | I am trying to integrate a very simple ODE using boost odeint.
For some cases, the values are the same (or very similar) to Python's scipy odeint function.
But for other initial conditions, the values are vastly different.
The function is: d(uhat) / dt = - alpha^2 * kappa^2 * uhat
where alpha is 1.0, and kappa is a constant depending on the case (see values below).
I have tried several different ODE solvers from boost, and none seem to work.
Update: The code below is now working.
In the code below, the first case gives nearly identical results, the 2nd case is kind of trivial (but reassuring), and the 3rd case gives erroneous answers in the C++ version.
Here is the C++ version:
#include <boost/numeric/odeint.hpp>
#include <cstdlib>
#include <iostream>
typedef boost::numeric::odeint::runge_kutta_dopri5<double> Stepper_Type;
struct ResultsObserver
{
std::ostream& m_out;
ResultsObserver( std::ostream &out ) : m_out( out ) { }
void operator()(const State_Type& x , double t ) const
{
m_out << t << " : " << x << std::endl;
}
};
// The rhs: d_uhat_dt = - alpha^2 * kappa^2 * uhat
class Eq {
public:
Eq(double alpha, double kappa)
: m_constant(-1.0 * alpha * alpha * kappa * kappa) {}
void operator()(double uhat, double& d_uhat_dt, const double t) const
{
d_uhat_dt = m_constant * uhat;
}
private:
double m_constant;
};
void integrate(double kappa, double initValue)
{
const unsigned numTimeIncrements = 100;
const double dt = 0.1;
const double alpha = 1.0;
double uhat = initValue; //Init condition
std::vector<double> uhats; //Results vector
Eq rhs(alpha, kappa); //The RHS of the ODE
//This is what I was doing that did not work
//
//boost::numeric::odeint::runge_kutta_dopri5<double> stepper;
//for(unsigned step = 0; step < numTimeIncrements; ++step) {
// uhats.push_back(uhat);
// stepper.do_step(rhs, uhat, step*dt, dt);
//}
//This works
integrate_const(
boost::numeric::odeint::make_dense_output<Stepper_Type>( 1E-12, 1E-6 ),
rhs, uhat, startTime, endTime, dt, ResultsObserver(std::cout)
);
std::cout << "kappa = " << kappa << ", initial value = " << initValue << std::endl;
for(auto val : uhats)
std::cout << val << std::endl;
std::cout << "---" << std::endl << std::endl;
}
int main() {
const double kappa1 = 0.062831853071796;
const double initValue1 = -187.097241230045967;
integrate(kappa1, initValue1);
const double kappa2 = 28.274333882308138;
const double initValue2 = 0.000000000000;
integrate(kappa2, initValue2);
const double kappa3 = 28.337165735379934;
const double initValue3 = -0.091204068895190;
integrate(kappa3, initValue3);
return EXIT_SUCCESS;
}
and the corresponding Python3 version:
enter code here
#!/usr/bin/env python3
import numpy as np
from scipy.integrate import odeint
def Eq(uhat, t, kappa, a):
d_uhat = -a**2 * kappa**2 * uhat
return d_uhat
def integrate(kappa, initValue):
dt = 0.1
t = np.arange(0,10,dt)
a = 1.0
print("kappa = " + str(kappa))
print("initValue = " + str(initValue))
uhats = odeint(Eq, initValue, t, args=(kappa,a))
print(uhats)
print("---")
print()
kappa1 = 0.062831853071796
initValue1 = -187.097241230045967
integrate(kappa1, initValue1)
kappa2 = 28.274333882308138
initValue2 = 0.000000000000
integrate(kappa2, initValue2)
kappa3 = 28.337165735379934
initValue3 = -0.091204068895190
integrate(kappa3, initValue3)
| With boost::odeint you should use the integrate... interface functions.
What happens in your code using do_step is that you use the dopri5 method as a fixed-step method with your provided step size. In connection with the large coefficient L=kappa^2 of about 800, the product L*dt=80 is far outside the stability region of the method, the boundary is between values of 2 to 3.5. Divergence or oscillating divergence is the expected result.
What should happen and what is implemented in the scipy odeint, ode-dopri5 or solve_ivp-RK45 methods is a method with adaptive step size. Internally the optimal step size for the error tolerances is chosen, and in each internal step an interpolation polynomial is determined. The output or observed values are computed with this interpolator, also called "dense output" if the interpolation function is returned from the integrator. One result of the error control is that the step size is always inside the stability region, for stiff problems with medium error tolerances on or close to the boundary of this region.
|
69,555,532 | 69,629,288 | CMake specifying Native Build System Options in CMakeLists.txt(managed C++ Project) | i got stuck with a problem which has to do with a managed c++ Project.
Currently we have a working Build and we are about to use CMake to generate our Solution Files in the future.
In our solution we have some Managed C++ Project and C# Projects. I tried to generate/build the Managed C++ Projects and it works. But there is one key thing that is different which atually breaks the build.
In our working build the managed C++ Project has the Xml Tag <TargetFrameworkVersion> but when I use CMake to configure/generate the Project I end up having <TargetFramework> and this breaks the build ( I confirmed by manually changing the Tag).
I got stuck with this Problem for 2 days and the following things I already tried:
I tried setting VS_DOTNET_TARGET_FRAMEWORK_VERSION which actually is deprecated but makes sense because of the name. I ended up having in the Project file.
I also tried the newer Variables DOTNET_TARGET_FRAMEWORK, DOTNET_TARGET_FRAMEWORK_VERSION but I ended up again with in the Project file.
I thought to myself I could change the Project file after I configure/generate but thats pretty hacky (but works)
There is a second solution which actually works but is not what I really want. I can tell cmake.exe to pass some options to the native MsBuild tool to build the managed C++ target. This works but I would prefer to some how tell the CMakeLists.txt to do this or even better have the right Xml tag when generating the Proect files because we don't want to use the command line when building our projects.
The approach looks like this (Target Name is NotifierLib and .NET Framework Version is 4.7.2)
cmake --build . --target NotifierLib -- /p:TargetFrameworkVersion=v4.7.2
Did anyone came across this exact issue? Or maybe has an idea how to solve this via CMakeLists.txt?
Thanks in advance.
| I finally came to a pretty Solution which was there initially.
This post helped my to get on the right Track:
How can cmake add custom entry in a project's vcxproj PropertyGroup?
Basically I don't need to iterate over the .xml File myself to edit the Tag.
I can tell CMake to set it for me as a global option with:
set_target_properties(NotifierLib PROPERTIES VS_GLOBAL_TargetFrameworkVersion "v4.7.2")
This way the initial <TargetFramework> Tag is still in the .xml File but it does not bother because it is not being used.
|
69,555,967 | 69,556,475 | This is explanation on recursion tracing and i can't understand some logic in it. Please help me with the logic |
The function written in this pic is for explaining recursion. It says that the function takes T(n) time to run but it contains a recursive call and then it takes T(n-1) time to run. But we know that function takes T(n) time and same function call is taken then it should again take T(n) time because function is doing same thing as before. Please tell me if i am wrong in understanding the concept or the concept is wrongly explained in the code.
| The image is this
void Test(int n) {
if (n > 0) {
printf("%d",n); // 1
Test(n-1); // T(n-1)
}
}
// T(n) = T(n-1) + 1
By definition T(n) is the time taken by Test(n). Also T(n-1) is just a label for "time taken to call Test(n-1)".
As the function only calls printf which is constant complexity, it is counted as 1 instruction, and calls Test(n-1), its total runtime is T(n) = T(n-1) + 1.
But we know that function takes T(n) time and same function call is taken then it should again take T(n) time because function is doing same thing as before.
No, T(n-1) is not the same as T(n) because Test(n) is not doing the same as Test(n-1). Test(n) is doing the same as Test(n-1) plus calling printf once.
|
69,556,320 | 69,556,443 | no return statement in function returning non-void while using C++ | I am trying to understand the C++(GCC compiler) expectation of return statement in a non-void function.
For example, running this piece of code is working fine:
int foo()
{
throw "blah";
}
While, on the other hand, if we try to use/call some function to complete the throw, it is facing the well known error/warning of:
no return statement in function returning non-void
for example:
void throw_blah()
{
throw "blah";
}
int foo()
{
throw_blah();
}
I am pretty curious about this as this is directly related to one of my other issue, where just like here, throw is working fine but using macro for throw is facing the same error.
| The compiler isn't going to go to very much trouble to detect this situation, because functions like throw_blah which are guaranteed to never return are rare, and because except in the simplest of situations, there's no way for it to reliably do so. If you have a function like throw_blah which is defined to never return, you can use the [[noreturn]] attribute to tell the compiler about it, and it will suppress the warning.
Note that throw_blah is the weird bit, not foo. If you called exit instead of throw_blah from foo, for instance, it wouldn't issue the error. That's because exit is marked as [[noreturn]].
|
69,556,427 | 69,556,548 | new bool** matrix vs new bool*matrix vs new bool matrix different types of cpp initialization confusion? | So,far after doing my own research i know bool** matrix will create 2d array,bool* matrix will create 1d array. Now,when implementing graphs using adjacency matrix
private:
bool** adjMatrix;
int numVertices;
public:
Graph(int numVertices) {
this->numVertices = numVertices;
adjMatrix = new bool*[numVertices];//<---here
for (int i = 0; i < numVertices; i++) {
adjMatrix[i] = new bool[numVertices];//<--here
for (int j = 0; j < numVertices; j++)
adjMatrix[i][j] = false;
}
}
Now, i commented the part where i am confused, see both lines look similar to me as per my above mentioned understanding.
| new bool*[numVertices] allocates and constructs an array of bool* (pointer to bool) of length numVertices. new bool[numVertices] allocates and constructs an array of bool of length numVertices.
What your code is doing is:
Declaring adjMatrix as a pointer to a pointer to bool
Setting adjMatrix to point to the first element of an array of bool*
Setting each element of that array to point to the first element of an array of bool
This gives the effect of adjMatrix looking like a 2D array, since you can write adjMatrix[i][j] and access one of the bool elements. However, this setup is not ideal for a few reasons.
It takes two pointer derefs to reach an array element rather than one
You have to do numVertices+1 dynamic allocations
The calls to new bool[numVertices] are not guaranteed to put all of the bools next to each other in memory
It would be better to make adjMatrix just be a bool*, and allocate all the bools at once:
adjMatrix = new bool[numVertices * numVertices];
This will save you numVertices dynamic allocations and put all the bools in a contiguous block of memory (better for cache). You could then access the array elements like
*(adjMatrix + i*numVertices + j)
instead of
adjMatrix[i][j]
|
69,556,488 | 69,558,565 | Reference implementation of vrecpeq_f32 intrinsic? | There is vrecpeq_f32 ARM NEON Intrinsic.
The official explanation for vrecpeq_f32: https://developer.arm.com/architectures/instruction-sets/intrinsics/#f:@navigationhierarchiessimdisa=[Neon]&q=vrecpeq_f32 .
Floating-point Reciprocal Estimate. This instruction finds an approximate reciprocal estimate for each vector element in the source SIMD&FP register, places the result in a vector, and writes the vector to the destination SIMD&FP register.
However, it is still not accurate for me. Just wondering if we can write a reference implementation in C/C++ that keep exactly the same result as vrecpeq_f32?
I've tried calling vrecpeq_f32 and get the result:
float32x4_t v1 = {1, 2, 3, 4};
float32x4_t v_out = vrecpeq_f32(v1);//0.99805, 0.49902, 0.33301, 0.24951
Curious why 1's reciprocal is 0.99805 instead of 1.0.
P.S. I'm not interested in how to use NEON intrinsics with some tricks to get better precision reciprocal result, e.g. one or more Newton-Raphson iterations.
| The ARM documention provides pseudocode detailing the exact algorithm being performed. Look for FPRecipEstimate which uses fixed-point RecipEstimate.
That may look like a lot of code, but a big chunk of it is there to handle various edge cases, operation modes, and element sizes.
Just wondering if we can write a reference implementation in C/C++ that keep exactly the same result as vrecpeq_f32?
Sure! This boils down to bit manipulation after all, so there's no reason it shouldn't be feasible. Converting it to C++ while removing most edge-case handling as well as extended precision mode looks like this: (see on godbolt)
Disclaimer: This is not a complete implementation of the function, just enough to explore the precision behavior, assuming finite normalized inputs, no special cases. Don't drop this in a codebase expecting it to match the instruction in general.
#include <iostream>
#include <cstring>
#include <iomanip>
// Convenience struct to deal with encoding and decoding ieee754 floats
struct float_parts {
explicit float_parts(float v);
explicit operator float() const;
std::uint32_t sign;
std::uint32_t fraction;
std::uint32_t exp;
};
// Adapted from:
// https://developer.arm.com/documentation/ddi0596/2021-03/Shared-Pseudocode/Shared-Functions?lang=en#impl-shared.FPRecipEstimate.2
// RecipEstimate()
// ===============
// Compute estimate of reciprocal of 9-bit fixed-point number.
//
// a is in range 256 .. 511 representing a number in
// the range 0.5 <= x < 1.0.
// result is in the range 256 .. 511 representing a
// number in the range 1.0 to 511/256
std::uint32_t RecipEstimate(std::uint32_t a) {
a = a*2+1;
std::uint32_t b = (1 << 19) / a;
return ( b + 1) / 2;
}
// FPRecipEstimate()
// =================
float FPRecipEstimate(float operand) {
// ([...],sign,[...]) = FPUnpack(operand, [...], [...]);
// fraction = operand<22:0> : Zeros(29);
// exp = UInt(operand<30:23>);
float_parts parts{operand};
// scaled = UInt('1':fraction<51:44>);
std::uint32_t scaled = 0x100 | ((parts.fraction >> 15) & 0xFF) ;
// when 32 result_exp = 253 - exp; // In range 253-254 = -1 to 253+1 = 254
parts.exp = 253 - parts.exp;
// // Scaled is in range 256 .. 511 representing a
// // fixed-point number in range [0.5 .. 1.0].
// estimate = RecipEstimate(scaled, increasedprecision);
std::uint32_t estimate = RecipEstimate(scaled);
// fraction = estimate<11:0> : Zeros(40);
parts.fraction = (estimate & 0xff ) << 15;
return float(parts);
}
int main() {
std::cout << std::setprecision(5)
<< FPRecipEstimate(1.0f) << "\n"
<< FPRecipEstimate(2.0f) << "\n"
<< FPRecipEstimate(3.0f) << "\n"
<< FPRecipEstimate(4.0f);
}
float_parts::float_parts(float v) {
std::uint32_t v_bits;
std::memcpy(&v_bits, &v, sizeof(float));
sign = (v_bits >> 31) & 0x1;
fraction = v_bits & ((1 << 23) - 1);
exp = (v_bits >> 23) & 0xff;
}
float_parts::operator float() const {
std::uint32_t v_bits =
((sign & 0x1) << 31) |
(fraction & ((1 << 23) - 1)) |
((exp & 0xff) << 23);
float result;
std::memcpy(&result, &v_bits, sizeof(float));
return result;
}
Which produces the expected values:
0.99805
0.49902
0.33301
0.24951
|
69,556,967 | 69,559,711 | converting data to struct hostent from getaddrinfo() | I am replacing old code to linux. I was using:
server_host = getipnodebyname(host.c_str(), AF_INET, 0, &err_num);
and
server_host = getipnodebyaddr(addr, sizeof(INET_ADDRSTRLEN), AF_INET, &err_num);
that it has to be replaced by the new getaddrinfo().
At moment I added:
struct addrinfo *p_addr = (struct addrinfo *) NULL;
struct addrinfo hints={0}; //Initialize the addrinfo hints
char addr[INET_ADDRSTRLEN]={0};
int result = 0;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET; //Request for IPV4 ADDRESSES ONLY
result = getaddrinfo(host.c_str(), NULL, &hints, &p_addr);
but I need to populate the gathered information in the hostent structure:
hostent *server_host;
for compatibility with other code.
I could use the gethostbyname() to get directly the hostent structure but I want avoid it.
What do you suggest?
| There is no C library function to convert an addrinfo into a hostent. You will have to construct the hostent yourself using the data from the addrinfo, eg:
#include <vector>
addrinfo hints = {0};
hints.ai_family = AF_INET;
hints.ai_flags = AI_CANONNAME;
addrinfo *p_addrs = NULL;
int result = getaddrinfo(host.c_str(), NULL, &hints, &p_addrs);
if (result != 0) ... // error handling...
std::vector<in_addr*> in_addrs;
for(addrinfo *p_addr = p_addrs; p_addr != NULL; p_addr = p_addr->ai_next) {
in_addrs.push_back(&reinterpret_cast<sockaddr_in*>(p_addr->ai_addr)->sin_addr);
}
in_addrs.push_back(NULL);
hostent hst;
h.h_name = p_addrs->ai_canonname;
h.h_aliases = NULL;
h.h_addrtype = AF_INET;
h.h_length = sizeof(in_addr);
h.h_addr_list = reinterpret_cast<char**>(&in_addrs[0]/* or: in_addrs.data() */);
// use hst as needed ...
freeaddrinfo(p_addrs);
|
69,557,155 | 69,557,393 | x86 Memory Alignment of struct vs. cache line? | Rcently I'm working on a "searching system" and something about memory/cache performance confuse me.
assume my machine info : x86 arch(L1-3 cache, 64 bytes cache line), linux OS
CPU reads 64 bytes(cache line) each time, so does CPU read data from memory address(to cache) always 64 multiple? For example 0x00(to 0x3F), 0x40(to 0x7f). If I need data(int32_t) located in 0x20 then system still need to load 0x00--0x3F.
how about this case:
struct Obj{int64_t a[5];char b[2];}; then define
int64_t c[5]; Obj obj; int64_t d;
Will virtual memory (or also physical?) be organized like this?
| I think the part you might be missing is the alignment requirement that the compiler imposes for various types.
Integer types are generally aligned to a multiple of their own size (e.g. a 64-bit integer will be aligned to 8 bytes); so-called "natural alignment". This is not a strict architectural requirement of x86; unaligned loads and stores still work, but since they are less efficient, the compiler prefers to avoid them.
An aggregate, like a struct, is aligned according to the highest alignment requirement of its members, and padding will be inserted between members if needed to ensure that each one is properly aligned. Padding will also be added at the end so that the overall size of the struct is a multiple of its required alignment.
So in your example, struct Obj has alignment 8, and its size will be rounded up to 48 (with 6 bytes of padding at the end). So there is no need for 24 bytes of padding to be inserted after c[4] (I think you meant to write the padding at addresses 40-63); your obj can be placed at address 40. d can then be placed at address 88.
Note that none of this has anything to do with the cache line size. Objects are not by default aligned to cache lines, though "natural alignment" will ensure that no integer load or store ever has to cross a cache line.
|
69,557,872 | 69,558,014 | std::span as a base class for std::vector | I'm currently developing a custom C++ container library that is similar to std::vector, but I also want to have features of std::span baked in. In particular, I want to be able to write functions that take in a std::span-like parameter, and also work with a std::vector-like argument.
What I can do is to construct a class, say my_vector, and another class my_span that can be converted from the class my_vector. This is what the STL does, and I know it's usually a good idea to imitate the standard library. But I had this idea that my_span is basically a my_vector that does not own memory, and so it is possible to implement the two classes using inheritance. Here is what it looks like in code.
class my_vector;
class my_span {
private:
/* span sees [data_ + start_, data_ + stop_) */
T* data_;
size_t start_;
size_t stop_;
friend class my_vector;
public:
/* Member functions operating on non-owning memory */
};
class my_vector : public my_span {
private:
size_t cap_;
public:
/* Member functions like resize, push_back, etc. */
};
Now my colleague is rejecting this idea based on the following reasons. To be fair, my representation of his objections might not be faithful.
It is counter-intuitive that a span is defined before the actual container.
Inheritance is used when the derived class is extended, but the class my_vector has the condition that its member start_ will always be 0. (There are reasons that force the pointer data_ to always point at the start of the allocated memory. This is why I can't just use a pointer and the length of the span.)
On the other hand, I believe this design has the following benefits.
If you think about it, my_vector still "is a" my_span. It's just a my_span that owns memory and can change size.
Every member function that operates on non-owning memory can be declared and implemented only once; the class my_vector automatically inherits it.
To use my_vector as a my_span, you don't need to create a new my_span instance. Up-casting is much more natural than a constructor.
I haven't seen a design that follows this pattern, so I wanted to get more opinions on whether this is a good design.
| The LSP states that a reference or pointer to a derived class should obey all of the invariants of a reference to a base class.
This has to be every operation. This is harder than you think.
Replacing a span's referenced buffer is a perfectly cromulant span operation. Doing so to the span parent component of a derived vector is toxic! In effect, you end up having to restrict what you can do to a span in order to make this work, resulting in either a crippled span type, or an unsafe combination.
A better option here is probably to just have an implicit conversion from a vector to a span (but not the other way around, that should be explicit as it is expensive).
On top of that, containers-of-data often consider the data to be part of them, while views-of-data don't. So getting begin/end iterators that mutate the contents of a span is const, while doing the same for a vector is not!
template<class T>
struct span {
T* data = nullptr;
std::size_t length = 0;
T* begin() const { return data; }
T* end() const { return data+length; }
};
template<class T>
struct vector {
T* data = nullptr;
std::size_t length = 0;
std::size_t capacity = 0;
T const* begin() const { return data; }
T const* end() const { return data+length; }
T * begin() { return data; }
T * end() { return data+length; }
};
another subtle difference.
The rule I follow for span-likes (as in, array views) is that they are in charge of converting-from. They will convert from
Raw C arrays.
Initializer lists. (warning: somewhat dangerous)
Any object with a .data() returning a pointer (to a compatible type), and a .size() returning an integral value. Note we are doing pointer arithmetic, so compatible is "identical up to const volatile".
And they deduce their type from all of the above (using the template class deduction feature).
Rule #3 catches std vector and std array and std string "for free".
Rule #2 permits
void foo( span<const flag> );
foo( {flag::a, flag::b} );
the danger of initializer list is:
span<int> sp = {1,2,3};
has a dangling reference in it.
|
69,558,232 | 69,578,851 | Using Assert() in a C++ test project for "test project" bugs? | Is it appropriate to use the Assert() function in a Visual Studio C++ test project for bugs WITHIN the test project? The Visual Studio test projects for C++ use
namespace Microsoft::VisualStudio::CppUnitTestFramework
For instance, I have a function that builds a vector full of random char value strings, how should I handle the case in which the user of the class uses it with the wrong arguments? Would it be appropriate to add a Assert::IsTrue(myVec.size() > 0) and then have the possibility of the test project it's self cause a test to fail?
An example:
/// <summary>
/// Returns a vector of std::string with randomized content.
/// count is the number of entries in the returned vector, length is the max length of the strings.
/// </summary>
/// <returns> a vector of std::string with randomized content. Empty vector on error. </returns>
std::vector<std::string> BuildRandomStringVector(const int count, const int length, const int minLength = 3)
{
//arg error checking, returns empty vector as per description
if (minLength >= length || (length <= 0) || (count <=0) || (minLength <=0))
{
return std::vector<std::string>();
}
//Test all kinds of random character possibilities.
std::uniform_int_distribution<int> distCharPossibility
(std::numeric_limits<char>::min(),
std::numeric_limits<char>::max());
std::uniform_int_distribution<int> distLengthPossibility(minLength, length);
std::random_device rd;
std::mt19937 stringGenerator(rd());
std::vector<std::string> ret;
//the distribution uses the generator engine to get the value
for (int i = 0; i < count; i++)
{
const int tLength = distLengthPossibility(stringGenerator);
std::string currentBuiltString = "";
for (int j = 0; j < tLength; j++)
{
char currentBuiltChar = distCharPossibility(stringGenerator);
currentBuiltString += currentBuiltChar;
}
ret.push_back(currentBuiltString);
}
return ret;
}
| I would not reccommend using any form of assertions in tests. The rationale is as follows. Assertion is a diagnostic code that is normally executed in "Debug" mode and skipped in "Release". You don't intend to run tests in two different modes, do you? And you are not going to test tests. Verification of the condition in your code should not have any measurable impact on the test execution time. In such a case prefer reliability: always perform the test sanity, for you can certainly afford a few microseconds longer tests. If violation of the condition should be considered an error, don't return an empty vector: will you be checking its size at the caller each time? Throw an exception. In short, rather then an assertion, use std::invalid_argument or something similar. Fire and forget.
From another viewpoint: in principle we could embed a lot of self-testing in production code, but we prefer external tests so that the production code is really slim and fast. This concern is not that important for tests: if you're afraid they can be used improperly, test the correctness of their usage explicitly and unconditionally. Use the common sense to tell when the overhead is still acceptable.
|
69,558,269 | 69,558,419 | How would C++ hardware destructive & constructive interference size work with the mandated declaration order? | For reference, the interference size is part of C++17, P0154R1, and mandated declaration order is proposed for C++23, P1847R4.
As far as I understand...
The first proposal requires the compiler to move alignas-ed member variables closer together / farther away.
The second proposal would require the compiler to lay out member variables in order of declaration in the class.
Seems to me the 2nd proposal takes the punch out of the first. hardware_destructive_interference_size would necessarily require leaving unused memory between the two member variables, with no option to fill it with other members. hardware_constructive_interference_size would be reduced to a warning saying "can't do it, try reordering the member variables yourself".
| P0154 makes no changes to how member variables are laid out. It merely exposes some constexpr variables, which you can use to adjust the alignment of member variables through alignas. But alignas doesn't gain any special properties.
That is, these two structs have the same layout, if hardware_destructive_interference_size is 64:
struct one
{
alignas(hardware_destructive_interference_size) int member1;
alignas(hardware_destructive_interference_size) int member2;
};
struct two
{
alignas(64) int member1;
alignas(64) int member2;
};
P1847 doesn't actually change any behavior. It removes a degree of freedom that was previously available to compilers when laying out the order of members in a class. This removal doesn't change any compiler's behavior because... no compilers took advantage of this degree of freedom. That's why the committee is removing it; nobody did anything with it.
Also, said degree of freedom is the ability to layout members with different access classes (public/private). The layout of members within an access class has been declaration order since (at least) C++11.
So these two changes have nothing to do with one another.
|
69,558,438 | 69,558,801 | setw and accentuated characters | I want to display a "pretty" list of countries and their ISO currency codes on C++.
The issue is that my data is in French and it has accentuated characters. That means that Algeria, actually is written "Algérie" and Sweden becomes "Suède".
map<string, string> currencies; /* ISO code for currency and country name: CAD/Canada */
for (auto &cursor: countries)
cout << setw(15) << left << cursor.second << right << " - " cursor.first << endl;
If the map contains Algeria, Canada and Sweden the result comes out something like this:
Canada - CAD
Algérie - DZD
Suède - SEK
Do you see how Algeria and Sweden are not "pretty"? That's because even though "Algérie" has 7 visible characters and "Suède" has 5, they "count" as one more for setw. The "é" in "Algérie" and the "è" in "Suède" "count" as two characters, because they are "special accentuated characters.
Is there an elegant and simple way to make sure that DZD and SEK get automatically aligned with CAD?
|
Convert to using std::wstring instead of std::string
Convert to using wide string constants (L"stuff" vs "stuff")
Convert to using std::wcout instead of std::cout
Use setlocale to set a UTF-8 locale
Use wcout.imbue to configure wcout for a UTF-8 locale
Example:
#include <map>
#include <string>
#include <iostream>
#include <iomanip>
#include <locale>
int main() {
setlocale(LC_ALL, "en_US.utf8");
std::locale loc("en_US.UTF-8");
std::wcout.imbue(loc);
std::map<std::wstring, std::wstring> dict
{ {L"Canada",L"CAD"}, {L"Algérie",L"DZD"}, {L"Suède",L"SEK"} };
for (const auto& [key, value]: dict) {
std::wcout << std::setw(10) << key << L" = " << value << std::endl;
}
}
|
69,558,521 | 69,558,592 | Friend Function name undefined | I tried to pass a friend function name comp to set_intersection, compiled in Visual Studio 2019 with a compilation error: E0020 identifier "comp" is undefined
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Test {
friend bool comp(const Test& A, const Test& B) { return A.a < B.a; }
public:
int a{ 10 };
};
int main() {
vector<Test> v1{ Test{} };
vector<Test> v2{ Test{} };
vector<Test> rs;
set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), back_inserter(rs), comp);
}
However, if I changed comp to operator<, it works fine with set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), back_inserter(rs));. Why comp doesn't work?
| comp is not visible for lookup here. For friend declaration,
A name first declared in a friend declaration within a class or class template X becomes a member of the innermost enclosing namespace of X, but is not visible for lookup (except argument-dependent lookup that considers X) unless a matching declaration at the namespace scope is provided
(Note that ADL only works for function-call expressions, i.e. comp(...);.)
You need to provide a declaration at the global namespace.
bool comp(const Test& A, const Test& B);
class Test {
friend bool comp(const Test& A, const Test& B) { return A.a < B.a; }
public:
int a{ 10 };
};
int main() {
vector<Test> v1{ Test{} };
vector<Test> v2{ Test{} };
vector<Test> rs;
set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), back_inserter(rs), comp);
}
|
69,558,602 | 69,558,690 | reference to function is ambiguous in c++ | Below is my c++ code. When I am compiling the below code in c++17, I am getting an error like this "reference to ‘greater’ is ambiguous. Can someone help me on this
#include <iostream>
using namespace std;
void greater(int num1, int num2, int num3);
int main()
{
int a, b, c;
cout<<"Enter three numbers"<<endl;
cin>>a>>b>>c;
greater(a,b,c);
return 0;
}
void greater(int num1, int num2, int num3){
if(num1 > num2 && num1 > num3){
cout<<num1<<" is the greatest number of them all";
}
else if(num2 > num1 && num2 > num3){
cout<<num3<<" is the greatest number of them all";
}
else if(num3 > num2 && num3 > num1){
cout<<num3<<" is the greatest number of them all";
}
else if(num1 == num2 && num1 == num3){
cout<<"All the numbers are equal";
}
else{
cout<<"There's an error, Check the inputs"<<endl;
}
}
| I would only add using namespace std; if your code is small or for one-off cases. Generally not good practice since in this case, the C++ standard library includes std::greater(). Thus when you are declaring your own version and add using namespace std;, the compiler doesn't know which to use.
Here's a simple way to fix this (you should move main() down or forward declare greater):
#include <iostream>
// using namespace std; -- Don't use this
void greater(int num1, int num2, int num3);
int main()
{
int a, b, c;
std::cout<<"Enter three numbers"<<std::endl;
std::cin>>a>>b>>c;
greater(a,b,c);
return 0;
}
void greater(int num1, int num2, int num3)
{
if(num1 > num2 && num1 > num3){
std::cout<<num1<<" is the greatest number of them all";
}
else if(num2 > num1 && num2 > num3){
std::cout<<num3<<" is the greatest number of them all";
}
else if(num3 > num2 && num3 > num1){
std::cout<<num3<<" is the greatest number of them all";
}
else if(num1 == num2 && num1 == num3){
std::cout<<"All the numbers are equal";
}
else{
std::cout<<"There's an error, Check the inputs"<<std::endl;
}
}
|
69,559,589 | 69,559,746 | Zeroing-Out multiple arrays with a single memset/assuming memory layout allowed? | Looking at the source-code of the Arduino-Ethernet-Library I found this:
class DhcpClass {
private:
...
#ifdef __arm__
uint8_t _dhcpLocalIp[4] __attribute__((aligned(4)));
uint8_t _dhcpSubnetMask[4] __attribute__((aligned(4)));
uint8_t _dhcpGatewayIp[4] __attribute__((aligned(4)));
uint8_t _dhcpDhcpServerIp[4] __attribute__((aligned(4)));
uint8_t _dhcpDnsServerIp[4] __attribute__((aligned(4)));
#else
uint8_t _dhcpLocalIp[4];
uint8_t _dhcpSubnetMask[4];
uint8_t _dhcpGatewayIp[4];
uint8_t _dhcpDhcpServerIp[4];
uint8_t _dhcpDnsServerIp[4];
#endif
...
aswell as this:
void DhcpClass::reset_DHCP_lease()
{
// zero out _dhcpSubnetMask, _dhcpGatewayIp, _dhcpLocalIp, _dhcpDhcpServerIp, _dhcpDnsServerIp
memset(_dhcpLocalIp, 0, 20);
}
Is this really a legal way of accessing/zeroing those arrays, which are fields of a class? Can we really safely assume that they are always in this order and always at a continuous memory location? I believe no but I don't understand why someone wouldn't just write one memset() for each array, is the performance really that much better?
| The performance improvement is not significant, although in an arduino environment,
you may be fighting to reduce every byte of generated code (more than execution speed).
As listed, the code is a bad idea, although it will "probably" work OK, that's usually not good enough.
For this case, you could do something like this:
class DhcpClass {
private:
struct {
#ifdef __arm__
uint8_t LocalIp[4] __attribute__((aligned(4)));
uint8_t SubnetMask[4] __attribute__((aligned(4)));
uint8_t GatewayIp[4] __attribute__((aligned(4)));
uint8_t DhcpServerIp[4] __attribute__((aligned(4)));
uint8_t DnsServerIp[4] __attribute__((aligned(4)));
#else
uint8_t LocalIp[4];
uint8_t SubnetMask[4];
uint8_t GatewayIp[4];
uint8_t DhcpServerIp[4];
uint8_t DnsServerIp[4];
#endif
} _dhcp;
void reset_DHCP_lease()
{
memset(&_dhcp, 0, sizeof(_dhcp));
}
};
although you'll have to change the rest of the code to match.
Edited to add:
If the class contains no virtual methods and no other data, you could also do this:
memset(this, 0, sizeof(*this));
|
69,559,867 | 69,657,950 | GCC > 7 on Ubuntu 18.04, expected to work? | I want to understand what's happening under the hood when using a newer GCC than the "default" version for a given version of Ubuntu.
Starting with a plain Ubuntu 18.04, I have:
/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.25
Then I install gcc-11 (via the toolchains/test ppa repo) and I get:
/usr/lib/gcc/x86_64-linux-gnu/11/libstdc++.so
I also notice that the system-provided version gets overriden!
/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.29
I can compile a hello-world application with g++-11, and get the following via ldd:
ldd a.out
linux-vdso.so.1 (0x00007ffc79ff7000)
libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007fd378546000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fd378155000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fd377db7000)
/lib64/ld-linux-x86-64.so.2 (0x00007fd378b55000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fd377b9f000)
So it's linking to the system-installed version of libstdc++, instead of the compiler-provided version. The binary runs just fine.
My questions are:
Is this expected to work or I'm just lucky with my tiny example? What can possibly go wrong?
Why is the system-provided library overriden? With what?
If there's a build of GCC-11 for Ubuntu 18.04, does it mean it's guaranteed to work in Ubuntu 18.04?
In what way do the two libstdc++ libraries (system-provided and gcc-11-provided) differ?
What about other libraries, like libgcc_s.so? The same happens, there's the "system" provided one, and the "GCC-provided" one.
Do I need to worry about the remaining libs that are present in ldd? (libc, libm, linux-vsdo). It seems there's only one version in the system, but I wonder if they get overriden when installing GCC.
Thanks!
| After all the great info I got from the comments, I think I got a good enough understanding to answer the question. Thanks everyone!
If the libstdc++ has the same major version (the one in the SONAME), then they are backwards-compatible. Meaning that something built on a older libstdc++ is guaranteed to run on a newer libstdc++.
The opposite is not true in general - the library is not forward-compatible. If a new symbol is introduced in a new library, it naturally doesn't exist in the older library. This can be reproduced as follows:
Start on Ubuntu 20.04.
Copy the example code from here.
Compile it with the default GCC 9 and -std=c++17.
This binary runs fine on Ubuntu 20.04.
Now, copy that binary over to a stock Ubuntu 18.04.
You'll get a "symbol not found error":
./a.out: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.26' not found (required by ./a.out)
When you install a new GCC on Ubuntu, it will override the system-wide libstdc++ (possibly other libs?) with the GCC-provided libstdc++ (so they are identical). This will ensure that whatever you build on that machine will also run there.
|
69,560,080 | 69,560,495 | C++ MATLAB Engine won't output to console | I am following the matlab example for using matlab in c++ from:
https://uk.mathworks.com/help/matlab/matlab_external/build-c-engine-programs.html
https://uk.mathworks.com/help/matlab/matlab_external/test-your-build-environment.html
and I compile and run it without issue, except that it won't print anything.
I'm using windows and below I'll supply the code and makefile I'm using (that both work).
I can't help but feel it's an issue with my setup but I can't figure it out.
Code:
#include "MatlabDataArray.hpp"
#include "MatlabEngine.hpp"
#include <iostream>
void callSQRT() {
using namespace matlab::engine;
// Start MATLAB engine synchronously
std::unique_ptr<MATLABEngine> matlabPtr = startMATLAB();
//Create MATLAB data array factory
matlab::data::ArrayFactory factory;
// Define a four-element typed array
matlab::data::TypedArray<double> const argArray =
factory.createArray({ 1,4 }, { -2.0, 2.0, 6.0, 8.0 });
// Call MATLAB sqrt function on the data array
matlab::data::Array const results = matlabPtr->feval(u"sqrt", argArray);
// Display results
for (int i = 0; i < results.getNumberOfElements(); i++) {
double a = argArray[i];
std::complex<double> v = results[i];
double realPart = v.real();
double imgPart = v.imag();
std::cout << "Square root of " << a << " is " <<
realPart << " + " << imgPart << "i" << std::endl;
}
}
int main() {
std::cout << "Starting test\n";
callSQRT();
return 0;
}
Make:
test: testFeval.cpp
mex -setup -client engine C++
mex -client engine testFeval.cpp
| The issue was finding the dlls, adding the path to the matlab bin to my path fixed this issue
|
69,560,280 | 69,560,326 | how to check if unique_ptr points to this | In following peace of code, I'm trying to find another object that has the same coordinates as this. How to do it correctly?
auto& organism_vector = world->get_vector();
auto attacked_organism = find_if(begin(organism_vector), end(organism_vector), [this](const unique_ptr<Organism>& attacked_organism)
{
return this->get_coordinates() == attacked_organism->get_coordinates() && *this != *attacked_organism;
});
Another thing, when I finally manage to get this iterator, how to refer to attacked_organism class methods?
*attacked_organism.get_coordinates();
| Change *this != *attacked_organism to this != attacked_organism.get():
auto& organism_vector = world->get_vector();
auto attacked_organism = find_if(begin(organism_vector), end(organism_vector),
[this](const unique_ptr<Organism>& attacked_organism)
{
return this->get_coordinates() == attacked_organism->get_coordinates() && this != attacked_organism.get();
}
);
Once you have the iterator that find_if() returns (and after you validate that it is not the end iterator), you can call methods on the Organism by first dereferencing the iterator to access the unique_ptr that is holding the Organism* pointer, and then dereferencing the unique_ptr to access the Organism itself:
auto attacked_organism = find_if(...);
if (attacked_organism != end(organism_vector))
{
(**attacked_organism).get_coordinates();
or:
(*attacked_organism)->get_coordinates();
...
}
On a side note: I would not recommend giving your iterator variable the same name as the lambda parameter. That just makes things confusing to read. The lambda is trying to find an Organism to attack, but it hasn't actually been attacked yet, so you should name the lambda parameter more appropriately, eg:
auto attacked_organism = find_if(begin(organism_vector), end(organism_vector),
[this](const unique_ptr<Organism>& candidate_organism)
{
return this->get_coordinates() == candidate_organism->get_coordinates() && this != candidate_organism.get();
}
);
For that matter, I wouldn't really suggest naming the iterator as attacked_organism, either. It is not the actual Organism, it is an iterator to the Organism, so something more like this would be more readable:
auto& organism_vector = world->get_vector();
auto found_iterator = find_if(begin(organism_vector), end(organism_vector),
[this](const unique_ptr<Organism>& candidate_organism)
{
return this->get_coordinates() == candidate_organism->get_coordinates() && this != candidate_organism.get();
}
);
if (found_iterator != end(organism_vector))
{
auto &attacked_organism = *found_iterator;
attacked_organism->get_coordinates();
...
}
|
69,560,690 | 69,560,733 | Efficient way to get a reversed copy of std::string | Dealing with algorithmic tasks I frequently need to get a copy of reversed std::string. Also, the source string should not be modified. As far as I concerned, there are two ways to do it:
Use std::reverse :
// std::string sourceString has been initialized before.
std::string reversedString = sourceString;
std::reverse(reversedString.begin(), reversedString.end());
Use reverse iterators. This one I found on the Internet:
// std::string sourceString has been initialized before.
std::string reversedString{sourceString.rbegin(), sourceString.rend()};
My question is which approach I should prefer according to efficiency and best practices.
C-style solutions are not in my concern, I am only interested in STL-way approaches.
|
My question is which approach I should prefer according to efficiency
The one which should be preferred according to efficiency is the one that has been measured to be more efficient. Both have the same asymptotic complexity.
But, I won't bother to measure the difference unless it happens to be a bottleneck. I prefer 2, but it's subjective.
|
69,561,153 | 69,561,406 | smooth out corners of a 3-point line strip | I have a line strip defined by 3 points, each having an x and y coordinate.
I'm trying to smooth out the middle (point 2) corner as shown in the picture below:
the gray line is the original line strip and the black one is the smoothed-out one.
The smoothed out area should be constant across multiple values (as in it is not dependent on length of the line between p1 and p2 or p2 and p3).
I've originally been using bezier curves and a simple spline, however that did not do the trick since the smooth curve was obviously not same across multiple values.
How can I do this?
| Pick 2 points on each line that are the same distance to the corner. On those points draw two lines at right angles to the lines you already have (normal vectors pointing bottom left). They will cross at a point which will be the center of a circle, part this circle will then be the smoothed corner.
|
69,561,483 | 69,561,565 | getter setter c++ not as expected | i want to ask about getters/setters. i have 2 classes besides 'main'. I get an error when accessing a variable from a different class.
this is my code
#include <iostream>
using namespace std;
class Employee {
private:
// Private attribute
int salary;
public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};
class boss {
public:
void tes() {
Employee myObj;
cout << "(2) boss ask salary: " << myObj.getSalary() << "?\n";
myObj.setSalary(60000);
cout << "(3) boss said new salary: " << myObj.getSalary() << "\n";
}
};
int main() {
Employee myObj;
myObj.setSalary(50000);
cout << "(1) main said salary: " << myObj.getSalary() << "\n";
boss bs;
bs.tes();
return 0;
}
and output:
(1) main said salary: 50000
(2) boss ask salary: 32649?
(3) boss said new salary: 60000
why is the result in line 2 not as expected? should be 50000. How do I write the code to make it correct?
thank you.
| In main function you have one instance of Employee to which you set a salary of 50000.
In boss.tes() function, you have a different instance of Employee, which doesn't have any value in salary member, that is the reason you get a "garbage" value when printing 'boss ask salary'.
I don't know what should be the logic in your code, but in case you want it to be the same salary, you need to change the tes() method to receive Employee& and then it will work for you.
#include <iostream>
using namespace std;
class Employee {
private:
// Private attribute
int salary;
public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};
class boss {
public:
void tes(Employee& employee) {
cout << "(2) boss ask salary: " << employee.getSalary() << "?\n";
employee.setSalary(60000);
cout << "(3) boss said new salary: " << employee.getSalary() << "\n";
}
};
int main() {
Employee myObj;
myObj.setSalary(50000);
cout << "(1) main said salary: " << myObj.getSalary() << "\n";
boss bs;
bs.tes(myObj);
return 0;
}
|
69,561,534 | 69,561,853 | How to always have N number of lines in a ofstream file with real-time data | I'd like to write lines to a file using ofstream, 10 times, and I want the 11th line to be written in the 1st line's place, 12th in 2nd, and so on (so that my file would always have 10 lines, to preserve log file size).
So far my best try involves a circular buffer, shown below:
#include <cstdio>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream myfile("new.txt");
string line, buffer[10];
const size_t size = sizeof buffer / sizeof * buffer;
size_t i = 0;
while (getline(myfile, line))
{
buffer[i] = line;
if (++i >= size)
{
i = 0;
}
}
ofstream myfileo("new.txt");
for (size_t j = 0; j < size; ++j)
{
myfileo << buffer[i] << "\n";
if (++i >= size)
{
i = 0;
}
}
myfileo << "hey";
return 0;
}
But this tends to only work on VS windows and not on the actual c++ code run on linux with real-time data (silly, I know). The "real-time data" part is that myfileo << "hey" line.
Should it really be this difficult to have a log file with only 10 lines in C++?! I think another good try would be creating new log files after a certain amount of lines reached and deleting the previous ones, but I don't know how I could write that!
Thanks
| You can sort-of get the behavior you want by doing a
myfileo.seekp(0, std::ios_base::beg);
... every time you've just finished writing out the tenth line of text. That will move the file's write-position back to the top of the file, and from there on you'll be overwriting existing contents of the file instead of making the file larger.
I say "sort of", because unless all of your text-lines are exactly the same length, then you're going to end up with some leftover bytes at the end of the file whenever the previous 10 lines were longer than the new 10 lines. Maybe that's acceptable for your purpose, I don't know.
Another possible approach would be to myfileo.close() your ofstream after 10 lines and myfileo.open() a new file with a different name, and start writing to that file instead. Then when the new file is "full", delete the older file, and repeat the process. That way you'd always have two files on disk, one complete 10-line "old" file and a smaller (<10-line) "in progress" file; the advantage is that both files would be well-formed at all times.
|
69,562,141 | 69,562,415 | If char and int differ only in the number of bits, why are they different when printing? | In Difference between char and int when declaring character, the accepted answer says that the difference is the size in bits. Although, MicroVirus answer says:
it plays the role of a character in a string, certainly historically. When seen like this, the value of a char maps to a specified character, for instance via the ASCII encoding, but it can also be used with multi-byte encodings (one or more chars together map to one character).
Based on those answers: In the code below, why is the output not the same (since it's just a difference in bits)? What is the mechanism that makes each type print a different "character"?
#include <iostream>
int main() {
int a = 65;
char b = 65;
std::cout << a << std::endl;
std::cout << b << std::endl;
//output :
//65
//A
}
| A char may be treated as containing a numeric value and when a char is treated such it indeed differs from an int by its size -- it is smaller, typically a byte.
However, int and char are still different types and since C++ is a statically typed language, types matter. A variable's type can affect the behavior of programs, not just a variable's value. In the case in your question the two variables are printed differently because the operator << is overloaded; it treats int and char differently.
|
69,562,408 | 69,563,361 | Trying to press a button and toggle an LED flash at 2Hz until i press the button again | i'm trying to learn coding and this has really stumped me so i thought i would ask you lovely people.
basically i'm trying to press a button and have an LED toggle on that is flashing on and off twice in a second, this will be continuous until i press the button again that will turn it off.
here is my code so far.
bool latch = false;
void setup(){
pinMode(1, INPUT);
pinMode(13, OUTPUT);
}
void loop(){
if (digitalRead(1)){
latch = !latch;
}
if (latch == 1){
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(1000);
}else{
digitalWrite(13, LOW)
}
}
| Because of the calls to delay(1000), your code requires you to press the button in the exact split-second instant when digitalRead(1) is called. The Arduino cannot listen for button presses while delay() is in action. Also, you call delay(1000) twice, which flashes the LED on and off once in two seconds, not twice in once second.
The solution is to make a counter that counts how many milliseconds have passed since the last time the LED was toggled on or off. The loop will add 1 to counter every millisecond, so that when counter is equal to or greater than 500 (half a second), the LED toggles on or off.
Here is a program that starts blinking the LED (on-and-off in 1 second) when the button is pressed, and stops blinking when the button is pressed again. There are more explanations in the code.
bool latch = false;
bool led_state = false;
// How many milliseconds it has been since the last LED state change
int counter = 0;
void setup() {
pinMode(2, INPUT);
pinMode(13, OUTPUT);
}
void loop() {
// Check if the button was pressed
if (digitalRead(2)){
// If the button was pressed, wait half a second before toggling latch,
// to "de-bounce" the button (prevent it from sending multiple clicks for
// one press)
delay(300);
latch = !latch;
}
// If we are in on state (latch == true)...
if (latch) {
// ...add 1 to the counter and wait 1 millisecond...
counter += 1;
delay(1);
// ...and toggle the LED state if 500 milliseconds have passed.
// This we know because counter >= 500.
if (counter >= 500) {
if (led_state == true) led_state = false;
else if (led_state == false) led_state = true;
counter = 0;
}
digitalWrite(13, led_state);
// If we are in off state, turn the LED off
} else {
digitalWrite(13, false);
}
}
|
69,563,038 | 69,563,310 | error: no match for 'operator+=' (operand types are 'long double' and 'std::__cxx11::basic_string<char>') | I need to read values from a tuple that could be any datatype and then add them if they are numbers, or concatenate them if they are castable as strings.
tuple<int32_t, bool, string, float, const char*, char, int> t{10, true, "Modern", 2.3f, "C++", 'e', 13}; // Example Tuple
So I thought a template would be the way to go but I get a compilation error even though it should not be possible for the situation to happen where a number and a const char* are added.
no match for 'operator+=' (operand types are 'long double' and 'std::__cxx11::basic_string<char>')
22 | numericSum += tupleValue;
| ~~~~~~~~~~~^~~~~~~~~~~~~
error: in evaluation of 'operator+=(long double, const char*)'
So what could be a way to modify my code to work around this problem? Is there an easy way to detect chars and strings similarly to is_arithmetic?
// Based on the datatype of the tupleValue, we either add, concatenate or ignore the value
template<typename T>
void interact_with_tuple(T tupleValue, long double &numericSum, string &stringConcatenation, int &argumentsIgnored){
// Check for chars
if (is_convertible<T*, string>::value){
stringConcatenation += tupleValue;
}
// Check for strings and char pointers
else if (is_convertible<T, string>::value){
stringConcatenation += tupleValue;
}
// Check for integers and floating point numbers but exclude bools
else if (is_arithmetic<T>::value && !is_same<T, bool>::value){
numericSum += tupleValue;
}
else{
argumentsIgnored += 1;
}
cout << tupleValue << endl;
}
Code from main function:
int main(){
tuple<int32_t, bool, string, float, int> t{10, true, "Modern", 2.3f, 13}; // Example Tuple
long double NumericSum = 0.0;
string stringConcatenation = "";
int argumentsIgnored = 0; // Im going to assume I don't need a long long for this
// Iterate through Tuple
apply([&](auto&&... args){((interact_with_tuple(args, NumericSum, stringConcatenation, argumentsIgnored)), ...);}, t);
cout << "NumericSum: " << NumericSum << endl;
cout << "stringConcatenation: " << stringConcatenation << endl;
cout << "argumentsIgnored: " << argumentsIgnored << endl;
}
| You can use the C++17' is new compile-time conditional if constexpr. It will compile only the chunk that you need and discard the rest.
if constexpr (std::is_convertible<T*, std::string>::value){
stringConcatenation += tupleValue;
}
// Check for strings and char pointers
else if constexpr (std::is_convertible<T, std::string>::value){
stringConcatenation += tupleValue;
}
// Check for integers and floating point numbers but exclude bools
else if constexpr (std::is_arithmetic<T>::value && !std::is_same<T, bool>::value){
numericSum += tupleValue;
}
else{
argumentsIgnored += 1;
}
Live demo: https://godbolt.org/z/rff88hM8r
|
69,563,354 | 69,591,716 | How can you use std::setw() with array output? | I am making a blackjack game in C++, and I am trying to print out the players and dealers cards in addition to their sums, capital and so on. However I'm running into an issue with std::setw() when printing out the vector of cards. Here is a code snippet:
int width = 18;
std::cout << std::left << std::setw(width) << "Your cards:";
std::cout << std::left << std::setw(width * 2) << "arr";
std::cout << std::left << std::setw(width) << "Dealers cards:";
std::cout << "arr2" << std::endl;
std::cout << std::left << std::setw(width) << "Your sum:";
std::cout << std::left << std::setw(width*2) << player.sum();
std::cout << std::left << std::setw(width) << "Dealers sum:";
std::cout << dealer.sum() << std::endl;
Where arr and arr2 is there should be number values like 5 2 6 1, but if I print each element separately the with alignment will break. I think for setw() to work it needs to be one block or string, or else the vertical alignment will mess up once the values change. I tried myString.push_back() for each vector value and then printing that, with no luck. I assume I need to find a way to print the string into one element.
This is what it should look like:
Your cards: 5 7 1 2 Dealers cards: 2 1 7 5
Your sum: 21 Dealers sum: 21
Your capital: 100 Dealers capital: 100
| I have found a solution. You can use stringstream to add int values to a string with no errors in conversion, this is how I fixed my code:
#include <sstream>
std::stringstream playerCards{};
for (int i{}; i < player.cards.size(); i++) {
playerCards << player.cards[i] << " ";
}
int width = 18;
std::cout << std::left << std::setw(width) << "Your cards:";
std::cout << std::left << std::setw(width * 2) << playerCards.str();
This way the array will get put into a string and will count as one block, which is what I was looking for.
|
69,563,394 | 69,563,740 | Converting string back to byte array C++ | So I have a string that contains a byte array of HEX values.
I am trying to figure out how to go from the string back to the original byte array.
I am using an Arduino-based board.
Simply put, I want to turn this:
char addr3[47] = "0x28, 0xB6, 0x4C, 0x4E, 0x0D, 0x00, 0x00, 0x86";
Back into this:
byte addr2[8] = {0x28, 0xB6, 0x4C, 0x4E, 0x0D, 0x00, 0x00, 0x86};
Thank you for your help.
EDIT, Here is a solution I came up with following the answers/comments:
Starting with:
char addr3[47] = "0x28, 0xB6, 0x4C, 0x4E, 0x0D, 0x00, 0x00, 0x86";
I run the string through this:
sscanf(addr3, "%x", &r1);
sscanf(addr3, "%*s %x", &r2);
sscanf(addr3, "%*s %*s %x", &r3);
sscanf(addr3, "%*s %*s %*s %x", &r4);
sscanf(addr3, "%*s %*s %*s %*s %x", &r5);
sscanf(addr3, "%*s %*s %*s %*s %*s %x", &r6);
sscanf(addr3, "%*s %*s %*s %*s %*s %*s %x", &r7);
sscanf(addr3, "%*s %*s %*s %*s %*s %*s %*s %x", &r8);
byte addr[8] = {r1,r2,r3,r4,r5,r6,r7,r8};
and then we get:
byte addr[8] = 28B64C4ED0086
Which although is not the exact format I was looking for, it will work.
| To accomplish this you need to parse the string and convert the individual values to byte. You can do this using the sscanf function in the c library. I don't know if the arduino has an implementation of the sscanf function. But I would look into that first. If it does not then you will have to write a function that reads each character of the hex string and coverts it to the 4bit equivalent.
|
69,563,480 | 69,563,508 | Issues cleaning a string only to include alphabet characters | I'm having some issues with a part of a C++ program I'm writing to encode and decode a Playfair cipher. The part of the program I'm having issues with is the first step (unfortunate, I know), which involves removing all whitespace, punctuation, and non-alphabet characters. This is what I have:
std::string step1(std::string plaintext)
{
plaintext.erase(remove_if(plaintext.begin(), plaintext.end(),
std::not1(std::ptr_fun(std::isalpha))));
plaintext.erase(remove_if(plaintext.begin(), plaintext.end(),
std::ptr_fun(std::ispunct)));
return plaintext;
}
The output is good, except it adds characters at the end of the string once cleaned. Usually, the extra characters are copies of characters found at the end of the cleaned input. I can't, for the life of me, figure out why this is happening. Any ideas?
| std::remove/_if() does not actually remove anything, it just moves matching items to the end of the container, and then returns an iterator to the beginning of that range of items. The caller can then use that iterator to actually remove the items from the container.
You are passing that iterator to the overload of std::string::erase() that takes 1 iterator as input. Thus, it will erase only 1 character at most (if std::remove_if() did not find anything, it would return the string's end() iterator, and calling erase() on that iterator is undefined behavior). If more than 1 character were "removed" to the end of the string, the remaining un-erased characters would be left behind. That is what you are seeing in your output.
To erase all of the "removed" characters, you need to use the overload of std::string::erase() that takes 2 iterators denoting a range, eg:
std::string step1(std::string plaintext)
{
plaintext.erase(
std::remove_if(plaintext.begin(), plaintext.end(),
std::not1(std::ptr_fun(std::isalpha))
),
plaintext.end()
);
plaintext.erase(
std::remove_if(plaintext.begin(), plaintext.end(),
std::ptr_fun(std::ispunct)
),
plaintext.end()
);
return plaintext;
}
Note that removing all non-alpha characters using std:::isalpha() will include all whitespace and punctuation characters, thus your 2nd search using std::ispunct() will not find anything to remove, so you can just drop that search entirely, eg:
std::string step1(std::string plaintext)
{
plaintext.erase(
std::remove_if(plaintext.begin(), plaintext.end(),
std::not1(std::ptr_fun(std::isalpha))
),
plaintext.end()
);
return plaintext;
}
That being said, as noted in comments, std::not1() and std::ptr_fun are deprecated in modern C++. In C++11 and later, you can use a lambda instead:
std::string step1(std::string plaintext)
{
plaintext.erase(
std::remove_if(plaintext.begin(), plaintext.end(),
[](unsigned char ch){ return !std::isalpha(ch); }
),
plaintext.end()
);
return plaintext;
}
In C++20 and later, you can use std::erase_if():
std::string step1(std::string plaintext)
{
std::erase_if(plaintext,
[](unsigned char ch){ return !std::isalpha(ch); }
);
return plaintext;
}
|
69,563,813 | 69,563,902 | convert std::array of bytes to hex std::string | I'd like a way to take an arbitrary-size array of bytes and return a hex string. Specifically for logging packets sent over the net, but I use the equivalent function that takes a std::vector a lot. Something like this, probably a template?
std::string hex_str(const std::array<uint8_t,???> array);
I've searched but the solutions all say "treat it as a C-style array" and I am specifically asking whether there's a way not to do that. I assume the reason this isn't in every single C++ FAQ is that it's impossible and if so can someone outline why?
I already have these overloads and the second one can be used for std::array by decaying into a C-style array, so please don't tell me how to do that.
std::string hex_str(const std::vector<uint8_t> &data);
std::string hex_str(const uint8_t *data, const size_t size);
(edit: vector is a reference in my code)
| If you know the size of the std::array at compile time you can use a non type template parameter.
template<std::size_t N>
std::string hex_str( const std::array<std::uint8_t, N>& buffer )
{ /* Implementation */ }
int main( )
{
// Usage.
std::array<std::uint8_t, 5> bytes = { 1, 2, 3, 4, 5 };
const auto value{ hex_str( bytes ) };
}
Or you can just template the entire container (cut down on your overloads).
template<typename Container>
std::string hex_str( const Container& buffer )
{ /* Implementaion */ }
int main( )
{
// Usage.
std::array<std::uint8_t, 5> bytes = { 1, 2, 3, 4, 5 };
const auto value{ hex_str( bytes ) };
}
|
69,564,388 | 69,628,345 | OpenCV C++ absdiff() unhandled exception | I tried finding the frame difference between a still image and a frame taken from my webcam, using absdiff(). My code is as follows:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/objdetect.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main() {
VideoCapture webcam(0);
Mat img, web, diff;
webcam >> web;
img = imread("/Users/dnxv2/Desktop/test.jpg");
cvtColor(web, web, COLOR_BGR2GRAY);
cvtColor(img, img, COLOR_BGR2GRAY);
absdiff(img, web, diff);
imshow("test", diff);
waitKey(0);
}
Upon running it, I ran into an error, and I could not resolve it.
Unhandled exception at 0x00007FF937E24F99 in test.exe: Microsoft C++ exception: cv::Exception at memory location 0x000000FA29CFE1B0.
Was there something I missed? Your help is much appreciated!
| I figured out the solution to this problem. In short, it was only a small resolution issue, which could be fixed by matching the resolution of img with web.
Here are the two lines of code that seemed to resolve the issue if anyone is interested :D
int resx = 500, resy = 500; // 500x400 resolution
resize(img, img, { resx, resy }, 0, 0, cv::INTER_NEAREST);
resize(web, web, { resx, resy }, 0, 0, cv::INTER_NEAREST);
|
69,565,123 | 69,565,224 | How to use std::invoke_result_t in c++17 or 20 instead of std::result_of_t in c++14? | when I use std::result_of_t in c++14 it's doing as i wish:
void just_simple()
{
std::cout << "【4】: in func return nothing. " << std::endl;
}
template<typename Callback, typename... Args>
auto InTemplate_Call(Callback&& bc, Args&&... args)
{
typedef typename std::result_of_t<std::decay_t<Callback>(std::decay_t<Args>...)> ReturnType;
//typedef typename std::invoke_result_t<std::decay_t<Callback>(std::decay_t<Args>...)> ReturnType;
if (typeid(ReturnType) == typeid(void))
{
std::cout << "get a void type" << std::endl;
}
return rtDeduction<ReturnType>::type();
}
int main(){
InTemplate_Call(just_simple);
return 0;
}
The ReturnType is just void.
But It's not work in c++17 or 20:
template<typename Callback, typename... Args>
auto InTemplate_Call(Callback&& bc, Args&&... args)
{
//typedef typename std::result_of_t<std::decay_t<Callback>(std::decay_t<Args>...)> ReturnType;
typedef typename std::invoke_result_t<std::decay_t<Callback>(std::decay_t<Args>...)> ReturnType;
if (typeid(ReturnType) == typeid(void))
{
std::cout << "get a void type" << std::endl;
}
return rtDeduction<ReturnType>::type();
}
The ReturnType is not void anymore!
Is there anything I made mistake?
| The difference between invoke_result and result_of is that the former accepts the callable type and arguments type, but your std::decay_t<Callback>(std::decay_t<Args>...) is just a function type that returns a std::decay_t<Callback>.
The following shows the differences:
#include <functional>
void just_simple() {}
template<typename Callback>
void foo(Callback&&)
{
static_assert(std::is_same_v<std::invoke_result_t<Callback()>, Callback>);
static_assert(std::is_same_v<std::invoke_result_t<Callback >, void>);
}
int main() {
foo(just_simple);
}
You should do this:
typedef typename std::invoke_result_t<
std::decay_t<Callback>,
std::decay_t<Args>...> ReturnType;
|
69,565,125 | 69,566,163 | Does std::lock_guard release the mutex after constructed with std::adopt_lock option? | I know my question is quite similar to this Why does std::lock_guard release the lock after using std::adopt_lock?, but the behavior I see is not. Here is my code:
#include <mutex>
#include <iostream>
using namespace std;
std::mutex m;
void fun2();
void fun1() {
cout << "fun1" << endl;
std::unique_lock<std::mutex> guard(m);
cout << "lock mutex" << endl;
fun2();
if (guard.owns_lock()) {
cout << "still holds mutex" << endl;
}
else {
cout << "doesn't hold mutex" << endl;
}
}
void fun2() {
std::lock_guard<std::mutex> guard(m, std::adopt_lock);
cout << "fun2" << endl;
}
int main(int argc, char* argv[]) {
fun1();
return 0;
}
And this is the result I get:
fun1
lock mutex
fun2
still holds mutex
Clearly, the unique_lock in fun1 still holds the mutex. So my question is "Does std::lock_guard release the mutex after constructed with std::adopt_lock option?". Hope you all can help me clarify this situation. Thank you.
| When you constructed a std::unique_lock to manage the mutex, you should stick to it unless you first break the association of the std::unique_lock with the mutex using std::unique_lock::release. In your sample, you touched the raw mutex when it's still managed by a std::unique_lock and this is wrong.
|
69,565,333 | 69,566,130 | Are there overflow check math functions for MSVC? | While looking for functions that do overflow checks on signed and unsigned integer arithmetics, I came across this answer, which presents nice compiler intrinsics to do checked math in GCC. Since the code I'm currently writing needs to be cross-platform, I need something similar for the MSVC (Microsoft Visual Studio) compiler as well.
Does that exist or do I have to implement it manually?
| For unsigned addition and subtraction, MSVC has _addcarry_u16/32/64 and _subborrow_u16/32/64, all defined in <intrin.h>. They seem to produce optimal code, including generating add and sub instead of adc and sbb if you pass constant 0 for the carry in.
Unfortunately, there are no analogous intrinsics that return the overflow flag.
For 64×64 multiplication, __mulh and __umulh return the high 64 bits of the result, which you can compare with 0 in the unsigned case or low >> 63 in the signed case. There are also _[u]mul128 functions that return the whole result, but I think they would be more cumbersome to use and would generate the same code with optimization on (I haven't tested that).
For division, there are _[u]div64 and _[u]div128, defined in <immintrin.h>. It seems to be undocumented what they do in the case of overflow, but they most likely raise #DE, which could be caught with SEH.
In other cases, there's probably nothing better than to calculate the result at a higher precision and then bounds-check it.
|
69,565,521 | 69,565,650 | How to format a string according to the formatting method entered by user in c++? | How to format a string according to the formatting method entered by user in c++?
For example, here is an integer:
int x = 100;
If a user inputs a formatting method (a string):
"%x",
I want to output: 0x40.
And another user inputs a formatting string:
%.4f,
I want it output:100.0000.
How to do it?
| I see the following two concepts:
1.
read in the formatting string from the user
reject anything with more than one format specifier
reject anything with wrong format specifier for the type of the variable you want to output (using a float specifier for an integer for example would be wrong; just mentioning it specifically because your example looks like this....)
reject anything with the wrong format specifier for the width of the variable (same as above, just another detail)
reject wrong specifiers which do not attempt to output the variable (there are some fancy/dagerous things which could otherwise be done with a user-provided string...)
remove anything but the format specifier (assuming you mean to not allow "decoration")
either reject above by removing it and use the remainder
or reject by giving an error message and asking for another input
use the string for output
provide user with a choice of predefined safe and applicable formatting options
For security and reliability reasons I would probably go with option 2.
|
69,566,191 | 69,566,423 | std::any_cast throws a bad any_cast error when converting void* to function pointer | I wrote the code below,
std::unordered_map<std::string_view, std::any> symbols_;
symbols_["foo"] = dlsym(handle_), "foo");
When i use any_cast
return (std::any_cast<void(*)()>(symbols_["foo"]))();, the program will throw a error: bad any_cast.
I found the main reason because of the function .
template<typename _Tp>
void* __any_caster(const any* __any)
It would judge the condition as false and then return nullptr.
else if (__any->_M_manager == &any::_Manager<_Up>::_S_manage
#if __cpp_rtti
|| __any->type() == typeid(_Tp)
#endif
){
any::_Arg __arg;
__any->_M_manager(any::_Op_access, __any, &__arg);
return __arg._M_obj;
}
return nullptr;
I want to know
1.why __any->_M_manager == &any::_Manager<_Up>::_S_manage and __any->type() == typeid(_Tp) were all false,
2.and how can i fix the problem(continue to use std::any).
Here is a simple demo.
#include <any>
void func() { }
auto main() -> int {
std::any a = (void*)func;
std::any_cast<void(*)()>(a)();
return 1;
}
gcc version 10.1.0 (GCC)
| Here you store a void* in the std::any object:
symbols_["foo"] = dlsym(handle_, "foo");
To instead store a void(*)(), you need to cast the void* that's returned by dlsym:
symbols_["foo"] = reinterpret_cast<void(*)()>(dlsym(handle_, "foo"));
In this case, you may want to just store the void* and cast when using it instead:
std::unordered_map<std::string_view, void*> symbols_;
symbols_["foo"] = dlsym(handle_, "foo");
//...
return reinterpret_cast<void(*)()>(symbols_["foo"])();
A third option, if you don't need the runtime lookup in the unordered_map, is to instead store the function pointers in named variables. That makes the usage a little easier. Here's an example:
A generic class for loading/unloading a shared library:
class Lib {
public:
explicit Lib(const char* filename, int flags = RTLD_LAZY) :
lib(dlopen(filename, flags))
{
if(!lib) throw std::runtime_error(dlerror());
}
Lib(const Lib&) = delete;
Lib(Lib&& rhs) = delete;
Lib& operator=(const Lib&) = delete;
Lib& operator=(Lib&& rhs) = delete;
virtual ~Lib() { dlclose(lib); }
private:
struct cast_proxy { // a class to cast to the proper pointer
// cast to whatever that is needed:
template<class Func>
operator Func () { return reinterpret_cast<Func>(sym); }
void* sym;
};
protected:
cast_proxy sym(const char* symbol) const {
void* rv = dlsym(lib, symbol);
if(rv) return {rv}; // put it in the cast_proxy
throw std::runtime_error(dlerror());
}
private:
void* lib;
};
A class for loading a specific shared library:
class YourLib : public Lib {
public:
YourLib() : Lib("./libyour_library.so"),
// load all symbols here:
foo(sym("foo")) // the cast proxy will return the correct pointer type
{}
// Definitions of all the symbols you want to load:
void(*const foo)();
};
Then using it will be as simple as this:
int main() {
YourLib ml;
ml.foo();
}
|
69,567,240 | 69,567,431 | changing list of character to list int in C++ | i try to change from string to list of char, than list of char change to list int. here is my code
int main() {
std::string int1 = "1122334455";
std::list<char> listChars(int1.begin(), int1.end());
std::list<int> intList(listChars.begin(), listChars.end());
for(const auto& elem: intList){
std::cout << elem << " ";
}
}
The result of this is
49 49 50 50 51 51 52 52 53 53
not
1 1 2 2 3 3 4 4 5 5
the second method i try to use is
void printListInt(std::list<int>& listInt){
for(int i:listInt){
std::cout << i;
}
std::cout << std::endl;
}
int main() {
// make string "Hello World" and string "1122334455"
std::string str1 = "Hello World";
std::string int1 = "1122334455";
std::list<char> listChars(str1.begin(), str1.end());
std::list<char> listCharInt(int1.begin(), int1.end());
std::list<int> listInt(listCharInt.begin(), listCharInt.end());
printListInt(listInt);
}
I understand that it has to -48 to show the expected result, but is there possibility that i don't use for to recalculate list int?
| Yes, the output is correct because you had declared a string i.e, std::string int1 = "1122334455"; and then you are trying to print it as integer then the compiler will automatically typecast it according to the ASCII value of all characters of the string.
ASCII value of "0" is 48
ASCII value of "1" is 49
ASCII value of "2" is 50
ASCII value of "3" is 51
.
.
ASCII value of "9" is 57
So you are getting the first output as
49 49 50 50 51 51 52 52 53 53
Because it's being printed after typecasting from char/string to int.
If you want to print
1 1 2 2 3 3 4 4 5 5
then there are different approach to achieve that, here is one of them
#include <bits/stdc++.h>
using namespace std;
int main()
{
std::string int1 = "1122334455";
// std::list<char> listChars(int1.begin(), int1.end());
std::list<char> intList;
for (char c: int1) {
intList.push_back(c);
}
for(const auto& elem: intList){
std::cout << elem << " ";
}
return 0;
}
OR, if you print or store the entire string into Integer List then simply subtract with the ascii value of 0 (i.e, 48)
#include <bits/stdc++.h>
int main() {
std::string int1 = "1122334455";
std::list<char> listChars(int1.begin(), int1.end());
std::list<int> intList(listChars.begin(), listChars.end());
for(const auto& elem: intList){
std::cout << elem-48 << " ";
}
}
|
69,567,284 | 69,583,215 | ESP32 Firebase: authenticating results in error code 400 - but Firebase does recognize my login | I am trying to authenticate using signIn() method and exact replica of example code from ESP32 Client library (the new version)
When I run my code I successfully connect to WiFi and also I can
successfully CREATE new account from the ESP32 board.
I need to know if my log in or registration was successful
In my Firebase authentication signup with email/pass is enabled.
In my serial monitor I can read that the error code is 400 this:
Code that I am using:
Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION);
/* Assign the api key (required) */
fb_config.api_key = API_KEY;
/* Assign the user sign in credentials */
fb_auth.user.email = email_name.c_str();
fb_auth.user.password = email_name.c_str();
/* Assign the RTDB URL */
fb_config.database_url = DATABASE_URL;
Firebase.reconnectWiFi(true);
fb_do.setResponseSize(4096);
/* Assign the callback function for the long running token generation task */
fb_config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h
/** Assign the maximum retry of token generation */
fb_config.max_token_generation_retry = 5;
/* Initialize the library with the Firebase authen and config */
Firebase.begin(&fb_config, &fb_auth);
if(Firebase.authenticated()){
Serial.println("I am authenticated");
} else {
Serial.println("Well I AM NOT???");
}
Screenshot from my Firebase authentication that my ESP32 was created and also logged in today:
I know my Firebase initialization was successful because I can read and write read data into the Realtime database:
I am using PlatformIO and this is my config file:
[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 115200
build_flags = -D PIO_FRAMEWORK_ARDUINO_MMU_CACHE16_IRAM48_SECHEAP_SHARED
lib_deps =
mobizt/Firebase Arduino Client Library for ESP8266 and ESP32@^2.5.4
bblanchon/ArduinoJson@^6.18.5
|
The problem was that I was checking for the
Firebase.authenticated() method too early, and the Firebase did not
have time to authenticate.
If I check it in the main loop() it works.
GitHub discussion where we find the solution.
|
69,567,383 | 69,567,572 | Is using a reference to a derived class member in its base class well defined in C++? | I was looking into some code and it seemed to work but I am not sure if it is defined behavior.
I think there is a problem in it because Base is constructed with a reference to a Derived member variable - which is in my understanding constructed after Base.
I did some research on this and all I found were answers stating that Base is constructed before Derived, and Arguments from a Derived Constructor can be forwarded to the Base constructor.
But what about Derived Members, can they safely be forwarded to a Base Constructor?
Might Constructor and Destructor or even Member-Functions in Base work with invalid objects?
Here is simple code sample with the problem:
class Base
{
public:
Base(SomeClass & obj): m_obj(obj)
{
// Does using m_obj here cause problems with a Derived instance?
}
virtual ~Base()
{
// Does using m_obj here cause problems with a Derived instance?
}
void SomeMethod()
{
// Does using m_obj here cause problems with a Derived instance?
}
private:
SomeClass & m_obj;
};
class Derived : public Base
{
public:
Derived():Base(m_derObj){}
private:
SomeClass m_derObj{123};
};
OnlineGDB
Maybe I am missing some guarantee C++ gives - or maybe we were just lucky and the error never occurred.
|
Is using a reference to a derived class member in its base class well defined in C++?
Yes.
SomeClass m_derObj(123);
This is invalid syntax. If you intended to write a default member initialiser, you must use either curly braces or equals initialiser.
Base(SomeClass & obj): m_obj(obj)
{
// Does using m_obj here cause problems with a Derived instance?
}
The referred object hasn't been initialised yet, so you are very limited in what you can do with the reference.
If you try to do something that isn't allowed for such reference, such as for example try to access the referred object, then the behaviour of the program is undefined. If you don't do such thing, then it's OK.
virtual ~Base()
{
// Does using m_obj here cause problems with a Derived instance?
}
The referred object has been destroyed already, so you are very limited in what you can do with the reference.
If you try to do something that isn't allowed for such reference, such as for example try to access the referred object, then the behaviour of the program is undefined. If you don't do such thing, then it's OK.
void SomeMethod()
{
// Does using m_obj here cause problems with a Derived instance?
}
Depending on which constructor you used to initialise the object, there is a possibility that the reference has become dangling. In such case, there won't be anything that you can do with the reference without causing undefined behaviour. Furthermore, if you call the function from the constructor or destructor, the issue with the object being destroyed/not yet constructed applies.
But in the case the reference is still valid, it's fine.
|
69,567,737 | 69,568,382 | Max capacity for FBString? | For FBString, max_size() simply returns std::numeric_limits<size_type>::max(). However, the higher two bits of capacity_ in struct MediumLarge is used to denotes the type of FBString(small/medium/large), which means the max of capacity_ will be 2^62-1(64-bit processor), it's less than the max value of size_t. Do I misunderstand the implementation or is this actually a bug?
struct MediumLarge {
Char* data_;
size_t size_;
size_t capacity_;
size_t capacity() const {
return kIsLittleEndian ? capacity_ & capacityExtractMask : capacity_ >> 2;
}
void setCapacity(size_t cap, Category cat) {
capacity_ = kIsLittleEndian
? cap | (static_cast<size_t>(cat) << kCategoryShift)
: (cap << 2) | static_cast<size_t>(cat);
}
};
| Since the documentation for folly::FBString claims to be:
100% compatible with std::string
it actually seems to be a bug (in my opinion).
BTW, for large strings, FBString applies copy-on-write (COW), which also breaks the compatibility with std::string (since C++11).
See Legality of COW std::string implementation in C++11 for more details.
I would guess that they simply do not care about strings of unrealistic lengths (nowadays). The incompatibility due to COW might be much more severe.
|
69,567,916 | 69,568,029 | How to split a vector into three variables in C++ | In Python the following expression splits the list a into the three variables x,y,z:
a = [2,5,7]
(x,y,z) = a
Is there anything similar in C++? I've tried writing the following code but it does not works:
#include <iostream>
int main() {
int a[] = {3, 5, 7};
int x,y,z;
(x,y,z) = a;
}
Compiler fails with the following error:
error: assigning to 'int' from incompatible type 'int [3]'
(x, y, z) = arr;
| You can use structured bindings starting from C++17, like so:
std::tuple<int, int, int> a{ 1, 2, 3 };
auto [x, y, z] = a;
See: https://en.cppreference.com/w/cpp/language/structured_binding
Pre-C++17 you can use std::tie, like so:
std::tuple<int, int, int> a{ 1, 2, 3 };
int x, y, z;
std::tie(x, y, z) = a;
See https://en.cppreference.com/w/cpp/utility/tuple/tie
If it has to be something other than std::tuple or std::pair, you'll have to assign the variables manually:
x = a[0]; y = a[1]; x = a[2];
|
69,568,299 | 69,568,440 | Divide integer in array and store it as double in array | for(int i = 0; i < iData; i++)
{
if(hPred[i]<=jData[i])
{
akur[i] = hPred[i] / jData[i];
}
else if(hPred[i]>jData[i])
{
akur[i] = hPred[i] / jData[i];
akur[i] = akur[i] - 1.000;
}
}
I got some issues here. I wanted to divide data in hPred[] with jData[] and store it in an array as double(akur[]). Instead, I got this:
| for(int i = 0; i < iData; i++){
if(hPred[i]<=jData[i]){
akur[i] = (float)hPred[i] / jData[i];
}else if(hPred[i]>jData[i]){
akur[i] = (float)hPred[i] / jData[i];
akur[i] = akur[i] - 1.000;
}
}
typecast any operand to float before division
|
69,568,387 | 69,612,488 | Generate protobuf files for a library target in CMAKE | In the following project structure:
root/
├─ CMakeLists.txt
├─ protocol/
│ ├─ msg.proto
│ ├─ CMakeLists.txt
├─ app/
│ ├─ main.cpp
│ ├─ CMakeLists.txt
I could generate the protobuf files. However, once the app target is added into the project, the configuration step fails, because the protobuf files are not generated anymore.
root CMakeLists.txt:
cmake_minimum_required(VERSION 3.18.4)
project(
root
VERSION 0.1
LANGUAGES CXX
)
add_subdirectory(protocol)
add_subdirectory(app)
protocol CMakeLists.txt:
add_library(protocol)
target_include_directories(protocol
PUBLIC
.
${CMAKE_CURRENT_BINARY_DIR}
${Protobuf_INCLUDE_DIRS}
)
find_package(Protobuf REQUIRED)
set(PROTO_SOURCES msg.proto)
protobuf_generate_cpp(LIB_SOURCES LIB_HEADERS ${PROTO_SOURCES} )
target_link_libraries(protocol ${Protobuf_LIBRARIES})
target_sources(protocol
PUBLIC
${LIB_HEADERS}
PRIVATE
${LIB_SOURCES}
)
app CMakeLists.txt:
add_library(app)
target_link_libraries(app PUBLIC protocol)
target_include_directories(app PUBLIC .)
target_sources(app
PRIVATE
main.cpp
)
The way I understand it is that somehow I have to tell CMAKE the dependency, but as far as I know target_link_libraries should tell exactly that.
Another step I could take is to tell the app target that the headers in the protocol library are generated at build, so they can be generated before the dependant target compiles. How can it be done?
Many other questions reference similar problems, but none that I found had library dependencies in mind.
Update:
After moving ${LIB_HEADERS} from PUBLIC to PRIVATE:
add_library(protocol)
target_include_directories(protocol
PUBLIC
.
${CMAKE_CURRENT_BINARY_DIR}
${Protobuf_INCLUDE_DIRS}
)
find_package(Protobuf REQUIRED)
set(PROTO_SOURCES msg.proto)
protobuf_generate_cpp(LIB_SOURCES LIB_HEADERS ${PROTO_SOURCES} )
target_link_libraries(protocol ${Protobuf_LIBRARIES})
target_sources(protocol
PRIVATE
${LIB_HEADERS}
${LIB_SOURCES}
)
the configure step is successful, the msg.pb.h files are generated into the protocol subfloder in build; but make fails with the following error:
main.cpp:29:10: fatal error: protocol/msg.pb.h: No such file or directory
29 | #include "protocol/msg.pb.h"
|
So how can the headers be provided from target protocol in this setup?
| Based on help from @Tsyvarev:
After moving ${LIB_HEADERS} from PUBLIC to PRIVATE, the protobuf files are now generated.
To make them reachable through the library for the include
#include "protocol/msg.pb.h"
${CMAKE_BINARY_DIR} Needs to be changed into ${CMAKE_CURRENT_BINARY_DIR} in target_include_directories.
In case I the code includes protobuf headers directly:
#include "msg.pb.h"
${CMAKE_CURRENT_BINARY_DIR} needs to be there.
Because:
${CMAKE_CURRENT_BINARY_DIR} represents the submodule binary directoy ( protocol project
${CMAKE_CURRENT_BINARY_DIR} represents the project binary directoy ( protocol project
|
69,568,397 | 69,569,941 | Encoded Sound loses data when encoding Opus | I'm trying to encode with Opus some data recorded via PortAudio, so whenever I try to encode data, the written data is lost because the unsigned char vector ends up being empty for every iteration of the vector, the original data is recorded from PortAudio
here are my structures :
typedef struct {
int size;
std::vector<unsigned char> *sound;
} AudioEnc;
typedef struct {
int size;
std::vector<float> sound;
} AudioData;
here is my encode code :
#define SAMPLE_RATE (48000)
#define FRAMES_PER_BUFFER (1920)
#define NUM_SECONDS (1)
AudioEnc Opus::Encode(AudioData data)
{
AudioEnc enc = {.size = 0, .sound = new std::vector<unsigned char>};
unsigned int max_size = NUM_SECONDS * SAMPLE_RATE;
float sound[max_size];
enc.sound->resize(max_size);
if (data.size == 0)
enc.size = opus_encode_float(_encode, sound, FRAMES_PER_BUFFER, enc.sound->data(), max_size);
else
enc.size = opus_encode_float(_encode, data.sound.data(), FRAMES_PER_BUFFER, enc.sound->data(), max_size);
return (enc);
}
AudioData Opus::Decode(AudioEnc data)
{
AudioData dec;
dec.sound.resize(NUM_SECONDS * SAMPLE_RATE * 2);
dec.size = opus_decode_float(_decode, data.sound->data(), data.size, dec.sound.data(), FRAMES_PER_BUFFER, 0) * 2;
return (dec);
}
when i iterate through enc after the opus_encode_float method, all the values of sound are empty.
Do you guys have any idea on what's wrong ?
| It looks like the problem is that you're keeping two sizes. You're mixing C and C++ style, which probably explains the std::vector<unsigned char> *. But more importantly, std::vector<unsigned char> stores its own size, yet you also store a seprate size. And it looks like they don't agree.
The fix is easy. Don't store that .size in AudioEnc and AudioData. Instead, call .resize on the vectors to remember the size returned from Opus. This will discard the unused entries.
|
69,571,287 | 69,571,466 | Can I exclude a number or subrange of numbers inside a range of random numbers in modern C++? | I have:
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> probability(0, 100);
I want to exclude some numbers in this range of probabilities.
Example 1: Let's say, I want to generate a random number between 0 and 100, but this number can never be 4.
Example 2: Let's say, I want to generate a random number between 0 and 100, but this number can never be any number between 4 and 7.
I wonder if it is possible to achieve in modern C++ without using std::rand?
| If you want to stay with a uniform_int_distribution you can do it manually like this:
Example1: Let's say, I want to generate a random number in between 0 and 100, but this number can never be 4.
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> distribution(0,99);
auto temp = distribution(mt);
auto random_number = (temp < 4) ? temp : temp + 1;
Example2: Let's say, I want to generate a random number in between 0 and 100, but this number can never be any number between 4 and 7.
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> distribution(0,96);
auto temp = distribution(mt);
auto random_number = (temp < 4) ? temp : temp + 4;
This could be generalize to write a function random_int_between_excluding(int first, int last, std::vector<int> exclude), though at some point it will be simpler to follow NathanOlivers suggestion and use a std::discrete_distribution instead.
|
69,571,550 | 69,571,855 | Qt UDpsocket working on same computer but not on two computers on same network | I am able to send and receive to two different programs running on same computer. But not able to do the same when running them on different computers. Both computers are on same Local area network. I am working on windows 10.
#include "communicationmanager.h"
communicationManager::communicationManager(int portNumber,int socketRole)
{
//socketRole:0=Sender 1=Reciever
//socket = new QUdpSocket(this);
PortNumber = portNumber;
socket = new QUdpSocket(this);
if(socketRole == 1)
{
socket->bind(QHostAddress::LocalHost,PortNumber);
connect(socket, SIGNAL(readyRead()), this, SLOT(recieve()));
}
}
communicationManager::~communicationManager()
{
//delete socket;
}
void communicationManager::prepareMessage(QString command,QString message,int recieverID)
{
Command = command;
Message = message;
recieverID = recieverID;
}
void communicationManager::send()
{
QByteArray datagram;
QDataStream out(&datagram, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_13);
out<<Command<<Message<<recieverID;
socket->writeDatagram(datagram, QHostAddress::LocalHost, PortNumber);
}
void communicationManager::recieve()//For recieving data
{
qDebug()<<"recieve";
QByteArray datagram;
do
{
datagram.resize(socket->pendingDatagramSize());
socket->readDatagram(datagram.data(), datagram.size());
} while (socket->hasPendingDatagrams());
QDataStream in(&datagram, QIODevice::ReadOnly);
QString command;
QString message;
int recieverID;
in >>command>>message>>recieverID;
}
| You need to bind to QHostAddress::Any in order to actually receive packets from outside the local machine. QHostAddress::LocalHost will only receive traffic from the same physical machine.
|
69,571,825 | 69,633,602 | Reflecting LuaBridge classes from Lua scripts | Before April 2019, it was possible for a Lua script to reflect the methods and properties of a LuaBridge class using string keys __parent, __class, __propget, and __propset. This was an incredibly useful tool for creating test scripts and development tools to maintain a large class framework exported into Lua.
From looking through the release notes of LuaBridge, it seems the string keys were removed for security reasons. But I find myself placing more priority on the ability to reflect classes from scripts than on whether scripts can muck around in the object model. Especially in dev mode.
The LuaBridge Reference Manual implies there is a way for a C/C++ program to expose the metatables, but I haven't been able to figure out how to do it. I am quite new to interfacing between C and Lua (or LuaBridge), so I'm not surprised that I am perplexed. If anyone could share an example of how to do this, I would appreciate it.
| Since no one seems to have a good suggestion, I realized I could roll my own reflection of the names of properties, methods, and constants. For my purposes I don't really need to execute or access them.
So rather than muck around inside LuaBridge I added __class, __propget, and __propset static properties to every class in my framework. These return a table implemented with std::map which LuaBridge supports. The tables simple have the names as keys and a dummy value.
One caveat I discovered is that you have to add static properties to derived classes when creating the derived class with deriveClass. If you try to add them later (using beginClass), LuaBridge throws an assert.
|
69,571,947 | 69,575,486 | What does it mean that data is prepared in the function of mosquitto_want_write()? | According to the API, the mosquitto_want_write() function returns TRUE when data to be used in the socket is prepared.
But what does it mean to have data ready? Where is the data being prepared? What function call can prepare the data?
Is the data prepared by the call Mosquito_publish()?
Unfortunately, I couldn't find any link related to this. I would appreciate it if you could let me know if there is any data or link related to this.
| Look no further than the definition of mosquitto_want_write:
bool mosquitto_want_write(struct mosquitto *mosq) {
bool result = false;
if(mosq->out_packet || mosq->current_out_packet){
result = true;
}
return result;
}
A call to mosquitto_publish eventually ends up in send__publish, which calls send__real_publish, which calls packet__queue.
And packet__queue is where mosq->out_packet is filled:
pthread_mutex_lock(&mosq->out_packet_mutex);
if(mosq->out_packet){
mosq->out_packet_last->next = packet;
}else{
mosq->out_packet = packet;
}
mosq->out_packet_last = packet;
pthread_mutex_unlock(&mosq->out_packet_mutex);
So, to summarize: mosquitto struct holds a linked list of packets to send and the actions add packets to the queue. Under certain conditions these packets are sent directly, I will leave it up to you to figure out what these are.
|
69,571,993 | 69,572,058 | Issue while extracting tuple element type in variadic tuple | I'm trying to write generic function that iterates through std::tuple elements. In doing so, i need to extract the element type of the given tuple element that is being processed. However, i'm running into an issue regarding type equality between the extracted type and the actual type of the tuple element. The below code illustrates the problem by adding static_asserts to the extracted type, which (as far as i can tell) should be true in both cases:
#include <tuple>
#include <type_traits>
using TestTuple = std::tuple<int>;
template <std::size_t I = 0, typename... Tp>
inline typename std::enable_if<I == sizeof...(Tp), void>::type
foo(std::tuple<Tp...> &) {}
template <std::size_t I = 0, typename... Tp>
inline typename std::enable_if <
I<sizeof...(Tp), void>::type foo(std::tuple<Tp...> &output) {
// Using tuple element
using ValueType = std::tuple_element<I, std::tuple<Tp...>>;
static_assert(std::is_same<ValueType, int>::value, "Should be true");
using ValueType2 = std::remove_reference<decltype(std::get<I>(output))>;
static_assert(std::is_same<ValueType2, int>::value, "Should be true");
}
void bar() {
TestTuple t;
foo(t);
}
Trying to compile through Compiler Explorer, both static_asserts fail on both GCC 11.2 and clang-13; clang output is:
<source>:16:5: error: static_assert failed due to requirement 'std::is_same<std::tuple_element<0, std::tuple<int>>, int>::value' "Should be true"
static_assert(std::is_same<ValueType, int>::value, "Should be true");
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:24:5: note: in instantiation of function template specialization 'foo<0UL, int>' requested here
foo(t);
^
<source>:19:5: error: static_assert failed due to requirement 'std::is_same<std::remove_reference<int &>, int>::value' "Should be true"
static_assert(std::is_same<ValueType2, int>::value, "Should be true");
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2 errors generated.
Compiler returned: 1
| You're not getting the type of the element of the tuple correctly. They should be
using ValueType = typename std::tuple_element<I, std::tuple<Tp...>>::type;
// ^^^^^^^^ ^^^^^^
static_assert(std::is_same<ValueType, int>::value, "Should be true");
using ValueType2 = typename std::remove_reference<decltype(std::get<I>(output))>::type;
// ^^^^^^^^ ^^^^^^
static_assert(std::is_same<ValueType2, int>::value, "Should be true");
Or (since C++14)
using ValueType = std::tuple_element_t<I, std::tuple<Tp...>>;
// ^^
static_assert(std::is_same<ValueType, int>::value, "Should be true");
using ValueType2 = std::remove_reference_t<decltype(std::get<I>(output))>;
// ^^
static_assert(std::is_same<ValueType2, int>::value, "Should be true");
|
69,572,294 | 69,577,892 | why does hotspot jvm use extern "C" in its JNI modules? | Since jvm itself is implemented and built by c++, why does it need to declare extern "C"?
extern "C" is used to generated c-compatible target, why does a c++ jvm need that?
| One nice quality of JNI is that you can compile it once and link it to any JVM for that platform. These days that's less of an issue since pretty much all JVMs are based on OpenJDK, but once upon a time there were several JVMs that had completely different implementations. My JNI library compiled on Windows could link to the Sun JVM or the Microsoft JVM. Using "C" linkage ensures compatibility regardless of what compiler I'm using, or what compiler the JVM was built with. The names won't get mangled, the parameters aren't modified, etc.
|
69,572,317 | 69,573,088 | Why does boost::basic_array_source give other values than what I have stored with boost::iostreams::back_insert_device? | I am trying to use functions of a library that reads and writes from/to streams. To adapt my data to that library, I wanted to use boost::iostreams from boost 1.77.0. Still, a first very simple example does not work as expected. Why?
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/device/back_inserter.hpp>
#include <boost/iostreams/stream.hpp>
#include <iostream>
int main(int, char*[])
{
// Create container
std::vector<char> bytes;
// Set up stream to write three chars to container
boost::iostreams::back_insert_device<std::vector<char>> inserter =
boost::iostreams::back_inserter(bytes);
boost::iostreams::stream stream(inserter);
// Write chars
stream << 1;
stream << 2;
stream << 3;
stream.close();
// Check container
for (char entry : bytes)
{
std::cout << "Entry: " << entry << std::endl;
}
std::cout << "There are " << bytes.size() << " bytes." << std::endl;
// Set up stream to read chars from container
boost::iostreams::basic_array_source<char> source(bytes.data(), bytes.size());
boost::iostreams::stream stream2(source);
// Read chars from container
while (!stream2.eof())
{
std::cout << "Read entry " << stream2.get() << std::endl;
}
return 0;
}
The output is:
Entry: 1
Entry: 2
Entry: 3
There are 3 bytes.
Read entry 49
Read entry 50
Read entry 51
Read entry -1
Why does it read 49, 50 and 51 instead of 1, 2 and 3? The -1 doesn't surprise me that much, it might denote the end of the container. Am I using the classes in a wrong way?
| It works correct to me, but not in the intuitive way though. You are putting integers 1 2 and 3 into the vector of chars via stream, so they land there as their ASCII codes, 49, 50 and 51 respectively. In the initial loop you are actually printing characters, not their integer representations, thus. I suggest you should try std::cout << "Entry: " << +entry << std::endl; (note the + sign) and it will become clear.
|
69,572,484 | 69,572,542 | If I had already declared the size and initialize the array in this C++ snippet how is this code running? | I am new to C++(please assume no C knowledge while answering).
I have just started learning about arrays and ran the following code :-
#include<iostream>
using namespace std;
int main(){
int arr_[10] ={1,2,3,4,5,6,7,8,9,0};
int i=0;
while (i<4)
{
printf("Value of arr_[ %i ] = %i \n",i ,arr_[i]);
i++;
}
arr_[15] = 555;
cout<<arr_[11]<<endl<<arr_[12]<<endl<<arr_[15];
return 0;
}
I was expecting an error but to my surprise the program successfully compiled and ran to produce the following output :-
Value of arr_[ 0 ] = 648017456
Value of arr_[ 1 ] = 648017456
Value of arr_[ 2 ] = 648017456
Value of arr_[ 3 ] = 648017456
4
1
555
I tried the same program once again on another machine . It produced a different output:-
Value of arr_[ 0 ] = 1
Value of arr_[ 1 ] = 2
Value of arr_[ 2 ] = 3
Value of arr_[ 3 ] = 4
-1644508256
0
555
So here are my queries I want to resolve :-
If array size was fixed to 10 items how come I was able to add a value at the index number 15 ?
If arrays are contiguous blocks of assigned memory , then how come I was able to jump out and declare a value skipping indices?
From where do the output of values at index numbers 11 and 12 come from ?
Does that mean C++ does not check ArrayOutOfIndex errors like Java and Python ?
I later added following line to my code :-
cout<<endl<<sizeof(arr_)/sizeof(int); //to find number of items
which returned the number of Items in the array to be 10 .
And this makes me horribly confused . I tried checking in books but could not find relevant
information or the terminology is too verbose to understand as a beginner and on web hunting
for such information proved to be too painful and went into vain.
| When you try to access the out of bound element of the array then the output is undefined. That is why you are getting different results on different run of the program.
arr_[15] = 555;
cout<<arr_[11]<<endl<<arr_[12]<<endl<<arr_[15];
Both of the above statements produce undefined behavior.
You can read more on this topic at : Accessing an array out of bounds gives no error, why?
The program crashes here.
But here the program doesn't crash.
This is the result of undefined behavior.
|
69,573,120 | 69,573,363 | can you replace enable_if to disable a function it if constexpr? | So I know you can use enable_if to disable a function template (e.g. if the type is not integral) - but can you do the same with constexpr?
i.e. is there an equivalent for this:
template<class T, typename = std::enable_if_t<std::is_integral_v<T>> >
T test2()
{
return {};
}
with constexpr - something like:
template <typename T>
T test()
{
// we expect various integral and floating point types here
if constexpr (std::is_integral_v<T>)
{
T output{};
return output;
}
else
{
// trigger compiler error
return{};
}
}
so I want:
test(1); // compile ok
test(std::string("hello")); // compile fail
| It is as simple as this:
template <typename T>
T test()
{
static_assert(std::is_integral_v<T>);
T output{};
return output;
}
|
69,573,327 | 69,603,379 | Qt Creator display in application output: NVD3DREL: GR-805 : DX9 Overlay is DISABLED | As I am working with my project, I noticed that when I run my app, inside the Application Output area I can see message:
NVD3DREL: GR-805 : DX9 Overlay is DISABLED
NVD3DREL: GR-805 : DX9 Overlay is DISABLED
NVD3DREL: GR-805 : DX9 Overlay is DISABLED
I have no idea what it means, but to be honest it has no impact on my app, but I don't like to see any kind of unnecessary messages. I've tried to google it, but found no similar issues. What might be a reason? I wasn't doing any changes in my code but this message appeared out of nowhere. Lately I installed CUDA SDK on my PC for another project and that's the only connection I can think of with DirectX. Any suggestions?
| The problem is a problem in the Nvidia Driver 496.13. I had the same problem, and reverting to an older version fixed it
|
69,573,668 | 69,573,809 | dynamic_cast on polymorphic class copy segfaults | The following code snippet causes a segmentation fault during the dynamic_cast. Can anybody explain to me why this happens?
#include <cassert>
#include <cstdint>
uint8_t buffer[32];
class Top {
public:
virtual ~Top() = default;
};
template <typename T>
class Middle : public Top {
public:
void copy() {
// Create copy of class instance in buffer
auto memory{reinterpret_cast<T *>(buffer)};
*memory = *dynamic_cast<T *>(this);
// Upcast, works
Top * topPtr{memory};
assert(topPtr != nullptr);
// Downcast, causes segmentation fault, why?
auto bottomPtr{dynamic_cast<T *>(topPtr)};
}
};
class Bottom : public Middle<Bottom> {
};
int main() {
Bottom b;
b.copy();
}
Thanks.
| auto memory{reinterpret_cast<T *>(buffer)};
*memory = *dynamic_cast<T *>(this);
This is incorrect approach, you cannot just interpret some bytes as T. Objects are created only by calling the appropriate constructors which for example initialize the virtual jump table.
The second line is also wrong even in your context. It calls the assignment operator, that rightfully assumes its this is an alive object.
The correct way is using placement new with correctly aligned storage, for example std::aligned_storage_t<sizeof(T),alignof(T)>.
Working example:
#include <cstdint>
#include <cassert>
#include <type_traits>
#include <new>
class Top {
public:
virtual ~Top() = default;
};
template <typename T>
class Middle : public Top {
public:
void copy() {
std::aligned_storage_t<sizeof(T),alignof(T)> buffer;
// Create a new T object. Assume default construction.
auto* memory = new(&buffer)T();
// Copy the object using operator=(const T&)
*memory = *dynamic_cast<T *>(this);
// Upcast, works
Top * topPtr{memory};
assert(topPtr != nullptr);
// Downcast also works.
auto* bottomPtr{dynamic_cast<T *>(topPtr)};
// Using placement new requires explicit call to destructor.
memory->~T();
}
};
class Bottom : public Middle<Bottom> {
};
int main() {
Bottom b;
b.copy();
}
Lifetime begins with a constructor call, you cannot get around that, if it needs parameters, you have to pass them.
operator= is the correct approach to copy objects, do not use std::memcpy unless you really know what you are doing.
Objects created by placement new require explicit call to their destructor.
Please do not hide pointers behind auto, typedef,or using with exception of opaque handles.
|
69,573,790 | 69,574,137 | How to group CTests together? | I would like to make groups of CTests to improve readability with a structure like this:
How can I do this? My current CMakeLists.txt:
cmake_minimum_required(VERSION 3.20)
project(Test)
set(CMAKE_CXX_STANDARD 14)
enable_testing()
add_executable(env environment.cpp)
add_test(Environment env)
add_subdirectory(unit) # Includes tests 'UserInterface' and 'Test2'
The tests in the subdirectory are not grouped together when I run it:
| CTest doesn't support this, as it's not a classical unit testing framework, but rather a convenient way to "run stuff" that is already configured (in most cases) to be built with CMake.
What you can do is:
Impose a naming scheme, e.g. prefix tests by a common identifier. For all tests that are registered with add_test(foo_...), you can run this group with ctest -R foo_ for example.
Associate setup- and teardown-like test with a set of tests (have a look at test properties like FIXTURES_CLEANUP). However, this doesn't give you structure per se, it only ensures a certain existing test is run as a setup/teardown before/after the test in question.
|
69,574,043 | 69,574,434 | NodeJS source code cannot find set_immediate_callback_function definition | I am trying to understand how Node works internally. I am really interested in the check phase but could not make sense of thing how that phase queue is processed. Right now I cannot understand where set_immediate_callback_function is defined. Such method is part of Environment class but I cannot see it.
This methods is called during the setup phase at:
void SetupTimers(const FunctionCallbackInfo<Value>& args) {
CHECK(args[0]->IsFunction());
CHECK(args[1]->IsFunction());
auto env = Environment::GetCurrent(args);
env->set_immediate_callback_function(args[0].As<Function>());
env->set_timers_callback_function(args[1].As<Function>());
}
| The set_immediate_callback_function is generated by the preprocessor, by a technique called X-Macros.
Let's break it down. You are referring to this code:
void SetupTimers(const FunctionCallbackInfo<Value>& args) {
CHECK(args[0]->IsFunction());
CHECK(args[1]->IsFunction());
auto env = Environment::GetCurrent(args);
env->set_immediate_callback_function(args[0].As<Function>());
env->set_timers_callback_function(args[1].As<Function>());
}
Grepping for set_immediate_callback_function does not reveal anything. But if you grep for immediate_callback_function (without the set_), you will find this here:
#define ENVIRONMENT_STRONG_PERSISTENT_VALUES(V) \
...
V(immediate_callback_function, v8::Function) \
This pattern is often called X-Macros. Following the trace, you can find ENVIRONMENT_STRONG_PERSISTENT_VALUES here:
#define V(PropertyName, TypeName) \
inline v8::Local<TypeName> PropertyName() const; \
inline void set_ ## PropertyName(v8::Local<TypeName> value);
ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
#undef V
Notice this line:
inline void set_ ## PropertyName(v8::Local<TypeName> value);
PropertyName is immediate_callback_function and ## is string concatenation. So, finally that is the origin of set_immediate_callback_function.
For the exact expansion, you would need to run the preprocessor. I find it hard to follow the expansion in my head after this point. It should end up with something like that:
inline v8::Local<v8::Function> immediate_callback_function() const;
inline void set_immediate_callback_function(v8::Local<v8::Function> value);
Looks like the NodeJs codebase uses the C preprocessor to generate a property-like mechanism. In C and C++, properties are not supported directly, and I assume they wanted to avoid duplicating code. That is why they used code generation through the preprocessor.
(X-Macros are a technique that should not be overused. Yet it is difficult to decide where to draw the line. As you saw, it makes it harder to reason about the code. On the other hands, manual code repetition can be more error-prone and verbose.)
|
69,574,129 | 69,574,713 | Problem in assigning of dynamic memory with dereference operator | I don't understand why the second for loop doesn't access my dynamic memory well.
After I exit the loop, the dynamic memory will somehow lose its data, while if I use the "second method" it will be ok.
Could you explain to me why is that?
Here is the code:
#include <iostream>
int main()
{
int* foo;
foo = new (std::nothrow) int[3];
int temp;
for (int i = 0; i != 3; i++)
{
std::cin >> temp;
*foo = temp;
foo++;
//std::cin >> foo[i];// second method (instead of line 10,11 and 12)
}
for (int i = 0; i != 3; i++)
std::cout << *(foo+i) << std::endl;
return 0;
}
| After you allocate the array and assign its starting address to foo, you are incrementing foo in the 1st loop to access each int in the array. By the time you get to the second loop, foo is now pointing past the end of the array. That is why your 2nd loop cannot access the values correctly.
Your "second method" does not increment foo at all, so it remains pointing at the start of the array at all times.
To make your "first method" work correctly, use a separate pointer for the iteration:
#include <iostream>
int main()
{
int* foo = new (std::nothrow) int[3];
int* ptr = foo; // <-- ADD THIS
int temp;
for (int i = 0; i < 3; i++)
{
std::cin >> temp;
*ptr = temp;
++ptr;
//std::cin >> foo[i];// second method
}
for (int i = 0; i < 3; ++i)
std::cout << *(foo+i) << std::endl;
delete[] foo;
return 0;
}
|
69,574,143 | 69,574,946 | move semantics in constructor in return statement | I know that when returning a local in order to keep RVO we should allow the compiler to perform move elision by returning a value like so
std::vector<double> some_func(){
std::vector<double> my_vector;
//do something
return my_vector;
}
rather than
std::vector<double> some_func(){
std::vector<double> my_vector;
//do something
return std::move(my_vector);
}
However, if we are constructing an object in a return statement, do uses of std::move in the constructor either help, hinder, or do nothing to get efficiency or get in the compilers way?
As an example consider these two implementations
std::pair<std::vector<double>,std::vector<double> > some_func()
std::vector<double> my_vec_a;
std::vector<double> my_vec_b;
//do something
return std::make_pair(my_vec_a,my_vec_b);
}
and
std::pair<std::vector<double>,std::vector<double> > some_func()
std::vector<double> my_vec_a;
std::vector<double> my_vec_b;
//do something
return std::make_pair(std::move(my_vec_a),std::move(my_vec_b));
}
So
In the first, will the compiler recognise that my_vec_a and my_vec_b will go out of scope and optimise the construction in the return statement?
If so will the use of std::move in the second prevent that optimisation?
Or will the second option be more efficient?
| This one is more efficient:
std::pair<std::vector<double>,std::vector<double> > some_func() {
std::vector<double> my_vec_a;
std::vector<double> my_vec_b;
//do something
return std::make_pair(std::move(my_vec_a),std::move(my_vec_b));
}
without the calls to std::move the two vectors will be copied.
The problem, however, isn't the actual return. It's that the two vectors in the pair being constructed are being constructed from lvalues; the compiler can't choose to use a move-constructor there without you explicitly telling it to via std::move.
|
69,574,163 | 69,574,594 | c++ change object properties of object that is key in map? | Say I have the following classes:
#include <string>
class Item {
public:
Item(std::string name, int id);
virtual int getWeight() = 0;
protected:
std::string name;
const int id;
}
#include <vector>
#include <memory>
#include "Item.h"
class Bucket : Item {
public:
Bucket(std::string name, std::string type, int id) // In the implementation this will call the Constructor of Item
bool operator<(const Bucket& b) const {
return (id < b.id );
}
void addItem(std::shared_ptr<Item> itemm) {
this->weight += item->getWeight();
this->items.push_back(item);
}
int getWeight() override; //this implementation does not matter to the problem
private:
std::string type;
std::vector<std::shared_ptr<Item>> items;
int weight = 0;
}
There are other classes inheriting from class Item aswell, but to make it easier I am only showing the class Bucket.
Now in my main method, I want to iterate over a map, that already contains some entries and call a method that changes one property of the key object.
main.cpp:
#include <map>
#include <memory>
#include <vector>
#include "Item.h"
#include "Bucket.h"
using namespace std;
int main(){
map<Bucket, vector<shared_ptr<Item>>> map; // Imagine this map has some entries
for(auto itr = map.begin(); itr != map.end(); itr++){
for_each(itr->second.begin(), itr->second.begin(), [&itr](shared_ptr<Item> item){
itr->first.addItem(item); // This does not compile, the error will be in the text below
});
}
As told in the code, it does not compile with the following error on line itr->first.addItem(item);:
'this' argument to member function 'addItem' has type 'const Bucket', but function is not marked const.
I can't make the method const, since it is changeing some property of the object and I would get an error there.
I am not sure if I understand this error correctly, but I think the problem is, that as I put a Bucket into a map (Bucket is the key), it becomes const.
If that is the case, is there a way to tell the compiler to use only the id property of Bucket as the const key of the map (Without changeing the map to something like map<int, <pair<Bucket,vector<shared_ptr<Item>>>>>)? Or am I not understanding the main problem here?
|
I think the problem is, that as I put a Bucket into a map (Bucket is the key), it becomes const
Correct. Maps are supposed to be ordered, and if you were able to mutate a key, you could break this invariant. Doing this would potentially break every subsequent search or insert horribly.
The linked workaround is effective, but ugly. Unless map-key-ness is a core feature of your Bucket (I can't tell from the sample code whether that's likely), making some of its members mutable feels like a hack.
Your whole design looks odd, tbh - you're going to end up with a map full of Bucket keys that duplicate the information in the second half of the key,value pair. Are you going to move those Buckets somewhere else afterwards, or are they going to live forever shackled to those vestigial vectors of redundant references?
If that map is an intermediate step in building up connections, it shouldn't be where the Bucket objects live. Perhaps you should have one main lookup map<id, Item>, another transient mapping multimap<id, id> describing which Item contains which other Items.
|
69,574,308 | 69,574,361 | Friend function for class in dll | Lets say I have the following class in my dll
class Test { private: int x; };
and following function in client side application which uses my dll
void test();
Is there a way to make test function friend for Test class?
|
Is there a way to make test function friend for Test class?
Yes, add a friend declaration to the class definition:
class Test {
private:
int x;
friend void test();
};
|
69,574,909 | 69,575,144 | Declaring an object in a header when its definition is in a different header | I am new to cpp, looking at an existing project.
There are several places in the project where an object is defined in a namespace in some header file and then declared in the same namespace and used in other declarations in some other header file. Example:
MyStruct.hpp:
namespace A { struct MyStruct { int i; }; }
MyClass.hpp:
namespace A { struct MyStruct; }
namespace B {
class MyClass {
private:
void foo(A::MyStruct& s);
};
}
MyClass.cpp:
#include "MyClass.hpp"
#include "MyStruct.hpp"
namespace B {
class MyClass {
void foo(A::MyStruct& s) { /* ... */ }
};
}
I might have expected there to be an #include "MyStruct.hpp" in MyClass.hpp, but that is not the case. I guess when the two header files are isolated there is not yet any relationship between the MyStruct objects in that case. Why does this not create some conflict though when the two headers are loaded together in the implementation file? I cannot, for instance, write int j; int j = 0;. Does the order of the #includes matter? And what might be the motivation for doing this?
| What you are seeing is a forward declaration being used.
Since foo() takes a MyStruct by reference, MyClass.hpp doesn't need to know the full declaration of MyStruct in order to declare foo(), it only needs to know that MyStruct exists somewhere. The linker will match them up later.
MyClass.cpp, on the other hand, needs to know the full declaration of MyStruct in order for foo()'s implementation to access the contents of its s parameter. So MyStruct.hpp is used there instead.
This also means that if the contents of MyStruct.hpp are ever modified, any source files using MyClass.hpp don't have to be recompiled since the forward declaration of MyStruct won't change (unless the namespace is changed, that is). Only files that are using MyStruct.hpp will need recompiling, like MyClass.cpp.
|
69,575,307 | 69,575,692 | Microsoft C/C++: what is the definition of "strict conformance" w.r.t. implementation? | Context:
/Za, /Ze (Disable Language Extensions):
... the C compiler conforms strictly to the C89/C90 standard
/permissive- (Standards conformance):
... and sets the /Zc compiler options for strict conformance
C++ Conformance improvements, behavior changes, and bug fixes in Visual Studio 2019:
... /permissive may be specified to turn off strict conformance mode in the compiler.
The second option is meant to disable the strict conformance mode ...
clock:
Note that this is not strictly conformant with ISO C99 ...
Walkthrough: Compile a C program on the command line:
MSVC is compatible with the ANSI C89 and ISO C99 standards, but not strictly conforming.
Question: what is the definition of "strict conformance"? Was it invented by Microsoft?
Note: both C (n2596.pdf) and C++ (n4849.pdf) standards no not use term "strict conformance" / "strictly conforming" applied to the implementation. The implementation is either conforming, either non-conforming. W/o gradations.
UPD. My guess: under "strict conformance" (w.r.t. to implemtation) Microsoft means "conforming implementation w/o support of any extensions".
| The C11 standard defines a strictly conforming program and implementation in section 4 paragraphs 5-7 as follows:
5 A strictly conforming program shall use only those features of the language and library specified in this
International Standard. It shall not produce output dependent
on any unspecified, undefined, or implementation-defined
behavior, and shall not exceed any minimum implementation limit.
6 The two forms of conforming implementation are hosted and freestanding. A conforming hosted implementation shall accept any
strictly conforming program. A conforming freestanding
implementation shall accept any strictly conforming program in
which the ∗ use of the features specified in the library clause
(clause 7) is confined to the contents of the standard headers
<float.h>, <iso646.h>, <limits.h>, <stdalign.h>, <stdarg.h>,
<stdbool.h>, <stddef.h>, <stdint.h>, and <stdnoreturn.h>. A
conforming implementation may have extensions (including
additional library functions), provided they do not alter the
behavior of any strictly conforming program.
7 A conforming program is one that is acceptable to a conforming implementation.
While the terms strictly conforming implementation and strict conformance do not appear here, they can be understood to mean an implementation (in a given mode) that will only accept a strictly conforming program (or more accurately, an implementation that doesn't support features not specified in the standard) .
|
69,575,497 | 69,575,704 | Is it possible to capture a type template into a template argument? | Is it possible to capture a template from a template argument i.e. have a nested template specifier with a template argument that holds the template type?
template< typename T, typename Label = std::string>
class foo {
// ...
};
template <
template < typename C, typename T > typename C<T>,
// ...
typename Label = std::string
>
class bar {
// ...
C< foo< T, Label > > A;
};
For instance, I'd like to pass a generic STL container (std::vector< int >) as template argument, but declare a member of the same meta-type (std::vector) but with different value type (foo< int >) i.e. std::vector< foo< int > >. It may seem convoluted, but it would be helpful to not hardcode the type of STL container.
For context, I'm aiming at a generic container adapter/wrapper (in the line of std::stack or std::queue) that provides some higher-level functionality.
| Yes, you can just use template specialization:
#include <string>
template<typename T, typename Label = std::string>
class foo {};
template <class T, typename Label = std::string>
class bar;
template <template<class...> class C, typename T, typename Label>
class bar<C<T>, Label> {
C<foo<T, Label>> A;
};
Demo.
|
69,575,585 | 69,575,679 | Should I delete variables if created them using "new" operator inside map::insert()? | I am writing scene manager which, among other things, contains a map of all objects, or rather pointers to them. I remember to delete my variables created using "new" and i tried doing it in my Scene deconstructor, but I got 0xC0000005 exit code and afaik it means that i tried to use memory that doesnt really exist anymore.
Here is my Scene class:
class Scene{
public:
Scene();
~Scene();
// other functions that I cut for question purposes
std::map<GLuint, Object*> view_layer;
Object AddObject(const std::string &title);
};
And I am creating new object in scene like this ("new Object" returns only pointer to newly created variable):
Object Scene::AddObject(const std::string &title) {
// other stuff again
view_layer.insert(std::make_pair(currentObjectID, new Object));
return *view_layer.find(currentObjectID)->second;
}
And i tried to delete it like this:
Scene::~Scene() {
for (auto const& [key, val] : view_layer)
{
if(val){
std::cout << "Deleting object...\n";
delete [] val;
}
}
};
But program crashes after this std::cout, right on delete [] val.
Val should be a reference to the pointer of my object, and delete [] needs pointer, so i guess that i have no syntax issue here.
My question is - Am I doing something wrong or I am just not supposed to delete this because somehow it deletes itself ?
Thanks for any kind of help!
| So..
As t.niese answered 0xC0000005 exit status in my code came from a difference between creating and deleting methods used.
When using new, you should delete it using delete
When using new[], you should use delete[]
|
69,575,909 | 69,576,105 | How to use lambda intead of std::bind in create_subscription method in ROS2 | I am creating a small euclidean clustering node for the point cloud, utilizing PCL's implementation of the KD tree.
Currently, my subscriber definition looks like this,
ClusteringNode::ClusteringNode(const rclcpp::NodeOptions &options)
: Node("clustering_node", options),
cloud_subscriber_{create_subscription<PointCloudMsg>(
"input_cloud", 10,
std::bind(&ClusteringNode::callback, this,
std::placeholders::_1))},
the definition of KD-tree method is inside callback method and is working perfectly,
Now just to improve it furthur, I want to use lambdas instead of the std::bind function here,
What should be the approach here?
| The std::bind() statement:
std::bind(&ClusteringNode::callback, this, std::placeholders::_1)
Would translate into a lambda like this:
[this](const auto msg){ callback(msg); }
Or, if the callback() has a non-void return value:
[this](const auto msg){ return callback(msg); }
|
69,575,926 | 69,576,197 | Does compiling with gcc flag -fno-exceptions reduce the size of the executable binary? | While reading the section about exception handling and the compiler flag -fno-exceptions in the gcc manual, I came across the following lines:
Exception handling overhead can be measured in the size of the
executable binary, and varies with the capabilities of the underlying
operating system and specific configuration of the C++ compiler. On
recent hardware with GNU system software of the same age, the combined
code and data size overhead for enabling exception handling is around
7%.
I tried to reproduce this overhead by compiling some simple C++ programs (without exception throwing code) using Ubuntu 20.04 and gcc 10.3.0 both with and without the -fno-exceptions flag, but could not observe any difference whatsoever regarding the size of the compiled binary executables.
So I came to the conclusion that the quoted sentence from the manual is referring only to the binary that is produced when recompiling libstdc++ files with -fno-exceptions because in this case, every occurence of try, catch and throw will be replaced by if ... else branches.
I am not entirely sure about this, so here are my questions:
a) User code being compiled with -fno-exceptions only prevents using the keywords try, catch and throw and does not generate a smaller binary by itself, right ?
b) User code being compiled with -fno-exceptions can still be exposed to exceptions being thrown from libstdc++ functions, if these have not been (re)compiled with -fno-exceptions, right ?
c) User code being compiled with -fexceptions (the default) will indeed produce a larger binary because of the generated frame unwind information, but only when exceptions are actually used, right ?
| It can reduce the size of the binary, and it often does for larger programs. However, it's not guaranteed to always do so.
a) User code being compiled with -fno-exceptions only prevents using the keywords try, catch and throw and does not generate a smaller binary by itself, right ?
Nope, it definitely has an impact on code generation. However, exceptions do not increase code size indiscriminately. There has to be exceptions possibly involved for frame unwind code to be generated. There also has to be something to do during unwinding (i.e non-trivial destructors). If one or the other is not present in a given function, then -fno-exceptions won't make a difference for that function.
For example, compiling the following will clearly show a smaller code size with -fno-exceptions.
#include <vector>
void foo(); // could potentially throw.
void bar() {
std::vector<int> v(12); // has non-trivial destructor.
foo();
}
see on godbolt
Notice how each of the following changes eliminates the exception handling code:
changing the declaration of foo() to void foo() noexcept;.
providing a non-throwing implementation of foo() in the same TU: void foo() {}
moving the construction of the vector to after foo() is called.
b) User code being compiled with -fno-exceptions can still be exposed to exceptions being thrown from libstdc++ functions, if these have not been (re)compiled with -fno-exceptions, right ?
Any exception thrown by libstdc++ that bubbles up into code compiled with -fno-exceptions will result in the program being immediately terminated. If that counts as "being exposed" to you, then yes.
However, keep in mind that a large portion of libstdc++ is implemented directly in headers, and your compiler flags are going to be applied to that portion of the library.
c) User code being compiled with -fexceptions (the default) will indeed produce a larger binary because of the generated frame unwind information, but only when exceptions are actually used, right ?
Close but not quite. The code will be emitted anywhere an exception might be thrown. This includes any call to a function without noexcept that is defined in a different TU than the one being compiled.
|
69,576,022 | 69,578,945 | How to instantiate an Octave classdef object in C++ and call its methods | I know how to call a function defined in an .m-file using the Octave interpreter and feval as shown in the Octave manual but not how to do something similar using Octave classes and their methods.
If I have a simple class defined in Octave using the classdef method such as
classdef TestClass < handle
properties
val
endproperties
methods
function obj = TestClass()
obj.val = 1;
endfunction
function obj = setval(obj, v)
obj.val = v;
endfunction
function showval(obj)
disp(obj.val);
endfunction
endmethods
endclassdef
If I then would would like to use my class in some C++ code, how would I go about doing that. In Octave it would be:
c = TestClass(); //create an instance of TestClass
c.setval(100); //use the objects methods
c.showval(); //display 100
Solution
Based on the answer below I'll present my solution here. The above octave code can be rewritten as
c = TestClass();
setval(c, 100);
showval(c);
which can be turned into this C++ code
#include <interpreter.h>
#include <parse.h>
int main()
{
octave::interpreter interpreter;
interpreter.execute();
octave_value_list arg;
octave_value c;
c = octave::feval("TestClass", arg, 1).xelem(0);
arg(0) = c;
arg(1) = 100;
octave::feval("setval", arg);
arg.clear();
arg(0) = c;
octave::feval("showval", arg);
return 0;
}
| If you already know how to call an Octave function from C++, then all you are missing is that a.b() is the same as b(a). Calling a method is just like calling a function, there is no distinction. Octave figures out which overload of the function to call based on the input arguments.
The bit of Octave code you posted,
c = TestClass();
c.setval(100);
c.showval();
can also be written as
c = TestClass();
setval(c, 100);
showval(c);
|
69,576,225 | 69,576,351 | C++ ostream parameters | I am building a project that solves a boggle board. The two functions I'm interested in at the moment are
void Boggle::SolveBoardHelper(bool printBoard, int row, int column, int rowMax, int columnMax,
ofstream& output, int numSteps, int steps[4][4], string currPath)
void Boggle::SolveBoard(bool printBoard, ostream &output) {
ofstream outputFile;
outputFile(output); // stuck here
string currPath; // used to track the current path on the board
for(int pos_x = 0; pos_x < BOARD_SIZE; pos_x++){
for(int pos_y = 0; pos_y < BOARD_SIZE; pos_y++)
SolveBoardHelper(print_or_not, pos_x, pos_y, BOARD_SIZE, BOARD_SIZE, outputFile, numSteps, visited, currPath);
}
}
My area of confusion is that when the user calls SolveBoard to solve a board, they have the option of passing "cout" or an output file into the ostream parameter. If the user decides to call the function and pass in an output file, say "output.txt", how do I account for this? How do I take the output file passed into the SolveBoard parameter by the user, and then plug that into the SolveBoardHelper function so that I can write to that file after the board has been solved?
My previous attempt included me just passing a predetermined output file into the parameter, but
I don't know what file the user will choose to output to:
void Boggle::SolveBoard(bool printBoard, ostream &output) {
string outputFile = "solve_output_test.txt"; // write to the already created solve_output_test.txt file
ofstream outFile(outputFile); // assign it to ofstream variable outFile
if(!outFile){
cout << "Error opening file" << endl; // file open check
}
string currPath;
for(int pos_x = 0; pos_x < BOARD_SIZE; pos_x++){
for(int pos_y = 0; pos_y < BOARD_SIZE; pos_y++)
SolveBoardHelper(print_or_not, pos_x, pos_y, BOARD_SIZE, BOARD_SIZE, outFile, numSteps, visited, currPath);
}
}
| void Boggle::SolveBoard(bool printBoard, ostream &output) {
// remove the two lines below and just use `output` in the rest of the function:
//ofstream outputFile;
//outputFile(output);
for(int pos_x = 0; pos_x < BOARD_SIZE; pos_x++) {
for(int pos_y = 0; pos_y < BOARD_SIZE; pos_y++)
SolveBoardHelper(print_or_not, pos_x, pos_y, BOARD_SIZE, BOARD_SIZE, output,
numSteps, visited, currPath);
}
}
Then call the function with
SolveBoard(the_bool, std::cout);
or
std::ofstream file("output.txt");
SolveBoard(the_bool, file);
You also need to redefine SolveBoardHelper to take an ostream instead:
void Boggle::SolveBoardHelper(bool printBoard, int row, int column, int rowMax,
int columnMax, ostream& output, int numSteps,
int steps[4][4], string currPath)
|
69,576,398 | 69,578,252 | BindingError: Passing raw pointer to smart pointer is illegal | Consider the following C++ code and corresponding Emscripten bindings.
class IBar {
void qux() = 0;
};
struct BarWrapper : public wrapper<IBar> {
void qux() override {
return call<>("qux");
}
}
EMSCRIPTEN_BINDINGS(IBar) {
class_<IBar>("IBar")
.smart_ptr<std::shared_ptr<IBar>>("IBar")
.function("qux", &IBar::qux)
.allow_subclass<BarWrapper>("BarWrapper");;
}
class Foo {
std::shared_ptr<IBar> getBar() const;
void setBar(std::shared_ptr<IBar> bar);
};
EMSCRIPTEN_BINDINGS(Foo) {
class_<Options>("Foo")
.constructor<>()
.property("bar", &Foo::getBar, &Foo::setBar);
}
In TypeScript, I have the following:
class Bar {
qux() {
}
}
const bar = new Module.Bar.implement(new Bar())
The issue here is that Foo::setBar takes a std::shared_ptr but Module.Bar.implement returns a raw pointer. That prevents me from passing bar to Foo::setBar.
Is anyone aware of how to convert a raw pointer to a shared pointer here? Alternatively, is anyone aware of a good workaround?
| I figured out a solution that doesn't return adding a method that accepts a raw pointer.
It works by expanding the bindings for IBar.
EMSCRIPTEN_BINDINGS(IBar) {
class_<IBar>("IBar")
.smart_ptr<std::shared_ptr<IBar>>("IBar")
.function("qux", &IBar::qux)
.allow_subclass<BarWrapper, std::shared_ptr<BarWrapper>>("BarWrapper", "BarWrapperSharedPtr");;
}
|
69,576,651 | 69,576,896 | Tell compiler not to execute destructor on my __thread variable | I specifically want no constructors and no destructors on one of my variables. It's defined as this
struct Dummy { ~Dummy() { assert(0); } };
__thread Dummy dumb;
The real code is zero initialized and grabs memory out of the thread local memory pool. The pool is destroyed at the end of main so this destructor tries to access a freed memory pool.
I can work around the problem but I wanted to do this in a clean way. 1) Can I tell the compiler to free my pool after all thread local (or global) variables? Or have it initialized before all thread local functions so it's cleaned up at the proper time? Or better yet 2) Not execute the cleanup at all? I could have sworn __thread doesn't allow constructors/destructors so I was surprised this even ran.
The stack trace shows __run_exit_handlers being the function that calls the destructor. It parents are exit, __libc_start_main and start. This occurs on both clang and gcc
| Before I get into the answer, anyone reading this should know that this is generally a very bad idea, and should be treated as a last resort. However, what the OP wants is feasible, so here it is:
Destructors are possibly the single most reliable thing in the C++ language. So if you want to prevent one from being executed, you'll have to manage the object's lifecycle and memory by yourself.
We could just new the Dummy object and never delete it, but that would leak heap memory, which is not desirable. Instead, we want to create, but never destroy, the Dummy object in the memory associated with the thread-local object itself.
For this, the way to go is std::aligned_storage and placement new:
struct Dummy { ~Dummy() { assert(0); } };
struct DummyWrapper {
DummyWrapper() {
// Create the dummy
dummy_ptr = new (&dummy_data) Dummy();
}
// Intentionally leave the destructor defaulted-out
~DummyWrapper() = default;
operator Dummy&() { return *dummy_ptr; }
std::aligned_storage_t<sizeof(Dummy), alignof(Dummy)> dummy_data;
Dummy* dummy_ptr;
};
__thread DummyWrapper dumb;
The DummyWrapper object will be constructed and destroyed, there's no going around that. However, the Dummy object is only ever created, and never destroyed, but the underlying memory management is still kept sane.
|
69,576,733 | 69,576,812 | Referring to template parameters to define types for function parameter | I would like to do something like this:
template <typename T, int Size>
struct config {
T field;
/* various other things */
}
template <typename C> // where C is a specific version of the 'config' object.
void func(C arg0, C::T arg1, std::array<int, C::Size> &arg2) {
int i = C::Size;
}
ie, can I choose the types my function parameters based on the full type of config?
I could achieve this by just listing out all the individual types:
template <typename T, int Size>
void func(config<T,Size> config, T arg1, std::array<int, Size> &arg2) { ... }
But my full use case is acquiring quite a large number of parameters, both compile-time and run-time, and I'd like to package them up into my config object and pass it around, without having to replicate many template definitions at dozens of function declarations. Is there a way to do this?
| You can of course add a type alias/static constexpr to config, but the only way to guarantee the first parameter of the function is instantiation of config, is the second alternative.
A solution using type alias/ static const:
template <class T, int N>
struct config
{
using FieldType = T;
static constexpr int Size = N;
FieldType field;
};
template <typename C>
void func(C arg0, typename C::FieldType arg1, std::array<int, C::Size> &arg2) {
int i = C::Size;
}
|
69,577,145 | 69,577,588 | Reference in container? | I'm having an issue with passing a string as reference to a lambda, when it is in a container. I guess it disappears (goes out of scope) when I call the init() function, but why? And then, why doesn't it disappear when I just pass it as a string reference?
#include <iostream>
#include <string>
struct Foo {
void init(int num, const std::string& txt)
{
this->num = num;
this->txt = txt;
}
int num;
std::string txt;
};
int main()
{
auto codegen1 = [](std::pair<int, const std::string&> package) -> Foo* {
auto foo = new Foo;
foo->init(package.first, package.second); //here string goes out of scope, exception
return foo;
};
auto codegen2 = [](int num, const std::string& txt) -> Foo* {
auto foo = new Foo;
foo->init(num, txt);
return foo;
};
auto foo = codegen1({3, "text"});
auto foo2 = codegen2(3, "text");
std::cout << foo->txt;
}
I know the way to go would be to use const std::pair<int, std::string>&, but I want to understand why this approach doesn't work.
| Part 1: This looks busted at a glance.
"text" is not a string, it's a literal that is being used to create a temporary std::string object, which is then used to initialize the std::pair. So you'd think it would make sense that the string, which is only needed transiently (i.e only until the std::pair is constructed), is gone by the time it is being referred to.
Part 2: But it shouldn't be busted.
However, temporaries that are created as part of an expression are supposed to be guaranteed to live until the end of the current "full-expression" (simplified: until the semicolon).
That's why the call to codegen2() works fine. A temporary std::string is created, and it stays alive until the call to codegen2() is complete.
Part 3: Yet it is busted, in this case.
So why does the string get destroyed prematurely in codegen1()'s case? The conversion from "text" to std::string does not happen as a sub-expression, but as part of a separate function being called with its own scope.
The constructor of std::pair that is being used here is:
// Initializes first with std::forward<U1>(x) and second with std::forward<U2>(y).
template< class U1 = T1, class U2 = T2 >
constexpr pair( U1&& x, U2&& y );
The constructor gets "text" as a parameter and the construction of the std::string is being done inside of std::pair's constructor, so the temporary variable created as part of that process gets cleaned up when we return from that constructor.
The funny thing is, if that constructor did not exist, std::pair's basic constructor: pair( const T1& x, const T2& y ); would handle this just fine. The implicit conversion to std::string would be done prior to invoking the constructor.
How do we fix this?
There's a few alternatives:
Force the conversion to happen at the right "level":
auto foo = codegen1({3, std::string("text")});
Effectively the same thing, but with a nicer syntax:
using namespace std::literals::string_literals;
auto foo = codegen1({3, "text"s});
Use a std::string_view, which removes the need for the conversion altogether:
auto codegen1 = [](std::pair<int, std::string_view> package) -> Foo* {
...
}
Though, in your case, since Foo will take ownership of the string, passing it by value and moving it around is clearly the way to go (I also took the liberty to clean up the code a bit):
struct Foo {
Foo(int num, std::string txt)
: num(num)
, txt(std::move(txt))
{}
int num;
std::string txt;
};
int main()
{
auto codegen1 = [](std::pair<int, std::string> package) {
return std::make_unique<Foo>(package.first, std::move(package.second));
};
auto foo = codegen1({3, "text"});
std::cout << foo->txt;
}
|
69,577,462 | 69,577,527 | Why doesn't constexpr function returning std::string doesn't compile when outside templated class? | Note: I am using gcc, but tested on godbolt.org and it also works on msvc, but not on clang
I accidentally discovered that the following simple function compiles while being in a templated class, but not as a free function. Could someone explain why?
Compiles OK:
template <typename T = void>
class A
{
public:
static constexpr std::string f()
{
return std::string();
}
}
Doesn't compile:
constexpr std::string f()
{
return std::string();
}
Throws error:
error: invalid return type ‘std::string’ {aka ‘std::__cxx11::basic_string<char>’} of ‘constexpr’ function ...
...
/usr/include/c++/9/bits/basic_string.h:77:11: note: ‘std::__cxx11::basic_string<char>’ is not literal because:
77 | class basic_string
| ^~~~~~~~~~~~
/usr/include/c++/9/bits/basic_string.h:77:11: note: ‘std::__cxx11::basic_string<char>’ has a non-trivial destructor
| std::string is supposed to be a literal type in C++20. However, it seems that GCC hasn't implemented this new feature yet, so it cannot accept std::string as the return type of a constexpr function.
However, when the constexpr function is part of a template, it doesn't exist as a function until it's instantiated. A class template is a blueprint for a class; it's not itself a class. When the class template is instantiated, then its set of members will come into being. So in your first example, what you have is a class template that will always produce ill-formed instantiations, because A<T>::f will always have an invalid return type. When this occurs, the program is "ill-formed, no diagnostic required", which means that the program is ill-formed, but the compiler is not required to tell you that the program is ill-formed. If the compiler accepts the program, the result of running the program is undefined.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.