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 |
|---|---|---|---|---|
71,432,328 | 71,432,342 | How to set global Clang flags? | I'm using Clang on MacOS. When I compile C++ with clang++, is there a way to specify -std=c++17 without writing it every time? Is there some sort of a global clang config file?
| alias c++="c++ -O2 -W -Wall -std=c++17"
You can add something like that to your bashrc or whatever shell you use.
Another thing that should work on MacOS, works on every other unix, would be to create a wrapper script in /usr/local/bin/. Assuming you have that in your $PATH. Otherwise the problem recurses to exetending your PATH.
% cat >> /usr/local/bin/c++ <<EOF
#!/bin/sh
/usr/bin/c++ -O2 -W -Wall -std=c++17 "$@"
EOF
% chmod a+x /usr/local/bin/c++
The cat creates the file and the chmod makes it executable by all. Use the text editor of your choice if you don't understand that cat command.
|
71,432,398 | 71,432,419 | What is causing this baffling compiler error with templates and inheritance? | It took quite a while to distill this down to a manageable size, but here's the code:
template<typename T = uint8_t> struct ArrayRef {
T* data;
size_t size;
size_t capacity;
ArrayRef<T>(T* d, size_t c, size_t size) : data(d), size(size), capacity(c) {}
void Add(T* buffer, size_t size) { }
};
struct ByteArray : ArrayRef<uint8_t> {
ByteArray(uint8_t* d, size_t c, size_t size) : ArrayRef<uint8_t>(d,c,size) {}
// If this function is removed, the test code can find the inherited Add function
template <typename T> void Add(T& item) { }
};
void Test() {
uint8_t ibuf[20];
ByteArray ba(ibuf, 20, 0);
uint8_t buf[5];
ba.Add(buf, sizeof(buf));
If this code is compiled as is (g++), I get the compiler error:
error: no matching function for call to 'ByteArray::Add(uint8_t [5], unsigned int)
But, as noted in the code, when the one function is removed, the code compiles fine and the Add function in the base class is found correctly. What exactly is going on here?
| When the name Add is found at the scope of class ByteArray, name lookup stops, the scope of class ArrayRef<uint8_t> won't be checked.
You can introduce ArrayRef<uint8_t>::Add into the scope of ByteArray, then it could be found and take part in overload resolution.
struct ByteArray : ArrayRef<uint8_t> {
ByteArray(uint8_t* d, size_t c, size_t size) : ArrayRef<uint8_t>(d,c,size) {}
// If this function is removed, the test code can find the inherited Add function
template <typename T> void Add(T& item) { }
using ArrayRef<uint8_t>::Add;
};
|
71,432,513 | 71,453,008 | Writing to a 3D Texture Using Framebuffers and Saving as Image | I'm trying to generate a 3D worley noise texture for some volumetric effects. I am simply generating a set of random points and for each fragment, I will find the closest point and get the distance between the fragment and the pixel. The distance is then used as the final color of the image. The result looks something like this in 2D:
This works very well when I generate a 2D texture. I start running into some issues when trying to generate a 3D texture.
Right now I attach each slice of the 3D texture as a color attachment and write to it using a shader. My Code is as follows:
Function to generate noise (Note: this code assumes that width, height and depth are all equal):
void WorleyGenerator::GenerateWorley3D(int numPoints, Texture3D* texture, PrimitiveShape* quad, unsigned int nativeWidth, unsigned int nativeHeight)
{
int resolution = texture->GetWidth();
glViewport(0, 0, resolution, resolution);
glDisable(GL_CULL_FACE);
frameBuffer->Bind();
shader3D->Bind();
shader3D->SetFloat("uResolution", resolution);
shader3D->SetInt("uNumWorleyPoints", numPoints); // Tell shader how many points we have
// Generate random points and pass them ot shader
for (int i = 0; i < numPoints; i++)
{
shader3D->SetFloat3("uPointData[" + std::to_string(i) + "]", glm::vec3(Utils::RandInt(0, resolution), Utils::RandInt(0, resolution), Utils::RandInt(0, resolution)));
}
// Render to each "slice" of the texture
for (int z = 0; z < resolution; z++)
{
shader3D->SetInt("uCurrentSlice", z);
glFramebufferTexture3D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_3D, texture->GetID(), 0, z);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
quad->Draw();
}
frameBuffer->Unbind();
glViewport(0, 0, nativeWidth, nativeHeight);
}
My fragment shader:
#version 420
in vec2 mTextureCoordinates;
out vec4 oColor;
uniform int uCurrentSlice;
uniform float uResolution;
uniform int uNumWorleyPoints;
uniform vec3 uPointData[256];
void main()
{
vec3 fragPos = vec3(gl_FragCoord.xy, uCurrentSlice) / uResolution; // Convert frag pos to range 0 - 1
// Find closest point's distance
float closestDist = 100000.0f;
// Get closest point for red channel
for (int i = 0; i < uNumWorleyPoints; i++)
{
vec3 p = uPointData[i] / uResolution; // Convert point to range 0 - 1
float dist = distance(fragPos, p);
if (dist < closestDist)
{
closestDist = dist;
}
}
oColor = vec4(closestDist, closestDist, closestDist, 1.0f);
}
Now to test my code, I will save each slice of the 3D texture to a BMP file:
void Utils::SaveTexture3DAsBMP(const std::string& savePath, Texture3D* texture)
{
unsigned int size = texture->GetWidth() * texture->GetHeight() * 4;
float* data = new float[size];
for (int z = 0; z < texture->GetDepth(); z++)
{
glGetTextureSubImage(texture->GetID(), 0, 0, 0, z, texture->GetWidth(), texture->GetHeight(), z, GL_RGBA16F, GL_FLOAT, size, data);
stbi_write_bmp((savePath + std::to_string(z) + ".bmp").c_str(), texture->GetWidth(), texture->GetHeight(), 4, data);
}
delete[] data;
}
The result of the saved images looks something like this:
Moreover, each slice is exactly the same which should never happen.
I suspect that I am either incorrectly writing to a slice, or my code to save the image is wrong.
Any help would be appreciated!
| My issue was not with the texture but rather with how I was saving the images. I changed my texture saving function from this:
void Utils::SaveTexture3DAsBMP(const std::string& savePath, Texture3D* texture)
{
unsigned int size = texture->GetWidth() * texture->GetHeight() * 4;
float* data = new float[size];
for (int z = 0; z < texture->GetDepth(); z++)
{
glGetTextureSubImage(texture->GetID(), 0, 0, 0, z, texture->GetWidth(), texture->GetHeight(), z, GL_RGBA16F, GL_FLOAT, size, data);
stbi_write_bmp((savePath + std::to_string(z) + ".bmp").c_str(), texture->GetWidth(), texture->GetHeight(), 4, data);
}
delete[] data;
}
To this:
void Utils::SaveTexture3DAsBMP(const std::string& savePath, Texture3D* texture)
{
unsigned int size = texture->GetWidth() * texture->GetHeight() * 4;
uint8_t* data = new uint8_t[size];
for (int z = 0; z < texture->GetDepth(); z++)
{
glGetTextureSubImage(texture->GetID(), 0, 0, 0, z, texture->GetWidth(), texture->GetHeight(), 1, GL_RGBA, GL_UNSIGNED_BYTE, size, data);
stbi_write_bmp((savePath + std::to_string(z) + ".bmp").c_str(), texture->GetWidth(), texture->GetHeight(), 4, data);
}
delete[] data;
}
|
71,432,656 | 71,432,722 | Where is the usage of struct with flexible array memeber defined in the C/C++ standards? | If I have code like this
struct s { int x; char b[]; };
int main() {
struct s s[10];
}
and I compile with "gcc -O2 -W -Wall -pedantic" then I get:
<source>:4:14: warning: invalid use of structure with flexible array member [-Wpedantic]
4 | struct s s[10];
| ^
And gcc is totally right. Structs with flexible array members can't work like that.
Where in the C/C++ standards is this defined?
| In C, it's §6.7.2.1, paragraph 3:
A structure or union shall not contain a member with incomplete or function type,… except that the last member of a structure with more than one named member may have incomplete array type; such a structure (and any union containing, possibly recursively, a member that is such a structure) shall not be a member of a structure or an element of an array.
As @phuclv points out in a comment, C++ doesn't have this feature.
|
71,432,796 | 71,432,850 | Why does the Quantlib::Error class allocate a std::string on the heap? | In a code review recently, I had some less than kind words for something I thought awful. It turns out that it was obviously inspired by the QuantLib::Error class, which looks like this:
//! Base error class
class Error : public std::exception {
public:
/*! The explicit use of this constructor is not advised.
Use the QL_FAIL macro instead.
*/
Error(const std::string& file,
long line,
const std::string& functionName,
const std::string& message = "");
#ifdef QL_PATCH_MSVC_2013
/*! the automatically generated destructor would
not have the throw specifier.
*/
~Error() throw() override {}
#endif
//! returns the error message.
const char* what() const QL_NOEXCEPT override;
private:
ext::shared_ptr<std::string> message_;
};
Why is the member variable ext::shared_ptr<std::string> and not just plain std::string? What reason could there be to heap-allocate the string object itself? (The QuantLib code base seems to heap-allocate just about everything just about always just about everywhere, and pulls in shared_ptr's to cope with that - a classic anti-pattern - but doing it here as well "just for consistency" strikes me as a bit much. Am I missing something?)
| This is following the behavior of standard library exception types.
They are supposed to be copyable without throwing exceptions, since throwing an exception during construction of an exception handler parameter would cause a call to std::terminate (and possibly in some other situations requiring a copy of the exception as well).
If std::string was used directly, copying the exception could cause for example a std::bad_alloc to be thrown. Using a reference-counted pointer instead avoids that.
|
71,432,992 | 71,433,112 | C++ - Compile and link multiple files | I have a project with the following structure:
Item.cpp
Item.h
main.cpp
Makefile
The following source code is in the Item.h file:
class Item {
public:
Item();
~Item();
};
The following source code is in the Item.cpp file:
#include <iostream>
#include "Item.h"
Item::Item() {
std::cout << "Item created..." << std::endl;
}
Item::~Item() {
std::cout << "Item destroyed..." << std::endl;
}
The following source code is the content of the main.cpp file:
#include "Item.h"
#include <iostream>
int main() {
std::cout << "Initialize program..." << std::endl;
Item item_1();
std::cout << "Hello world!" << std::endl;
return 0;
}
And finally, the following source code is the Makefile file:
CXX = g++
all: main item
$(CXX) -o sales.o main.o Item.o
main:
$(CXX) -c main.cpp
item:
$(CXX) -c Item.cpp
clean:
rm -rf *.o
When I run the make command and then I run the compiled code with the command ./sales.o, I get the following output:
Initialize program...
Hello world!
Why is the output of the constructor method of the class Item not printed in the console? I found in some web pages that you can compile the source codes in steps and then you can link it with the -o option when using g++ but it does not work in this case. How can I compile this source codes step by step and then link it in the Makefile?
| I'm surely you ignored this warning :
warning: empty parentheses were disambiguated as a function declaration [-Wvexing-parse]
#include "Item.h"
#include <iostream>
int main() {
std::cout << "Initialize program..." << std::endl;
Item item_1;
std::cout << "Hello world!" << std::endl;
return 0;
}
just remove parentheses it will be work
test : https://godbolt.org/z/KrdrhvsrW
|
71,432,993 | 71,434,511 | Why does delete[] work in one case but not another? | Could someone explain to me how delete[] works in the function below?
Specifically, arr = arrtemp; delete[] arrtemp; fails, but delete[] arr; arr = arrtemp works.
void AddElement(int *&arr, int &n, int pos, int val){
int *arrtemp = new int[n + 1];
for(int i = 0; i <= pos; i++){
*(arrtemp + i) = *(arr + i);
}
for(int i = pos; i < n; i++){
*(arrtemp + i + 1) = *(arr + i);
}
*(arrtemp + pos) = val;
n++;
//This works just fine
delete[] arr;
arr = arrtemp;
//But this one fails
//arr = arrtemp;
// delete[] arrtemp;
}
My thought was that I assign arr = arrtemp so that pointer arr now points to the added array, and I delete[] arrtemp should have no effect on arr, but it does @@ and I don't know why.
|
My thought was that I assign arr = arrtemp so that pointer arr now points to the added array, and I delete[] arrtemp should have no effect on arr,
Strictly speaking, this much is true. However, if you take this viewpoint, then strictly speaking, delete[] arrtemp should have no effect on arrtemp. Deleting the memory to which arrtemp points does not change arrtemp; it still points to the same memory location. What has changed is that accessing that memory is no longer valid.
but it does
Strictly speaking, this is false. Deleting the memory to which arrtemp points has no effect on arr. And that likely accounts for the symptoms you are seeing. There is no effect on arr, so arr still points to the same memory as before the deletion, to the same memory to which arrtemp points, to the memory that is no longer valid to access because it has been deleted.
Before the deletion:
-----------
| arr |---\
----------- |
| --------------------
same address |--->| allocated memory | valid to access
| --------------------
----------- |
| arrtemp |---/
-----------
After the deletion:
-----------
| arr |---\
----------- |
| ~~~~~~~~~~~~~~~~~~~~
same address |--->( deleted memory ) invalid to access
| ~~~~~~~~~~~~~~~~~~~~
----------- |
| arrtemp |---/
-----------
There is no change to arr (the pointer), but there is a change to *arr (the pointed-to object). This distinction is important. When arr == arrtemp, then deleting *arrtemp also deletes *arr. The situation is not merely that *arr is equivalent to *arrtemp, but that *arr is *arrtemp. Two names for the same object. Calling delete[] arrtemp directs the computer to delete the array (starting at) *arrtemp, a.k.a. *arr in your situation. Accessing that array after the deletion is invalid, regardless of which name you use to access the array.
|
71,432,999 | 71,435,405 | nlohmann json parsing key and value to a class | I have the following data file
{
"France": {
"capital": "paris",
"highpoint": "20",
},
"Germany": {
"size": "20",
"population": "5000"
}
}
I am using nlohmann/json to parse it
I need to parse it into a country class
country.h
class Country {
public:
friend void to_json(json &j , const Country &c);
friend void from_json(const json &j , Country &c);
private:
std::string _name;
std::map _detail;
to_json and from_json implementation
to_json(json &j, const Country &c) {
j = json{{c._name, c._detail}};
void from_json(const json& j, Item& cat){
auto c = j.get<std::map<std::string, std::map<std::string, std::string>>>();
cat._id = c.begin()->first;
cat._entry = c.begin()->second;
when i try to get the country from the json it does not work like this
std::ifstream in("pretty.json");
json j = json::parse(in);
Country myCountry = j.get<Country>();
I have looked at the documentation the only i see to create the from_json is by knowing the key before hand see doc
j.at("the_key_name").get_to(country._name);
is there a way i could parse it without knowing the key ? in the from_json method ?
| I think you need to customise to/from JSON for a vector of Country instead of the individual objects.
You need to parse the outer object in the JSON file and add the name to each of the objects before parsing the inner map values.
#include <map>
#include <string>
#include "nlohmann/json.hpp"
#include <sstream>
#include <iostream>
using nlohmann::json;
class Country {
public:
friend void to_json(json& j, const std::vector<Country>& value);
friend void from_json(const json& j, std::vector<Country>& value);
private:
std::string _name;
std::map<std::string, std::string> _detail;
};
void to_json(json& j, const std::vector<Country>& value)
{
for (auto& c : value)
{
j[c._name] = c._detail;
}
}
void from_json(const json& j, std::vector<Country>& value)
{
for (auto& entry : j.items())
{
Country c;
c._name = entry.key();
c._detail = entry.value().get<std::map<std::string, std::string>>();
value.push_back(c);
}
}
int main()
{
try
{
std::stringstream in(R"({
"France": {
"capital": "paris",
"highpoint": "20"
},
"Germany": {
"size": "20",
"population": "5000"
}
})");
json j = json::parse(in);
std::vector<Country> myCountry = j.get<std::vector<Country>>();
json out = myCountry;
std::cout << out.dump(2);
}
catch (std::exception& ex)
{
std::cout << ex.what() << "\n";
}
}
Note that the JSON you gave in the question was not valid JSON.
Try to avoid the use of friend functions, it'd be better to add getters and setters and a constructor to the class instead.
|
71,433,130 | 71,433,344 | Why does template not discard the co_return? | I'd like to make a function with both sync and coroutine version, without using template specialization, i.e. with an if constexpr.
This is the function I wrote:
template <Async _a>
AsyncResult<int, _a> func(int a) {
if constexpr (_a == Async::Disable)
return a;
else
co_return a;
}
But when I instantiate the true branch it gives an error
auto a = func<Async::Disable>(1); // compiler error
auto b = func<Async::Enable>(2); // ok
error: unable to find the promise type for this coroutine
Why is this not working?
Full code with an implementation of the promise type
| The standard explicitly says this is not possible. As per Note 1 in stmt.return.coroutine#1
... A coroutine shall not enclose a return statement ([stmt.return]).
[Note 1: For this determination, it is irrelevant whether the return statement is enclosed by a discarded statement ([stmt.if]). — end note]
So you won't be able to return from a coroutine even if it's in a discarded statement. You can specialize the function template instead of using if constexpr.
template <Async _a>
AsyncResult<int, _a> func(int a)
{
co_return a;
}
template <>
AsyncResult<int, Async::Disable> func<Async::Disable>(int a)
{
return a;
}
Here's a demo.
|
71,433,398 | 71,434,040 | How to improve my custom unique_ptr class? I want to realize that derived class can cast to base class | I realize a unique_ptr class by myself as below, and use it to manage another class:
namespace mcj {
template <typename CallbackT>
class unique_ptr {
public:
unique_ptr(CallbackT* ptr = nullptr) : ptr_(ptr) {
std::cout << "unique_ptr normal constructor" << std::endl;
}
unique_ptr(unique_ptr<CallbackT>&& ptr) {
if (ptr_) {
delete ptr_;
ptr_ = nullptr;
}
ptr_ = ptr.release();
std::cout << "unique_ptr move constructor(unique_ptr<CallbackT>&& ptr)"
<< std::endl;
}
unique_ptr<CallbackT>& operator=(unique_ptr<CallbackT>&& ptr) {
if (ptr_) {
delete ptr_;
ptr_ = nullptr;
}
ptr_ = ptr.release();
std::cout << "unique_ptr move operation(=)" << std::endl;
return *this;
}
unique_ptr(const unique_ptr<CallbackT>& other) = delete;
unique_ptr<CallbackT>& operator=(const unique_ptr<CallbackT>& other) = delete;
~unique_ptr() {
delete ptr_;
ptr_ = nullptr;
}
CallbackT& operator*() { return *ptr_; }
CallbackT* operator->() { return ptr_; }
CallbackT* get() const { return ptr_; };
CallbackT* release() {
if (ptr_) {
CallbackT* temp = ptr_;
ptr_ = nullptr;
return temp;
}
return ptr_;
}
private:
CallbackT* ptr_;
};
} // namespace mcj
I call mcj::unique_ptr like this, A is base base class and B is derived class:
mcj::unique_ptr<A> CastToBase() {
return mcj::unique_ptr<B>(new B);
}
mcj::unique_ptr<A> h = CastToBase();
But an error occurs:
/Users/chaojie.mo/Documents/test/test/main.cpp:42:10: error: no viable
conversion from returned value of type 'unique_ptr' to function
return type 'unique_ptr' return mcj::unique_ptr(new B);
^~~~~~~~~~~~~~~~~~~~~~~~~ /Users/chaojie.mo/Documents/test/src/callback_utils.h:11:3: note:
candidate constructor not viable: no known conversion from
'mcj::unique_ptr' to 'A ' for 1st argument unique_ptr(CallbackT
ptr = nullptr) : ptr_(ptr) { ^
/Users/chaojie.mo/Documents/test/src/callback_utils.h:15:3: note:
candidate constructor not viable: no known conversion from
'mcj::unique_ptr' to 'unique_ptr &&' for 1st argument
unique_ptr(unique_ptr&& ptr) { ^
/Users/chaojie.mo/Documents/test/src/callback_utils.h:35:3: note:
candidate constructor not viable: no known conversion from
'mcj::unique_ptr' to 'const unique_ptr &' for 1st argument
unique_ptr(const unique_ptr& other) = delete;
Can someone tell me how to improve mcj::unique_ptr to support that a derived class can cast to a base class?
| foo<B> is not a subclass of foo<B> in c++. Google 'contravariance and covariance in c++ smart pointers',
You will have to extract the pointer cast it and create a new unique_ptr to return
|
71,434,180 | 71,434,322 | When object is a argument of function, why does function use copy constructor? | I'm studying about copy constructors now. I learned that copy constructor is called when we make a object with already made object. And I heard that When we use object as a argument in function, copy constructor is called.
I want to know what happens inside function. How can function knows that function have to use copy constructor?
I think inside function, the passed argument is assigned to function parameter so that copy constructor is called.
|
I think inside function, the passed argument is assigned to function parameter
No. The arguments are essentially local variables of the called function, except they are created by the caller before the execution goes into the function. The function does not even know how they were constructed.
why does function use copy constructor?
So this assumption is wrong, the function does not use copy constructor on its arguments. The caller does (if argument is a variable and passed by value, so copy needs to be made).
|
71,434,475 | 71,434,540 | How to use a concept for STL containers? | Based on this old stack overflow question How do you define a C++ concept for the standard library containers?
I see that it's possible to define a concept for STL containers. However, I am unsure how to actually apply the concept to anything, because it requires 2 containers, container a and container b.
For example, taking the signature of the most upvoted answer
template <class ContainerType>
concept Container = requires(ContainerType a, const ContainerType b)
I've only seen concepts used with just 1 requirement argument, like so
//source: https://en.cppreference.com/w/cpp/language/constraints
template<typename T>
concept Hashable = requires(T a)
{
{ std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;
};
struct meow {};
// Constrained C++20 function template:
template<Hashable T>
void f(T) {}
//
// Alternative ways to apply the same constraint:
// template<typename T>
// requires Hashable<T>
// void f(T) {}
//
// template<typename T>
// void f(T) requires Hashable<T> {}
int main()
{
using std::operator""s;
f("abc"s); // OK, std::string satisfies Hashable
// f(meow{}); // Error: meow does not satisfy Hashable
}
| The definition of this concept is in fact
template <class ContainerType>
concept Container = /* */;
which only constrains one type ContainerType, so the function that applies this concept would be
template <Container C>
void f(C& c);
|
71,434,630 | 71,436,706 | What does this mean in gdb after executing the last line of a function? | Line 31 is the last line in this C++ function. After stepping over it, this strange number 0x00007ffe1fc6b36b is printed, and it starts walking back up the function, going back to line 30. I imagine it is calling destructors now. I'm just curious what the strange number means.
31 _sock->bind(addr);
(gdb) n
0x00007ffe1fc6b36b 30 _sock = unique_ptr<zmq::socket_t>(new zmq::socket_t(_ctx,zmq::socket_type::req));
| If the actual $pc value does not match the start of a line (according to the line table within the debug information), then GDB will print the $pc before printing the line number, and source line.
That's what's going on here. For line 31 GDB stopped at the exact address for the start of line 31, and so no address was printed.
For the line 30 output, which, like you said, is almost certainly the destructor call, the address we are now at 0x00007ffe1fc6b36b is associated with line 30, but is not the start of that line, and so, GDB prints the address.
The important thing to understand here, is that when GDB prints something like:
31 _sock->bind(addr);
No part of that line has yet been executed, while when GDB prints:
0x00007ffe1fc6b36b 30 _sock = unique_ptr<zmq::socket_t>(new zmq::socket_t(_ctx,zmq::socket_type::req));
then that line is part way through being executed, so your program will be in some weird half way state; in this case the object has been constructed, but not yet destructed.
|
71,434,795 | 71,434,866 | Integer literal as parameters of function declaration in cpp | I'm almost familiar with c and c++ programming. Today I was searching about function declaration when I suddenly came across a strange syntax in c++ language.
I wrote below code:
#include <iostream>
using namespace std;
int foo('3');
int bar(3);
int main(){
}
I've never seen defining the literals as function parameters! So I expected to get compile error when I compile this program:
$ g++ file.cpp
But it compiled without any problem!
So I'm curious to know what's the meaning and usage of int foo('3'); and int bar(3); lines?
| It means int foo = '3'; and int bar = 3; respectively.
But it's not exactly equivalent, e.g. with classes = doesn't permit explicit constructors.
|
71,435,269 | 71,435,414 | why type name is not allowed? | I want that when passing a certain enumeration property, the corresponding operator with type checking is output, here is a simple code example
#include <iostream>
#include <typeinfo>
//#include <memory>
enum MessageType : uint16_t
{
Display,
Warning,
Error
};
#define MESSAGE(_MessageType, _Text)\
if((_MessageType == Display) && (typeid(_MessageType).name() == MessageType))\
{\
std::cout<<"Display: "<<_Text;\
}\
else if((_MessageType == Warning) && (typeid(_MessageType).name() == MessageType))\
{\
std::cout<<"Warning: "<<_Text;\
}\
else if ((_MessageType == Warning) && (typeid(_MessageType).name() == MessageType))\
{\
std::cout<<"Error: "<<_Text;\
}\
else\
return
int main()
{
MESSAGE(Display, "Text!"); // type name is not allowed
return 0;
}
| std::type_info::name returns a c-string. MessageType is not a string, its the name of a type. You can compare the string returned from typeid(_MessageType).name() to the string returned from typeid(MessageType).name().
However, identifiers starting with leading _ followed by capital letter are reseved. If you use them your code has undefined behavior. Moreover main is not void you must return an int.
And last but not least, you don't need typeid when you can use constexpr if and std::is_same. A simple function instead of macro would also make it much easier to get a compiler error when the type does not match. Currently your check for the right type is made at runtime. I see no reason to use a macro here, the same could be achieved without one.
|
71,435,595 | 71,436,077 | C++: average of vector of structs | My struct is a 2D coordinate:
template<typename T>
struct coordinate {
std::pair<T, T> coords;
coordinate() : coords({0, 0}) {}
const T x() const { return coords.first; }
const T y() const { return coords.second; }
// functions to set and manipulate x and y
};
I have a std::vector<coordinate<double>> vec and would like to get averages of x and of y coordinates across the vector.
My way is (please don't judge)
double x_ = 0.;
double y_ = 0.;
for (auto v : vec) {
x_ += v.x();
y_ += v.y();
}
x_ /= vec.size();
y_ /= vec.size();
I assume there is a more suitable approach? I try to go for std::accumulate, but don't know how to access the struct members in std::accumulate.
I still struggle with C++ so some explanation to your approach would be great.
| Like I said, if you want to do arithmetic operations on your type, you likely want to overload the operators. Thus you can do
#include <numeric>
#include <vector>
template<typename T>
struct coordinate {
std::pair<T, T> coords;
coordinate() : coords({0, 0}) {}
coordinate(T x,T y) : coords(x,y) {}
T x() const { return coords.first; }
T y() const { return coords.second; }
coordinate& operator+=(coordinate const& other){
coords.first += other.coords.first;
coords.second += other.coords.second;
return *this;
}
template<typename D>
coordinate& operator/=(D divider){
coords.first /= divider;
coords.second /= divider;
return *this;
}
};
template<typename T>
coordinate<T> operator+(coordinate<T> lhs, coordinate<T> const& rhs){
return lhs += rhs;
}
template<typename T, typename D>
coordinate<T> operator/(coordinate<T> lhs, D rhs){
return lhs /= rhs;
}
template<typename T>
coordinate<T> average(std::vector<coordinate<T>> const& vec){
if (vec.empty()){
return coordinate<T>{};
}
return std::accumulate(cbegin(vec), cend(vec), coordinate<T>{}) / vec.size();
}
int main()
{
std::vector<coordinate<double>> vec{{1,1},{2,0}};
auto avg = average(vec);
}
|
71,436,069 | 71,443,720 | Writing and reading ADTF3 Files | I am using ADTF Libraries to write a structure data. I need to verify whether the data is being written properly. How can i do this?
|
I am assuming you are writing structured data to a .dat/.adtfdat file. In that case, you can always convert a .dat/.adtfdat file into a csv to verify. See examples on how to do so.
If you have access to MATLAB, then the easiest way would be using a simple function in MATLAB : adtffilereader
Alternatively, there are these tools that help in extracting data out of a dat file.
|
71,436,279 | 71,436,395 | convert uint_8 ascii to string | I am sending a string from RaspberryPi to ESP32 via BT.I am getting an ascii values one per line. How to convert it into a whole one String? I tried as follow but I get an error while running the method printReceivedMEssage(buffer):
invalid conversion from 'uint8_t {aka unsigned char}' to 'uint8_t* {aka unsigned char*}' [-fpermissive]
uint8_t buffer;
void printReceivedMessage(const uint8_t* buf) {
char string_var[100];
size_t bufflen = sizeof(buf);
for (int i = 0; i < bufflen; ++i) {
Serial.println(static_cast<char>(buf[i]));
}
memcpy( string_var, buf, bufflen );
string_var[bufflen] = '\0'; // 'str' is now a string
Serial.print("string_var=");
Serial.println(string_var);
}
void loop()
{
buffer = (char)SerialBT.read();
Serial.println(buffer); // THIS SHOWS AN ASCII VALUES ONE PER LINE
printReceivedMessage(buffer); // ERROR
delay(1000);
}
| One error that should be fixed is the incorrect sizeof(). The code is getting the size of a pointer, which in C and C++ does simply that (you will get the value 4 for 32-bit pointers for example), but doesn't return the size of any "contents" being pointed to. In your case, where the buffer contains a null-terminated string, you can use strlen()
size_t bufflen = strlen(buf);
To remove the compiler error you need to pass a byte array to printReceivedMessage(). For example:
uint8_t buffer[200];
Also, you could print the buffer in one call with Serial.println(a_string), but then you need to read a whole string with SerialBT.readString().
The byte array seems to be an unnecessary intermediary. Just read a String over BT, and print it, as in the post I linked to.
Serial.println(SerialBT.readString());
|
71,436,332 | 71,441,824 | Converting from std::chrono:: to 32 bit seconds and nanoseconds? | This could be the inverse of Converting from struct timespec to std::chrono::?
I am getting my time as
const std::Chrono::CRealTimeClock::time_point RealTimeClockTime = std::Chrono::CRealTimeClock::now();
and I have to convert it to a struct timespec.
Actually, I don't, if there is an altrerntive; what I have to do is get the number of seconds since the epoch and the number of nanoseconds since the last last second.
I chose struct timespec becuase
struct timespec
{
time_t tv_sec; // Seconds - >= 0
long tv_nsec; // Nanoseconds - [0, 999999999]
};
The catch is that I need to shoehorn the seconds and nonseconds into uint32_t.
I am aware theat there is a danger of loss of precision, but reckon that we don't care too much about the nanoseconds while the year 208 problem gives me cause for concern.
However, I have to bang out some code now and we can update it later if necessary. The code has to meet another manufacturer's specification and it is likely to take weeks or months to get this problem resolved and use uint64_t.
So, how can I, right now, obtain 32 bit values of second and nanosecond from std::Chrono::CRealTimeClock::now()?
| I'm going to ignore std::Chrono::CRealTimeClock::now() and just pretend you wrote std::chrono::system_clock::now(). Hopefully that will give you the tools to deal with whatever clock you actually have.
Assume:
#include <cstdint>
struct my_timespec
{
std::uint32_t tv_sec; // Seconds - >= 0
std::uint32_t tv_nsec; // Nanoseconds - [0, 999999999]
};
Now you can write:
#include <chrono>
my_timespec
now()
{
using namespace std;
using namespace std::chrono;
auto tp = system_clock::now();
auto tp_sec = time_point_cast<seconds>(tp);
nanoseconds ns = tp - tp_sec;
return {static_cast<uint32_t>(tp_sec.time_since_epoch().count()),
static_cast<uint32_t>(ns.count())};
}
Explanation:
I've used function-local using directives to reduce code verbosity and increase readability. If you prefer you can use using declarations instead to bring individual names into scope, or you can explicitly qualify everything.
The first job is to get now() from whatever clock you're using.
Next use std::chrono::time_point_cast to truncate the precision of tp to seconds precision. One important note is that time_point_cast truncates towards zero. So this code assumes that now() is after the clock's epoch and returns a non-negative time_point. If this is not the case, then you should use C++17's floor instead. floor always truncates towards negative infinity. I chose time_point_cast over floor only because of the [c++14] tag on the question.
The expression tp - tp_sec is a std::chrono::duration representing the time duration since the last integral second. This duration is implicitly converted to have units of nanoseconds. This implicit conversion is typically fine as all implementations of system_clock::duration have units that are either nanoseconds or coarser (and thus implicitly convertible to) nanoseconds. If your clock tracks units of picoseconds (for example), then you will need a duration_cast<nanoseconds>(tp - tp_sec) here to truncate picoseconds to nanoseconds precision.
Now you have the {seconds, nanoseconds} information in {tp_sec, ns}. It's just that they are still in std::chrono types and not uint32_t as desired. You can extract the internal integral values with the member functions .time_since_epoch() and .count(), and then static_cast those resultant integral types to uint32_t. The final static_cast are optional as integral conversions can be made implicitly. However their use is considered good style.
|
71,436,670 | 71,436,903 | I want to get the encoded string as output . But not able to | Input:
101101110
1101
Expected Ouput:
000000000011
My output:
It just keeps on taking the input.and not showing any output.
Please help me . what is wrong with my code. Any help would be aprreciated.I have given the names of the variables such that its easy to understand.This code is only for the senders side.
#include <iostream>
using namespace std;
int main()
{
string input;
string polynomial;
string encoded="";
cin>>input;
cin>>polynomial;
int input_len=input.length();
int poly_len=polynomial.length();
encoded=encoded+input;
for(int i=1;i<=poly_len-1;i++){
encoded=encoded+'0';
}
for(int i=0;i<=encoded.length()-poly_len;){
for(int j=0;j<poly_len;j++){
if(encoded[i+j]==polynomial[j]){
encoded[i+j]=='0';
}
else{
encoded[i+j]=='1';
}
}
while(i<encoded.length() && encoded[i]!='1'){
i++;
}
}
cout<<encoded;
return 0;
}
| Look at these lines properly:
if (encoded[i + j] == polynomial[j]) {
encoded[i + j] == '0'; // Line 1
}
else {
encoded[i + j] == '1'; // Line 2
}
See? You are using == while you should be using =. == is a comparison operator which returns a boolean (true/false). It does not assign values. So to fix your problem, replace the above lines with:
if (encoded[i + j] == polynomial[j]) {
encoded[i + j] = '0'; // Replaced == with =
}
else {
encoded[i + j] = '1'; // Replaced == with =
}
This should fix your problem.
|
71,436,877 | 71,437,040 | Perfect forwarding c++ | Is this correct way to use std::forward?
struct Command {
public:
int32_t uniqueID{0};
public:
Command() = default;
template<typename T>
Command(T&& _uniqueID) : uniqueID(std::forward<int32_t>(_uniqueID)) //
{
//
}
};
Or I should use this line?
Command(T&& _uniqueID) : uniqueID(std::forward<T>(_uniqueID))
|
Is this correct way to use std::forward?
No, there's no point to use std::forward here. Moving a primitive type is same as copying it. I recommend following:
Command(std::int32_t _uniqueID) : uniqueID(_uniqueID) {}
Or alternatively, let the class be an aggregate:
struct Command {
std::int32_t uniqueID{0};
};
|
71,437,288 | 71,441,827 | Why GetDeviceToAbsoluteTrackingPose(...) doesn't return the HMD position in OpenVR? | I'm trying to implement a basic OpenVR C++ app. This is my code:
#include <iostream>
#include <thread>
#include <chrono>
#include <openvr.h>
int main()
{
vr::EVRInitError eError = vr::VRInitError_None;
vr::IVRSystem * pvr = vr::VR_Init(&eError, vr::VRApplication_Utility);
std::cout << "Error code: " << eError << std::endl;
std::cout << "Is HMD present? " << vr::VR_IsHmdPresent() << std::endl;
std::cout << "Is VR runtime installed? " << vr::VR_IsRuntimeInstalled() << std::endl;
for (uint32_t deviceId = 0; deviceId < vr::k_unMaxTrackedDeviceCount; deviceId++)
{
vr::TrackedDevicePose_t trackedDevicePose;
vr::VRControllerState_t controllerState;
vr::ETrackedDeviceClass deviceClass = pvr->GetTrackedDeviceClass(deviceId);
if (!pvr->IsTrackedDeviceConnected(deviceId))
{
//std::cout << "Device ID " << deviceId << " is not connected." << std::endl;
continue;
}
switch (deviceClass)
{
case vr::ETrackedDeviceClass::TrackedDeviceClass_HMD:
std::cout << "HMD ID: " << deviceId << std::endl;
//for (int i = 0; i < 100; ++i)
{
pvr->GetDeviceToAbsoluteTrackingPose(vr::TrackingUniverseStanding, 0, &trackedDevicePose, deviceId);
//pvr->GetControllerStateWithPose(vr::TrackingUniverseStanding, deviceId, &controllerState,
// sizeof(controllerState), &trackedDevicePose);
vr::HmdMatrix34_t & m34 = trackedDevicePose.mDeviceToAbsoluteTracking;
std::cout << m34.m[0][3] << " " << m34.m[1][3] << " " << m34.m[2][3] << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
break;
default:
break;
}
}
vr::VR_Shutdown();
return 0;
}
The outputs are:
Error code: 0
Is HMD present? 1
Is VR runtime installed? 1
HMD ID: 0
-1.07374e+08 -1.07374e+08 -1.07374e+08
The last output doesn't change, even if I run this for a minute or more and moving my headset (HTC Vive).
I've tried to get the controller position with an other case:
case vr::ETrackedDeviceClass::TrackedDeviceClass_Controller:
std::cout << "Controller ID: " << deviceId << std::endl;
//for (int i = 0; i < 100; ++i)
{
pvr->GetControllerStateWithPose(vr::TrackingUniverseStanding, deviceId, &controllerState,
sizeof(controllerState), &trackedDevicePose);
vr::HmdMatrix34_t & m34 = trackedDevicePose.mDeviceToAbsoluteTracking;
std::cout << m34.m[0][3] << " " << m34.m[1][3] << " " << m34.m[2][3] << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
break;
And it outputs
Controller ID: 1
-1.07374e+08 -1.07374e+08 -1.07374e+08
When the headset or the controller is turned off, there is no output from them, so something is working but I can't figure out what's wrong.
I'm using OpenVR SDK 1.16.8
Printing out the whole matrix also gives me this weird result:
std::cout << m34.m[0][0] << " " << m34.m[1][0] << " " << m34.m[2][0] << std::endl;
std::cout << m34.m[0][1] << " " << m34.m[1][1] << " " << m34.m[2][1] << std::endl;
std::cout << m34.m[0][2] << " " << m34.m[1][2] << " " << m34.m[2][2] << std::endl;
std::cout << m34.m[0][3] << " " << m34.m[1][3] << " " << m34.m[2][3] << std::endl;
-1.07374e+08 -1.07374e+08 -1.07374e+08
-1.07374e+08 -1.07374e+08 -1.07374e+08
-1.07374e+08 -1.07374e+08 -1.07374e+08
-1.07374e+08 -1.07374e+08 -1.07374e+08
| Okay, I've found the solution.
pvr->GetDeviceToAbsoluteTrackingPose(vr::TrackingUniverseStanding, 0, &trackedDevicePose, 1);
The last parameter should be 1 (in my case). It's an array count parameter, not the device ID.
|
71,437,422 | 71,440,328 | ambiguity of overloaded function taking constant Eigen argument | I've designed a class with two overloaded functions taking Eigen data structures of different sizes.
The code compiles as long as I'm passing lvalues but if I pass an rvalue I get a compiler error ambiguity because both return the same ConstantReturnType.
Here is a MWE:
#include <iostream>
#include <Eigen/Geometry>
using namespace std;
using namespace Eigen;
class MyOverloadAmbiguity {
public:
void ambiguousOverload(const Eigen::Vector3d& v) {
std::cout << "I'm taking a Vector3d\n";
}
void ambiguousOverload(const Eigen::Vector4d& v){
std::cout << "I'm taking a Vector4d\n";
}
};
int main()
{
MyOverloadAmbiguity moa;
Eigen::Vector3d v3;
moa.ambiguousOverload(v3); // <--- this works
moa.ambiguousOverload(Eigen::Vector4d::Zero()); // <--- this doesn't
return 0;
}
main.cpp:26: error: call of overloaded ‘ambiguousOverload(const ConstantReturnType)’ is ambiguous
26 | moa.ambiguousOverload(Eigen::Vector4d::Zero());
| ^
main.cpp:10:8: note: candidate: ‘void MyOverloadAmbiguity::ambiguousOverload(const Vector3d&)’
10 | void ambiguousOverload(const Eigen::Vector3d& v) {
| ^~~~~~~~~~~~~~~~~
main.cpp:13:8: note: candidate: ‘void MyOverloadAmbiguity::ambiguousOverload(const Vector4d&)’
13 | void ambiguousOverload(const Eigen::Vector4d& v){
| ^~~~~~~~~~~~~~~~~
Is there a way to avoid this without explicitly changing the function names or add extra arguments just to avoid the ambiguity?
| Your example does not work because the return type of Zero() is not a matrix, but an Eigen expression.
Thus, one way of achieving what you want with minimal changes is to use explicit matrix evaluation:
moa.ambiguousOverload(Eigen::Vector4d::Zero().eval());
You may also want to consider writing functions taking Eigen expressions as parameters (rather than explicit matrices), as an alternative solution.
|
71,437,485 | 71,437,826 | Detect if a vector is a palindrome in C++ | I set myself a challenge of trying to make a program that detects if a given vector is a palindrome. Here is the code:
#include <iostream>
#include <vector>
bool isPalindromeArray(std::vector<int>& nums) {
float size = nums.size()/2;
int k = 0;
if(size = int(size)) {
for(int i = 0; i < size; i++) {
if(nums[i] == nums[nums.size() - i]) {
k++;
if(k == size) {
return true;
}
}
}
} else {
for(int i = 0; i < int(size) - 1 ; i++) {
if(nums[i] == nums[(int(size) - 1) - i]) {
k++;
if(k == int(size) - 1) {
return true;
}
}
}
}
return false;
}
int main() {
std::vector<int> arr;
arr.push_back(1);
arr.push_back(2);
arr.push_back(3);
arr.push_back(2);
arr.push_back(1);
if(isPalindromeArray(arr)) {
std::cout << "My Code Works";
}
}
When I run the code, it returns false no matter if the vector has an odd or even number of values. I have tried various troubleshooting steps but I can't seem to make it work.
(MinGW64, Windows 10, VS Code)
| It is highly recommended if you learn how to use algorithms delivered by standard library:
template <typename T>
bool is_palindrome(const T& container)
{
return std::equal(std::begin(container),
std::begin(container) + std::size(container) / 2,
std::rbegin(container));
}
Live test
|
71,437,697 | 71,437,812 | CMake MSBUILD : error MSB1009: Project file does not exist | I need to build my CMake based project under MSVC 2013 and MSVC 2019.
With MSVC 2019 using Ninja generator I build it successfully with following commands:
cmake -S . -B build -GNinja "-DCMAKE_BUILD_TYPE:STRING=Release"
cmake --build build --target all
On MSVC 2013 I have no Ninja available, so I tried the following:
cmake -S . -B build -DCMAKE_BUILD_TYPE:STRING=Release
cmake --build build --target all
Anyway I am getting following error and nothing is built:
MSBUILD : error MSB1009: Project file does not exist.
Switch: all.vcxproj
Any idea how to build it without ninja? (I cannot install it, since I am building it on a build server.)
| In contrast to other generators (like Makefiles or Ninja) CMake does not generate an all target for Visual Studio solution but an ALL_BUILD target.
So cmake --build build --target ALL_BUILD --config Release should succeed.
|
71,439,116 | 71,439,309 | array class member, with dynamically changeable length during runtime | I am trying to make a network application. Its class blueprint is roughly like this-
class Node
{
public:
// member functions
private:
int nodeID;
// other members
};
class NodeNetwork
{
public:
// member functions
private:
Node nodeArray[MAX_NODES];
// other members
};
Here, the Node class will deal with each node and the NodeNetwork is used to deal with the complete network.
The actual number of nodes in nodeArray can vary from 0 to MAX_NODES during runtime, i.e., it may not always be MAX_NODES, the number of nodes can be increased or decreased during runtime. Moreover, when the program starts the number will always be 0, after that it will start increasing.
I am using Node nodeArray[MAX_NODES];, but I think it's a serious wastage of space as not always I will have MAX_NODES nodes at runtime. So I am looking for ways to optimize it. I want it so that it starts with a zero-length array, but the size can be increased or decreased subjected to the above constraints based on the nodes added or removed at runtime. I researched on the internet but did not find any concrete answer.
I hope someone can help me solve this problem, thanks in advance.
| You can use dynamically array allocation for this purpose:
int* arr = new int[5];
..and anytime you wish to change the number of elements:
int size = 5;
int* arr = new int[size] {};
int* new_arr = new int[size + 1];
for (int i = 0; i < size; i++)
{
new_arr[i] = arr[i];
}
delete[] arr;
arr = new_arr;
// Now arr has a storage capacity of 6 elements
..so for your case you can write:
Node* nodeArray = nullptr; // nullptr == null pointer
But this can take a lot of time for huge arrays.
So preferably, you can use std::vector:
#include <iostream>
#include <vector>
int main()
{
std::vector<int> vec{ 1, 2, 3, 4, 5 };
vec.push_back(6); //Insert a new element
std::cout << vec[0]; // Accessing an element is the same as an array
}
..so for your case:
// {} is just for initialization, not exactly mandatory
std::vector<Node> nodeArray{};
|
71,440,067 | 71,443,339 | Python ctypes argtypes for class object pointer | I have this C++ code to integrate my class Foo based code into python.
class Foo{
public:
Foo(){};
int do_thing(int arg){ return arg*2; }
};
extern "C" {
Foo* get_foo_obj(){
return new Foo;
}
int do_thing(Foo* ptr, int arg){
return ptr->do_thing(arg);
}
}
Now I want to assign argtypes and restype for the functions from python.
lib = ctypes.CDLL("mylib.so")
lib.get_foo_obj.restype = <POINTER?>
lib.do_thing.argtypes = (<POINTER?>, c_int)
lib.do_thing.restype = c_int
What would be the correct ctypes I need to use here?
| ctypes.c_void_p works (void* in C), although you can be more type safe with an opaque pointer type like:
import ctypes as ct
class Foo(ct.Structure):
pass
lib = ct.CDLL('mylib.so')
lib.get_foo_obj.argtypes = ()
lib.get_foo_obj.restype = ct.POINTER(Foo)
lib.do_thing.argtypes = ct.POINTER(Foo), ct.c_int
lib.do_thing.restype = ct.c_int
foo = lib.get_foo_obj()
print(lib.do_thing(foo, 5))
|
71,440,305 | 71,440,417 | free(): double free detected in tcache 2, in linked List deletion of a node in c++ and how destructor is working in this code | class Node{
public:
int data;
Node* next;
Node(int d){
data = d;
next = NULL;
}
~Node(){
delete next;
}
};
class List{
public:
Node* head;
Node* tail;
List(){
head = NULL;
tail = NULL;
}
~List(){
delete head;
}
void push_back(int data){
Node* n = new Node(data);
if(head == NULL){
head = tail = n;
}else{
tail->next = n;
tail = n;
}
}
void print(){
Node* temp = head;
while(temp != NULL){
cout<<temp->data<<" ";
temp = temp->next;
}
}
void deleteNode(int d){
Node* curr = head;
Node* prev = NULL;
while(curr != NULL){
if(curr->data == d){
if(prev == NULL){
head = head->next;
delete curr;
break;
}else{
prev->next = curr->next;
curr->next = NULL;
delete curr;
break;
}
}
prev = curr;
curr = curr->next;
}
}
};
int main(){
List l;
l.push_back(1);
l.push_back(2);
l.push_back(3);
l.push_back(4);
l.push_back(5);
l.deleteNode(1);
l.print();
}
If I delete 1 from 1->2->3->4->5
Expected Output: 2->3->4->5
Output: free(): double free detected in tcache 2;
Reason: Destructor in Node Class. If I remove it is working fine.
Doubt : If I remove destructor in Node class in Node class then how can I free up memory. And can anyone also explain how destructors are working in both Node and List class.
Can someone please help me with this, or can provide alternative solution.
Thank You!!!
| ~Node(){ delete next; } makes it hard to delete a single node from that list. It'll delete all nodes after it too.
I suggest that the individual Nodes do not delete following Nodes:
class Node {
public:
int data;
Node* next;
Node(int d) : // colon starts the member initializer list
data(d), next(nullptr)
{
// the body of the constructor can now be empty
}
// No user-defined destructor needed here
};
Instead, delete all Nodes in the destructor of List:
~List() {
for(Node* next; head; head = next) {
next = head->next;
delete head;
}
}
Unrelated to the problem at hand. These are just suggestions:
You could make the constructor of Node a little more versatile so it's possible to provide the next Node already at construction:
class Node {
public:
int data;
Node* next;
// `nullptr` below is a default argument that will be used if the
// user of this class does not provide a second argument
Node(int d, Node* n = nullptr) :
data(d), next(n)
{}
};
This could be used in a List member function called push_front:
void push_front(int data) {
head = new Node(data, head);
if(!tail) tail = head;
}
Unrelated to that, you could make push_back a little clearer without even changing the current Node at all:
void push_back(int data) {
Node* n = new Node(data);
if(tail) tail->next = n;
else head = n;
tail = n;
}
|
71,440,327 | 71,441,763 | Align struct while minimizing cache line waste | There are many great threads on how to align structs to the cache line (e.g., Aligning to cache line and knowing the cache line size).
Imagine you have a system with 256B cache line size, and a struct of size 17B (e.g., a tightly packed struct with two uint64_t and one uint8_t). If you align the struct to cache line size, you will have exactly one cache line load per struct instance.
For machines with a cache line size of 32B or maybe even 64B, this will be good for performance, because we avoid having to fetch 2 caches lines as we do definitely not cross CL boundaries.
However, on the 256B machine, this wastes lots of memory and results in unnecessary loads when iterating through an array/vector of this struct. In fact, you could store 15 instances of the struct in a single cacheline.
My question is two-fold:
In C++17 and above, using alignas, I can align to cache line size. However, it is unclear to me how I can force alignment in a way that is similar to "put as many instances in a cache line as possible without crossing the cache line boundary, then start at the next cache line". So something like this:
where the upper box is a cache line and the other boxes are instances of our small struct.
Do I actually want this? I cannot really wrap my head around this. Usually, we say if we align our struct to the cache line size, access will be faster, as we just have to load a single cache line. However, seeing my example, I wonder if this is actually true. Wouldn't it be faster to not be aligned, but instead store many more instances in a single cache line?
Thank you so much for your input here. It is much appreciated.
| To address (2), it is unclear whether the extra overhead of using packed structs (e.g., unaligned 64-bit accesses) and the extra math to access array elements will be worth it. But if you want to try it, you can create a new struct to pack your struct elements appropriately, then create a small wrapper class to access the elements like you would an array:
#include <array>
#include <iostream>
using namespace std;
template <typename T, size_t BlockAlignment>
struct __attribute__((packed)) Packer
{
static constexpr size_t NUM_ELEMS = BlockAlignment / sizeof(T);
static_assert( NUM_ELEMS > 0, "BlockAlignment too small for one object." );
T &operator[]( size_t index ) { return packed[index]; }
T packed[ NUM_ELEMS ];
uint8_t padding[ BlockAlignment - sizeof(T)*NUM_ELEMS ];
};
template <typename T, size_t NumElements, size_t BlockAlignment>
struct alignas(BlockAlignment) PackedAlignedArray
{
typedef Packer<T, BlockAlignment> PackerType;
std::array< PackerType, NumElements / PackerType::NUM_ELEMS + 1 > packers;
T &operator[]( size_t index ) {
return packers[ index / PackerType::NUM_ELEMS ][ index % PackerType::NUM_ELEMS ];
}
};
struct __attribute__((packed)) Foo
{
uint64_t a;
uint64_t b;
uint8_t c;
};
int main()
{
static_assert( sizeof(Foo) == 17, "Struct not packed for test" );
constexpr size_t NUM_ELEMENTS = 10;
constexpr size_t BLOCK_ALIGNMENT = 64;
PackedAlignedArray<Foo, NUM_ELEMENTS, BLOCK_ALIGNMENT> theArray;
for ( size_t i=0; i<NUM_ELEMENTS; ++i )
{
// Display the memory offset between the current
// element and the start of the array
cout << reinterpret_cast<std::ptrdiff_t>(&theArray[i]) -
reinterpret_cast<std::ptrdiff_t>(&theArray[0]) << std::endl;
}
return 0;
}
The output of the program shows the byte offsets of the addresses in memory of the the 17-byte elements, automatically resetting to a multiple of 64 every four elements:
0
17
34
64
81
98
128
145
162
192
|
71,440,372 | 71,440,769 | lifetime of a temporary object when passed as an argument to std::move | Can somebody explain how the lifetime of a temporary object gets affected when (and not) is passed as an argument to std::move. In the below code I'm creating r-value references using with and without std::move. And to my surprise I didn't get expected results.
#include <iostream>
class A {
public:
A() {
std::cout << "const" << std::endl;
}
A(A&& a) {
std::cout << "move const" << std::endl;
}
~A() {
std::cout << "dest" << std::endl;
}
};
void fn(A&& a) {
std::cout << "inside fn" << std::endl;
}
int main() {
A&& a_ref = std::move(A());
fn(std::move(A()));
A&& a_ref1 = A();
std::cout << "end" << std::endl;
}
And this is the output I got
const
dest
const
inside fn
dest
const
end
dest
| The lifetime extension of temporary objects does not work when you pass that temporary through a function. When you do
A&& a_ref = std::move(A());
The rvalue reference that A() binds to is not a_ref but instead the parameter of move. That parameter is destroyed when the fucntion ends, which means the temporary it is bound to will also be destroyed. This is why we see
const
dest
in the output and a_ref is a dangling refence.
With
fn(std::move(A()));
a temporary A is created from A() and move passes along a reference to that temporary to fun. The temporary is still bound to the parameter of move but since temporary objects live at least until the end of the full expression they were created in, A() will still be alive when we enter fun. The temporary will only be destroyed after fun ends which corresponds to the output of
const
inside fn
dest
Then with
A&& a_ref1 = A();
Here we are binding a temporary directly to an rvalue reference. This will extend the lifetime of the temporary to be the lifetime of the reference. Since the reference is local to main, it is only "destroyed" once main ends, so that is why you see the output
const
end
dest
|
71,440,526 | 71,441,989 | Plotting multiple dataset in same gnuplot window | I have two data set (x,y1) and (x,y2) which I got from the result of computation and wrote those files in "data1.tmp" & "data2.tmp". I want to use this two data set to plot in Gnuplot.
#include <iostream>
#include <cstdlib>
int main()
{
FILE* gnupipe1, *gnupipe2;
const char* GnuCommands1[] = {"set title \"v vs x\"","plot \'data1.tmp\' with lines"};
const char* GnuCommands2[] = {"set title \"y vs x\"","plot \'data2.tmp\' with lines"};
gnupipe1 = _popen("gnuplot -persistent","w");
gnupipe2 = _popen("gnuplot -persistent", "w");
for (int i = 0; i < 2; i++)
{
fprintf(gnupipe1,"%s\n",GnuCommands1[i]);
fprintf(gnupipe2,"%s\n", GnuCommands2[i]);
}
return 0;
}
Now when I run the program two window shows up plotting the data accurately.
How to plot multiple data set this way? say (x,y1) & (x,y2) in same window?
| You are opening two different gnuplots, you don't need to do that.
#include <iostream>
#include <cstdlib>
int main()
{
FILE* gnupipe1;
const char* GnuCommands1[] = {"set title \"v vs x\"",
"plot \'data1.tmp\' with lines, \'data2.tmp\' with lines"};
gnupipe1 = _popen("gnuplot -persistent","w");
for (int i = 0; i < 2; i++)
fprintf(gnupipe1,"%s\n",GnuCommands1[i]);
return 0;
}
|
71,440,707 | 71,440,918 | How to find the Final Path from the Traversal Path while performing BFS/DFS algorithm | I am trying to solve a problem which apples a Breadth-First Search Algorithm as well as Depth-First Search algorithm on a Tree and finds out the traversal and final paths that are found by both these algorithms.
What I am actually confused with is how do I calculate these two different paths? And are they really different?
For example, consider the following tree,
Let's say, that our starting node is A and Goal node is H
For both the algorithms, this is what I feel would be the Traversed and Final Paths
For BFS
Traversal Path: A B C D E F G H
Final Path: A C F H
If this is how it works, then how can I find that Final Path? Its very easy to find traversed path, but not exactly so easy to find the Final Path.
Similarly,
For DFS
Traversal Path: A B D E C F G
Final Path: A C F H
Again, how can I extract the Final Path from the Traversal Path for DFS.
This actually gets a bit more complicated. What if my Goal Node is reachable from two sides? How do I find the Final Path in such a scenario?
For example, Consider the following scenario,
Let's say for this case, our Starting Node is A and Goal Node is H, again.
Traversal path is very easy to compute with both BFS and DFS.
But for the Final Path, "H" is reachable from two sides, it is reachable from F and it is also reachable from G
For the DFS, you may write the final path as A C F G because from the F node, we would reach the H first (as G would still be unexplored, however you would still have to extract this Final Path from the Traversal path, which I do not know how to do)
But for BFS, you can not do that. So, what would be my Final Path in this scenario? Should there be two Final Paths in such a scenario?
Can anyone help me out in this please.
| One [out of many possible] approach is to maintain a map of target to source node. Every time you advance, record which source node was made to make that advance. So, in BFS case it will look like:
parents = {
'A': NULL,
'B': 'A',
'C': 'A',
'D': 'B',
'E': 'B',
'F': 'C',
'G': 'C'
}
Then, from the final node, reconstruct the path by going backward:
node = target
path = []
while node:
path.append(node)
node = parents[node]
Same approach works for DFS and Dijkstra
|
71,441,047 | 71,441,228 | I was trying to convert String into ASCII value using Recursive function. By using the string only as parameter | This is my code (I want to use string as the parameter only):
#include <iostream>
using namespace std;
int i = 0; //to take string character by character
void parseToInteger (string s1)
{
char convert;
string another;
if (convert == s1.length()) //at null character function terminates
{
cout<<endl; // prints nothing
}
else
{
convert = s1.at(i++);
static_cast <int> (convert);
cout<<convert;
parseToInteger (s1);
}
}
int main ()
{
string s0;
cout<<"Enter a string to convert it into its integer value: ";
getline (cin, s0);
parseToInteger (s0);
return 0;
}
This is the error I am getting:
Enter a string to convert it into its integer value: hello
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::at: __n (which is 32540) >= this->size() (which is 5)
Can someone please help me? I am learning to program.
| Your if (convert == s1.length()) is very strange. That expression is comparing an uninitialized char variable to the length of the s1 string (which will be of size_t type). What you should be doing is comparing the i variable to the length (and that i would be better defined as size_t type).
Also the static_cast <int> (convert); line does nothing. You can't change the type of a variable like that; instead, you should use the cast on the operand of the cout << in the following line. And note that, when casting a character digit to its integer value, you need to subtract the value of '0' from it.
Here's a fixed version that addresses the above issues:
#include <iostream>
#include <string> // You 'forgot' this required header
size_t i = 0; // The "size_t" type is better suited for container sizes and lengths
void parseToInteger(std::string s1)
{
char convert;
// std::string another; // Never used!
if (i == s1.length()) { // Here, we've reached the end of the string
std::cout << std::endl; // prints nothing
}
else {
convert = s1.at(i++);
std::cout << cout << static_cast <int> (convert - '0'); // Apply the cast here
parseToInteger(s1);
}
}
int main()
{
std::string s0;
std::cout << "Enter a string to convert it into its integer value: ";
std::getline(std::cin, s0);
parseToInteger(s0);
return 0;
}
But note, there are other concerns in your code, as mentioned in the comments. First, it would be better to pass the s1 argument by reference; second: Are global variables bad?
Here's a version of your function that addresses these last two concerns:
void parseToInteger(std::string& s1, size_t i = 0)
{
if (i == s1.length()) { // Here, we've reached the end of the string
std::cout << std::endl; // 'flushes' output stream
}
else {
char convert = s1.at(i++);
std::cout << static_cast <int> (convert - '0'); // Convert to int
parseToInteger(s1, i);
}
}
The default value (of zero) for the new i argument means that you don't have to change the call in the main function.
|
71,441,341 | 71,441,886 | Overloading insertion operator for std::array | I'm trying to overload the insertion (<<) operator to output elements of an std::array. The following yields a compilation error:
// overload operator<< to display array objects of any type T and size N
template<typename T, int N>
std::ostream &operator<<(std::ostream &Output, const std::array<T,N> &Arr) {
for (const auto &Element: Arr)
Output << Element << " ";
return Output;
}
But the following works just fine (if I apply it to an array of, say, 5 elements):
// overload operator<< to display array objects of any type T and size 5
template<typename T>
std::ostream &operator<<(std::ostream &Output, const std::array<T,5> &Arr) {
for (const auto &Element: Arr)
Output << Element << " ";
return Output;
}
I'm aware that arrays need to know their size N at compile time, but doesn't the template provide just that?
The error happens when I try, for instance, the following:
std::array<int,5> MyArr {1, 2, 3, 4, 5};
std::cout << "MyArr = " << MyArr;
| The 2nd template argument of std::array is a size_t, not an int.
Also, return output; needs to be return Output; as C++ is case-sensitive.
// overload operator<< to display array objects of any type T and size N
template<typename T, size_t N>
std::ostream &operator<<(std::ostream &Output, const std::array<T,N> &Arr) {
for (const auto &Element: Arr)
Output << Element << " ";
return Output;
}
|
71,441,443 | 71,441,512 | can I add optional types parameters in C++ | the title says it all.
I have this function that couts the parameter:
void outlog(string par) {
std::cout << par;
}
but Par can only be a string. how can I make its type optional.
| C++ (and many other languages) makes it available to have generic functions. Here you can read more about it: Generics in C++ Here is the sample code for your function. Note: the object should be printable (if it is a class object, it should have the << operator overloaded):
template <typename T>
void outlog(T& input){
std::cout << input;
}
|
71,441,900 | 71,446,441 | How to unit test bit manipulation logic | I have a method which converts RGBA to BGRA. Below is the method
unsigned int ConvertRGBAToBGRA(unsigned int v) {
unsigned char r = (v)& 0xFF;
unsigned char g = (v >> 8) & 0xFF;
unsigned char b = (v >> 16) & 0xFF;
unsigned char a = (v >> 24) & 0xFF;
return (a << 24) | (r << 16) | (g << 8) | b;
};
How can I unit test this nicely? Is there a way I can read back the bits and unit test this method somehow?
I am using googletests
| Inspired by @Yves Daoust's comment, why can't you just write a series of checks like below? You can use the nice formatting of C++14:
unsigned int ConvertRGBAToBGRA(unsigned int v) {
unsigned char r = (v)&0xFF;
unsigned char g = (v >> 8) & 0xFF;
unsigned char b = (v >> 16) & 0xFF;
unsigned char a = (v >> 24) & 0xFF;
return (a << 24) | (r << 16) | (g << 8) | b;
};
TEST(ConvertRGBAToBGRATest, Test1) {
EXPECT_EQ(ConvertRGBAToBGRA(0x12'34'56'78), 0x12'78'56'34);
EXPECT_EQ(ConvertRGBAToBGRA(0x12'78'56'34), 0x12'34'56'78);
EXPECT_EQ(ConvertRGBAToBGRA(0x11'11'11'11), 0x11'11'11'11);
EXPECT_EQ(ConvertRGBAToBGRA(0x00'00'00'00), 0x00'00'00'00);
EXPECT_EQ(ConvertRGBAToBGRA(0xAa'Bb'Cc'Dd), 0xAa'Dd'Cc'Bb);
EXPECT_EQ(ConvertRGBAToBGRA(ConvertRGBAToBGRA(0x12'34'56'78)), 0x12'34'56'78);
EXPECT_EQ(ConvertRGBAToBGRA(ConvertRGBAToBGRA(0x12'78'56'34)), 0x12'78'56'34);
EXPECT_EQ(ConvertRGBAToBGRA(ConvertRGBAToBGRA(0x11'11'11'11)), 0x11'11'11'11);
EXPECT_EQ(ConvertRGBAToBGRA(ConvertRGBAToBGRA(0x00'00'00'00)), 0x00'00'00'00);
EXPECT_EQ(ConvertRGBAToBGRA(ConvertRGBAToBGRA(0xAa'Bb'Cc'Dd)), 0xAa'Bb'Cc'Dd);
}
Live example: https://godbolt.org/z/eEajYYYsf
You could also define a custom matcher and use EXPECT_THAT macro:
// A custom matcher for comparing BGRA and RGBA.
MATCHER_P(IsBgraOf, n, "") {
return ((n & 0xFF000000) == (arg & 0xFF000000)) &&
((n & 0x00FF0000) == ((arg << 16) & 0x00FF0000)) &&
((n & 0x0000FF00) == (arg & 0x0000FF00));
}
TEST(ConvertRGBAToBGRATest, WithExpectThat) {
EXPECT_THAT(ConvertRGBAToBGRA(0x12'34'56'78), IsBgraOf(0x12'34'56'78));
EXPECT_THAT(ConvertRGBAToBGRA(0x12'78'56'34), IsBgraOf(0x12'78'56'34));
EXPECT_THAT(ConvertRGBAToBGRA(0xAa'Bb'Cc'Dd), IsBgraOf(0xAa'Bb'Cc'Dd));
EXPECT_THAT(ConvertRGBAToBGRA(0x00'00'00'00), IsBgraOf(0x00'00'00'00));
EXPECT_THAT(ConvertRGBAToBGRA(0x11'11'11'11), IsBgraOf(0x11'11'11'11));
}
Live example: https://godbolt.org/z/P4EcW19s9
|
71,442,134 | 71,442,466 | Can you Avoid Multiple Operator Overloads for Mathematical Operators? | Say I have a very simple Rational class like the one below:
class Rational
{
int numer;
int denom;
public:
Rational(const int& numer, const int& denom) : numer(numer), denom(denom) {}
void operator*(const Rational& other) { std::cout << "multiply, simple as\n"; }
}
All well and good. Then say that I want to be able to multiply my Rational class with an integer, so I add another function to the class:
class Rational
{
int numer;
int denom;
public:
Rational(const int& numer, const int& denom) : numer(numer), denom(denom) {}
void operator*(const Rational& other) { std::cout << "multiply, simple as\n"; }
void operator*(const int& other) { std::cout << "some math here\n"; }
}
Ok no big deal. Except that I can't actually do the following because the order of the parameters would be all wrong:
Rational mine(1, 2);
const Rational result = 2 * mine;
Ok, one more iteration and I have the following:
class Rational
{
int numer;
int denom;
public:
Rational(const int& numer, const int& denom) : numer(numer), denom(denom) {}
void operator*(const Rational& other) { std::cout << "multiply, simple as\n"; }
void operator*(const int& other) { std::cout << "some math here\n"; }
friend void operator*(const int& other, const Rational& mine) { std::cout << "even more math here\n"; }
}
What I'm trying to find out is if there's a way that I can avoid having to write the same function twice for every mathematical operation that I'd want my class to support, just so that I can call it with the arguments in whatever order I want. This may well just be how you have to implement this sort of thing within C++'s type system, but it seems a tad annoying to have to add this boilerplate for every mathematical operation that you want your class to support.
| The issue with having a single function is that the type of the left and right operands to * would vary (and you would have to use them differently).
This can be solved by fixing both of the argument types to Rational and creating an implicit conversion from an int x to Rational x/1 (which is probably desirable anyways). This way, in 2 * mine, the 2 will implicitly be converted to Rational(2, 1) * mine.
Here's an example:
class Rational
{
int numer;
int denom;
public:
// default argument of denom=1 allows implicit conversion from int
Rational(int numer, int denom = 1) : numer(numer), denom(denom) {}
friend Rational operator*(const Rational& l, const Rational& r) {
std::cout << "Rational(" << l.numer << ", " << l.denom
<< ") * Rational(" << r.numer << ", " << r.denom << ")\n";
// calculate and return result
}
friend Rational operator/(const Rational& l, const Rational& r) { /* ... */ }
friend bool operator==(const Rational& l, const Rational& r) { /* ... */ }
};
|
71,442,143 | 71,442,325 | Overloading and LinkedList | I was trying to overload cout operator to print a class.
The class consists of an integer value and a pointer. So I was hoping to print an integer value and a memory address, but I got an error. I got confused since the class itself already has a pointer and couldn't figure out the problem.
The compiler gives "expected primary-expression before '.' token" error for the overloading part of the code.
#include <iostream>
using namespace std;
class Node{
public:
int Value;
Node* Next;
};
ostream& operator<<(ostream& a, Node& head){
a << "Value " << Node.Value << endl;
a << "To where " << Node.Next << endl;
return a;
}
int main()
{
Node* head = new Node();
Node* second = new Node();
Node* third = new Node();
head -> Value = 1;
second -> Value = 2;
third -> Value = 3;
head -> Next = second;
second -> Next = third;
third -> Next = NULL;
cout << head;
return 0;
}
| First, generally we need to add a friend declaration for the overloaded operator<< so that the be-friended function can access the private fields of the class type as shown below. But since both the data members of your class type are public you can skip the friend declaration.
Second, Node.value should be replaced by head.value as shown below.
Third, cout << head should be replaced by cout << *head as shown below:
class Node{
public:
int Value;
Node* Next;
//friend declaration for overloaded operator<< NOTE: Since both the data members are public you can skip this friend declaration
friend std::ostream& operator<<(std::ostream& a, const Node& head);
};
//definition for overloaded operator<<
std::ostream& operator<<(std::ostream& a,const Node& head){
a << "Value " << head.Value << std::endl << "To where " << head.Next;
return a;
}
int main()
{
Node* head = new Node();
Node* second = new Node();
Node* third = new Node();
head -> Value = 1;
second -> Value = 2;
third -> Value = 3;
head -> Next = second;
second -> Next = third;
third -> Next = NULL;
std::cout << *head;
//don't forget to use delete to free the dynamic memory
}
Also, don't forget to use delete(when/where needed) so that you don't have memory leaks.
|
71,442,472 | 71,444,732 | C++ : Throw Away threads vs Thread Pool | So I have a main application thread in my opengl application with all rendering and stuff. Now i need some really heavy calculation which takes about 2 3 seconds so I moved it to a seperate thread here is how I manage it:
std::atomic<bool> working = false;
void work(){
if(!working)
{
working = true;
std::thread worker(do_work);
worker.detach();
}
else
{
// Some Updations
}
}
void do_work()
{
// The actual work
// working = false;
}
Now i call work every frame and the actual work gets dispatched automatically once the previous one has finished.
Now my question is what will be some ways to optimize this?
Some ideas that come to my mind are have a thread pool but I am not sure if that is worth the trouble implementing? Or is there any other way?
| You could use std::launch as some people have suggested. Or you could do a google for "c++ thread pool library" and probably find something waiting for you.
But the reality is simple: writing a thread pool is close to trivial and is a good exercise. So you could write your own and learn something. As has been suggested, you can dispatch via some sort of message queue.
A work queue would be any sort of mutex & cond_var - managed FIFO, and then you can have multiple readers and multiple writers. The entries in the queue can be any sort of runnable or bound function (such as a lambda).
Fun to write and you can toss into your person library for years to come.
|
71,442,515 | 71,442,749 | Inheritance and random number generation in const member function | I have the following class inheritance structure
#include <random>
class ABC{
protected:
std::mt19937_64 rng;
double a();//calls random correction
virtual double random_correction() const=0;
public:
double x;
explicit ABC(const double x0) :
rng(std::random_device{}()), x(x0){}
ABC(const ABC& other)=default;
ABC& operator=(const ABC& other)=default;
ABC(ABC&& other) noexcept = default;
ABC& operator=(ABC&& other) noexcept = default ;
virtual ~ABC()=default;
virtual void update(const int step_number)=0;//calls a and uses rng
};
class D1 : public ABC{
private:
double y;
double random_correction() const override {return 0;};
public:
D1(const double x0, const double y0):
ABC(x0), y(y0){}
D1(const D1& other)=default;
D1& operator=(const D1& other)=default;
D1(D1&& other) noexcept = default;
D1& operator=(D1&& other) noexcept = default ;
~D1() override=default;
void update(const int step_number) override;
};
class D2 : public D1{
private:
double noise;
double random_correction() const override {
static std::uniform_real_distribution<> u{-noise, noise};
return u(rng); //error here
};
public:
D2(const double x0, const double y0, const double na):
D1(x0,y0), noise(na) {}
D2(const D2& other)=default;
D2& operator=(const D2& other)=default;
D2(D2&& other) noexcept = default;
D2& operator=(D2&& other) noexcept = default ;
~D2() override=default;
};
In the definition of random_correction of D2 I get the following error: "in instantiation of function template specialization 'std::uniform_real_distribution::operator()<const std::mersenne_twister_engine<unsigned long, 64, 312, 156, 31, 13043109905998158313, 29, 6148914691236517205, 17, 8202884508482404352, 37, 18444473444759240704, 43, 6364136223846793005> >' requested here" .
If I erase the const qualifier in all the declaration the error disappear.
Why? Doesn't a const qualifier in a member function mean that no member of the class is going to be modified?
As a workaround I thought I could modify the class D2 in this way
class D2 : public D1{
private:
double noise;
std::uniform_real_distribution<> u;
double random_correction() const override {
return u(rng); //error always here
};
public:
D2(const double x0, const double y0, const double na):
D1(x0,y0), noise(na) {u.param(std::uniform_real_distribution<>::param_type{-noise, noise});}
D2(const D2& other)=default;
D2& operator=(const D2& other)=default;
D2(D2&& other) noexcept = default;
D2& operator=(D2&& other) noexcept = default ;
~D2() override=default;
};
However now I get the error: "no matching function for call to object of type 'const std::uniform_real_distribution<>'". I suppose because generating a random number changes the state of u (and maybe of rng as well). Is this correct? Is it convenient to have a distribution as a member?
P.S. Please, if there is any design error or inefficiency point it out to me.
| Generating random number doesn't change the state of u. It's state is just what range of values to be generated.
But it does change the state of rng. Pseudo-random number generators are usually deterministic meaning that rng() is determined by the current state and the state will change upon evaluation so next time a different value will be produced.
To fix the compilation issue, you can either drop the const declaration of the function or you can declare rng to be mutable. It will still bear certain problems like "accessing the class instance concurrently will cause data races". So you might consider rethinking the design.
RNG engines can benefit from thread_local keyword... but you'll need to design it in a way so it won't cause performance issues which can be a bit tricky.
Edit: after checking in with cppreference apparently uniform_distribution can contain extra information besides the range of distribution. Probably, bits of data that were generated by the RNG engine, so it can use them for future calls and doesn't need to use the engine too often.
|
71,443,639 | 71,443,830 | Issue with std::wstring when calling from c# with DllImport | I was going to call an unmanaged function in a c++ library from c#, but it crashed. While troubleshooting I narrowed it down to std::wstring. A minimal example looks like this:
C++
#include <iostream>
extern "C" __declspec(dllexport) int __cdecl Start()
{
std::wstring test = std::wstring(L"Hello World");
return 2;
}
C#
using System.Runtime.InteropServices;
internal class Program
{
[DllImport("test.exe", CallingConvention=CallingConvention.Cdecl)]
public static extern int Start();
static void Main(string[] args)
{
var result = Start();
Console.WriteLine($"Result: {result}");
}
}
This gives me a Stack overflow. If I remove the line with std::wstring or I change it to std::string, there is no problem and I get back 2.
Can anyone explain to me what is going on here?
| This is something I noticed:
[DllImport("test.exe", CallingConvention=CallingConvention.Cdecl)]
Exporting functions from an EXE instead of a DLL isn't standard. (I think it can be done, but I wouldn't recommend it.)
Build your C++ code as a DLL instead of an EXE. Statically link the DLL with the C++ runtime libraries to avoid missing dependency issues that could arise from not having the right DLLs in the loader search path.
|
71,443,997 | 71,444,773 | Creation of a driving simulator : how to rotate the circuit around the origin? | I have a circuit in my driving simulator in cpp and I want to know how to rotate the circuit around the origin, I tried to dig into some trigonometry because i know this is what will help me but I'm at a point where I'm stuck.
For your information, the circuit is stored inside a vector of pair (std::vector<pair<double,double> roads).
Here's what my example circuit looks like (red one), and what i want to do are the two other iteration (yellow and green).
circuit in 3 steps:
and this is an example of what is stored inside roads
x : 170, y : 0
x : -170, y : 0`
x : 170, y : 0
x : -170, y : 0
x : 170, y : -0.69632
x : -170, y : -0.69632
x : 170, y : -5.57056
x : -170, y : -5.57056
x : 170, y : -18.8006
x : -170, y : -18.8006
x : 170, y : -44.5645
x : -170, y : -44.5645
x : 170, y : -0.69632
x : -170, y : -0.69632
x : 170, y : -5.57056
x : -170, y : -5.57056
x : 170, y : -18.8006
x : -170, y : -18.8006
x : 170, y : -44.5645
x : -170, y : -44.5645
...
For going foward, backward, straft to the left or the right, it's quite easy as i only need to decrease/ increase all x/y as i go in one direction, but the problem comes when i want to rotate.
I know that, in theory I need to make sqrt(x²+y²) to find the distance from the origin (aka the driver) and apply a rotation in consideration of that distance (as a ratio, the lesser the distance is the lesser it needs to rotate).
But for now, I'm stuck and I don't know how to do that, can anyone provide my some sort of explanation on how to do this ?
| you just get to apply a 2d rotation matrix (https://en.wikipedia.org/wiki/Rotation_matrix). This should work, you just get to iterate at each point:
#include <math.h>
void rotate(float &x,float &y,float teta)
{
float newX = x*cos(teta)+y*sin(teta);
float newY = x*sin(teta)-y*cos(teta);
x = newX;
y = newY;
}
remember that this teta angle is measured in radians not degrees.
|
71,444,098 | 71,444,301 | Automatic generation of a brace-enclosed initializer list in C++ using language features (NOT pre-processor directives) | I'm looking for a solution using only native C++ language features (up to C++17) for accomplishing the following:
std::array<Type, unsigned int Elem> array_{Type(), // 1 - Call constructor on Type()
Type(), // 2 - ...
... , // 3 - ...
Type()} // Elems - Call the Elem:th Type() constructor
In addition, what I'd also like is that each constructor call should be able to take an arbitrary number of arguments.
A concrete example would be to automate the writing of the following:
std::array<std::shared_ptr<int>, 4> array_{std::make_shared<int>(),
std::make_shared<int>(),
std::make_shared<int>(),
std::make_shared<int>()}
I.e., provided that I know Type and Elem, I'd like to automate the process of creating the brace-enclosed initializer list and in the process call Type:s constructor.
Any ideas?
Update, the real problem I'd like to solve is the following:
template <typename Type, unsigned int Size>
class Storage {
public:
Storage(std::initializer_list<Type> initializer) : array_{initializer} {}
private:
std::array<Type, Size> array_;
};
void foo(){
Storage<std::shared_ptr<int>, 100> storage(...);
// or perhaps
auto storage = std::make_shared<Storage<std::shared_ptr<int>, 100>>(here be an initializer list containing calls to 100 std::make_shared<int>());
}
| Like this:
#include <array>
#include <memory>
#include <utility>
template <std::size_t ...I>
std::array<std::shared_ptr<int>, sizeof...(I)> foo(std::index_sequence<I...>)
{
return {(void(I), std::make_shared<int>())...};
}
std::array<std::shared_ptr<int>, 4> array_ = foo(std::make_index_sequence<4>());
Guaranteed copy elision from C++17 ensures that the array is constructed in place, and no extra moves happen.
The return statement expands to {(void(0), std::make_shared<int>()), (void(1), std::make_shared<int>())...}. void(...) is not strictly necessary, but Clang emits a warning otherwise.
But if it was my code, I'd write a more generic helper instead:
#include <utility>
template <typename R, typename N, typename F, N ...I>
[[nodiscard]] R GenerateForEach(std::integer_sequence<N, I...>, F &&func)
{
return {(void(I), func(std::integral_constant<N, I>{}))...};
}
template <typename R, auto N, typename F>
[[nodiscard]] R Generate(F &&func)
{
return (GenerateForEach<R, decltype(N)>)(std::make_integer_sequence<decltype(N), N>{}, std::forward<F>(func));
}
Then:
auto array_ = Generate<std::array<std::shared_ptr<int>, 4>, 4>([](auto){return std::make_shared<int>();});
While the lambda discards the index in this case, it often ends up being useful, especially given that in [](auto index){...}, index.value is constexpr.
|
71,444,249 | 71,444,560 | calculation of the midpoint of the coordinate values entered by the user. (x, y, z axes) Need class topic | I have an assignment, here is the description:
Create a class named Point. It must have three private float field named as x, y, z to keep coordinates in space and public get and set functions to access these data members ( getX(), getY(), getZ(), setX(), setY(), setZ() ). Create another function that is defined outside of the scope of Point class and named Space. In Space function, you will find the middle point between two points and create a new Point object that will keep calculated coordinates. The written code below must be able to run without errors.
The teacher gave us structure of the code. The code should be like below. only the definition of get, set and space functions can change. I wrote the set and get functions, but I have no idea what to do with the space function. That's why I need help with the space function part.
#include <iostream>
using namespace std;
class Point {
private:
int x, y, z;
public:
float getX();
float getY();
float getZ();
void setX(float x1);
void setY(float y1);
void setZ(float z1);
};
float Point::getX() {
return x;
}
float Point::getY() {
return y;
}
float Point::getZ() {
return z;
}
void Point::setX(float x1) {
x = x1;
}
void Point::setY(float y1) {
y = y1;
}
void Point::setZ(float z1) {
z = z1;
}
Point Space(Point a, Point b)
{
// complete space function
}
int main()
{
float x_, y_, z_;
Point p[3];
for (int i = 0; i < 2; ++i)
{
cout << "Please enter x coordinate for p" << i + 1 << endl;
cin >> x_;
p[i].setX(x_);
cout << "Please enter y coordinate for p" << i + 1 << endl;
cin >> y_;
p[i].setY(y_);
cout << "Please enter z coordinate for p" << i + 1 << endl;
cin >> z_;
p[i].setZ(z_);
}
p[2] = Space(p[0], p[1]);
cout << "Coordinations of middle point (p3) between p1 and p2 is x=" << p[2].getX() << ",y=" << p[2].getY() << ", z=" << p[2].getZ();
return 0;
}
| As the instructions says:
In Space function, you will find the middle point between two points and create a new Point object that will keep calculated coordinates.
Per Mid Point Formula in 3D:
A midpoint is the exact center point between two defined points. To find this center point, midpoint formula is applied. In 3-dimensional space, the midpoint between (x1, y1, z1) and (x2, y2, z1) is (x1+x2)/2, (y1+y2)/2, (z1+z2)/2.
So, try this:
Point Space(Point a, Point b)
{
Point mid;
mid.setX((a.getX() + b.getX()) / 2);
mid.setY((a.getY() + b.getY()) / 2);
mid.setZ((a.getZ() + b.getZ()) / 2);
return mid;
}
|
71,444,527 | 71,445,271 | Find base period of sequence in C++ |
For a sequence of numbers a1, a2,...,an, we say that there is a period if 1≤p<n and if it holds that it is ai=ai+p for all values for which this equality makes sense.
For example, the sequence of numbers 1, 3, 1, 4, 2, 1, 3, 1, 4, 2, 1, 3 has period 5, because ai=ai+5 for all values such that both indices i and i+5 are within the allowable range (i.e. for 1 to 7 inclusive). The same sequence also has a period of 10. Next, we say that the sequence of numbers is periodic if it exists at least one number that is the period of that sequence, with the smallest such number being called the base sequence period. If such a number does not exist, the sequence is not periodic. For example, the above the sequence of numbers is periodic with the base period 5, while the sequence of numbers 4, 5, 1, 7, 1, 5 is not periodic.
#include <iostream>
#include <vector>
int period(std::vector<double> vektor) {
int p;
for (int i : vektor) {
for (int j : vektor) {
if (vektor[i] == vektor[j])
p = j;
}
}
return p;
}
int main() {
std::vector<double> vektor{1, 3, 1, 4, 2, 1, 3, 1, 4, 2, 1, 3};
std::cout << period(vektor);
return 0;
}
This should be solved using vector.
Could you help me fix this code? This returns 3 as base period of sequence.
| For starters it is unclear why you are using a vector with the value type double instead of the type int when all initializers have the type int.
The function period should accept a vector by constant reference.
The variable p is not initialized. As a result the function can return an indeterminate value.
The range based for loop does not return indices in a container as you think
for (int i : vektor) {
It returns stored in the vector objects of the type double.
So the condition in the if statement
if (vektor[i] == vektor[j])
makes no sense.
The function can look the following way as it is shown in the demonstration program below.
#include <iostream>
#include <vector>
size_t period( const std::vector<double> &v )
{
size_t p = 0;
for (size_t i = 1; !p && i < v.size(); i++)
{
size_t j = 0;
while (j < v.size() - i && v[j] == v[j + i]) ++j;
if ( j + i == v.size() ) p = i;
}
return p;
}
int main()
{
std::vector<double> v = { 1, 3, 1, 4, 2, 1, 3, 1, 4, 2, 1, 3 };
std::cout << period( v ) << '\n';
}
The program output is
5
|
71,444,896 | 71,444,957 | Having a member variable only conditionally present using requires clause | I wish to make the existence of member within dat dependent on B (or some other concept).
template <bool B>
struct dat {
void member_func() requires (B) {} //ok
std::byte member requires (B); //err
};
I know this is possible to do with specialisation but as far as I am aware that would get very ugly if multiple different member requirements were nessacary.
Is this behaviour possible without specialisation?
| There's a couple approaches to this (see Conditional Members).
One is you use the condition to change the type of member:
struct E { };
[[no_unique_address]] std::conditional_t<B, std::byte, E> member;
This isn't really a conditional member variable, member is always present. But it's sometimes the type you care about and other times it's an empty type that takes no space. That could be good enough - if you never actually have to access the thing, and no code depends on the presence of this member.
If that doesn't work, then you do have to resort to a different sort of specialization. But you don't have to specialize all of dat, just a base class that conditionally provides this member:
template <bool B>
struct maybe_member {
std::byte member;
};
template <>
struct maybe_member<false> { };
template <bool B>
struct dat : maybe_member<B> {
void member_func() requires (B) {} //ok
};
Here, dat<true> has a member named member but dat<false> has no data members. Which is important for things like iterator_category (as I mention).
Neither are great solutions, but both definitely beat having to specialize the entire class just to condition on member variable. Both scale if there is a need to have multiple different, independently conditional variables.
|
71,445,161 | 71,445,207 | clang standard library bug or c++ undefined behavior? | Does the following C++ program contain any undefined behavior?
int
main()
{
struct entry
{
uint32_t hash;
uint32_t idx;
};
entry arr[31] = {
{ 7978558, 0}, { 9241630, 1}, { 65706826, 2},
{ 639636154, 3}, {1033996244, 4}, {1225598536, 5},
{1231940272, 6}, {1252372402, 7}, {2019146042, 8},
{1520971906, 9}, {1532931792, 10}, {1818609302, 11},
{1971583702, 12}, {2116478830, 13}, { 883396844, 14},
{1942092984, 15}, {1274626222, 16}, { 333950222, 17},
{1265547464, 18}, { 965867746, 19}, {1471376532, 20},
{ 398997278, 21}, {1414926784, 22}, {1831587680, 23},
{ 813761492, 24}, { 138146428, 25}, { 337412092, 26},
{ 329155246, 27}, { 21320082, 28}, {1751867558, 29},
{1155173784, 30},
};
std::sort(std::begin(arr), std::end(arr),
[](entry a, entry b) { return a.hash <= b.hash; });
}
When I compile with gnu c++ compiler or any clang/llvm after 12.0.0, the program works fine. However, when I compiled it with clang version 12.0.0 (the default compiler shipped on my Mac laptop), it crashed inside of std::sort() as following:
$ g++ --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 12.0.0 (clang-1200.0.32.2)
Target: x86_64-apple-darwin21.3.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
$ g++ -g -std=c++11 bug.cc
$ ./a.out
Segmentation fault: 11
Also if I change it to use std::vector instead of fixed size array. The std::sort() will never return when compiled with clang 12.0.0
| Yes, the comparator is not a strict weak ordering which violates the preconditions of std::sort, resulting in undefined behavior.
For two arguments a and b (possibly identical), a strict weak ordering comp should never evaluate both comp(a,b) and comp(b,a) to true. In other words, it should model the behavior of the built-in <, not <=.
So in your code it should be <, not <=, to make it a strict weak ordering.
|
71,445,233 | 71,445,712 | Properly initialise a struct in C++, specifically addrinfo | I am wondering how I can properly initialise a struct in a "C++-way".
I am filling an addrinfo-structure with the relevant information for my hints (to use in getaddrinfo()).
Depending on how I initilise the struct, I will later on be able to get said addrinfo and let the network thing do its networky thing or fail with "unknown error".
The tutorial I took the code from (which was in C as far as I can tell) used this:
struct addrinfo hints;
memset(&hints, 0, sizeof hints);
This seems to be a valid way to initialise the struct of name "hints" with all zeroes. It makes my program work.
Although it appears that memset (if applied incorrectly) is evil, in this case we are filling a "POD"-object, so we should be safe. (https://stackoverflow.com/a/1976024/1968308)
The alternative I tried was using a initialiser (Can you call it a constructor?) as suggested in this answer: https://stackoverflow.com/a/54019987
struct addrinfo hints;
hints = addrinfo{};
(I am aware that I can abbreviate above two lines by initialising while declaring, but the declaration is in the header file for my base class whereas the initialisation happens in each inheriting class)
This produces an error (probably from getaddrinfo).
Since the only thing I changed was the initialisation of hints, the underlying mechanism seems to be the culprit. Can anyone please shed light on what is going on here?
| In C++ the initialization stacks. A class member and all base classes are initialized before the program enters the body of the constructor and will call the appropriate constructors to do so. Everything afterward, including inside the constructor's body, is assignment. To initialize a member you need to use either a default member initializer or a Member Initializer List in the class's constructor.
It's not important to this question, but explicitly initializing in the member initializer list is often superior to default initialization followed by assignment in the constructor body. If the default initialization is expensive, you won't want to perform it and then repeat a lot of the work later with the assignment.
addrinfo is a C structure, what we used to call a Plain Old Data type, and they are as simple as it gets. They require no specialized initialization and have no constructors and nothing they contain does either. So no initialization is performed. Their initial values are undefined and tend to reflect whatever happened to be in the memory location where the addrinfo now sits, basically garbage. As the asker found, this "garbage" is detrimental and needs to be cleared.
Simple code example:
class info_base
{
protected:
addrinfo info = addrinfo(); // default member initializer
// will fall back on zero initialization in this case
};
class info_tcp:public info_base
{
public:
info_tcp() // initialization includes default initialization of info_base
// which will use the default member initializer
{
info.ai_socktype = SOCK_STREAM;
info.ai_protocol = IPPROTO_TCP;
}
};
One of the advantages of being so simple is it can be aggregate initialized and as of C++20 we can do simple stuff like this (Note there is no noticeable performance advantage to this--far as I can see--but knowing you can do this could come in handy later)
class info_base
{
public: // note public now. Necessary to be an aggregate
addrinfo info = addrinfo();
};
class info_tcp:public info_base
{
public:
info_tcp(): info_base({.ai_socktype = SOCK_STREAM,
.ai_protocol = IPPROTO_TCP})
// Aggregate initialization of info_base via member
// Initializer List taking advantage of designated
// initializers added in C++20
{
}
};
Because info_base and its info member are being explicitly initialized, the default member initializer is skipped. I don't much like this one because it made info public and now any shmuck can mess with it, but it is really simple.
class info_base
{
protected:
addrinfo info;
info_base(int type,
int protocol): info {.ai_socktype = SOCK_STREAM,
.ai_protocol = IPPROTO_TCP}
{
}
};
class info_tcp:public info_base
{
public:
info_tcp(): info_base(SOCK_STREAM, IPPROTO_TCP)
{
}
};
Now info_base doesn't have a default constructor, you can add it back if you like, but the caller can specify the important parameters to use to initialize info and no one outside of the family can interact with addr.
|
71,445,432 | 71,478,695 | Why can compiler not optimize out unused static std::string? | If I compile this code with GCC or Clang and enable -O2 optimizations, I still get some global object initialization. Is it even possible for any code to reach these variables?
#include <string>
static const std::string s = "";
int main() { return 0; }
Compiler output:
main:
xor eax, eax
ret
_GLOBAL__sub_I_main:
mov edx, OFFSET FLAT:__dso_handle
mov esi, OFFSET FLAT:s
mov edi, OFFSET FLAT:_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEED1Ev
mov QWORD PTR s[rip], OFFSET FLAT:s+16
mov QWORD PTR s[rip+8], 0
mov BYTE PTR s[rip+16], 0
jmp __cxa_atexit
Specifically, I was not expecting the _GLOBAL__sub_I_main: section.
Godbolt link
Edit:
Even with a simple custom defined type, the compiler still generates some code.
class Aloha
{
public:
Aloha () : i(1) {}
~Aloha() = default;
private:
int i;
};
static const Aloha a;
int main() { return 0; }
Compiler output:
main:
xor eax, eax
ret
_GLOBAL__sub_I_main:
ret
| Compiling that code with short string optimization (SSO) may be an equivalent of taking address of std::string's member variable. Constructor have to analyze string length at compile time and choose if it can fit into internal storage of std::string object or it have to allocate memory dynamically but then find that it never was read so allocation code can be optimized out.
Lack of optimization in this case might be an optimization flaw limited to such simple outlying examples like this one:
const int i = 3;
int main()
{
return (long long)(&i); // to make sure that address was used
}
GCC generates code:
i:
.long 3 ; this a variable
main:
push rbp
mov rbp, rsp
mov eax, OFFSET FLAT:i
pop rbp
ret
GCC would not optimize this code as well:
const int i = 3;
const int *p = &i;
int main() { return 0; }
Static variables declared in file scope, especially const-qualified ones can be optimized out per as-if rule unless their address was used, GCC does that only to const-qualified ones regardless of use case. Taking address of variable is an observable behaviour, because it can be passed somewhere. Logic which would trace that would be too complex to implement and would be of little practical value.
Of course, the code that doesn't use address
const int i = 3;
int main() { return i; }
results in optimizing out reserved storage:
main:
mov eax, 3
ret
As of C++20 constexpr construction of std::string? Per older rules it could not be a compile-time expression if result was dependant on arguments. It possible that std::string would allocate memory dynamically if string is too long, which isn't a compile-time action. It appears that only mainstream compiler that supports C++20 features required for that it at this moment is MSVC in certain conditions.
|
71,445,466 | 71,445,602 | Simpler, portable way to iterate over all char values? | For a class I'm teaching I needed to write a piece of code to iterate over all possible char values. I wanted to do this in a way that was portable across different C++ implementations. This meant that
I can't assume char is signed or unsigned,
I can't assume char is eight bits,
I can't assume that sizeof(int) > 1,
I can't assume the int32_t etc. types exist,
I can't assume that integer overflow will not trap,
etc.
The best solution I came up with was the following unusual do ... while loop:
char ch = numeric_limits<char>::min();
process(ch);
do {
ch++;
process(ch);
} while (ch != numeric_limits<char>::max());
This approach works, but it feels pretty clunky to me. It intuitively makes sense that an approach like this might be needed because the number of increments is one more than the number of possible characters, but perhaps there's a fundamentally different approach available that more closely resembles a traditional for loop.
Is there a portable way to achieve this that's less clunky than this?
|
but perhaps there's a fundamentally different approach available that more closely resembles a traditional for loop.
Well, you can use an actual for loop:
#include <limits>
#include <iostream>
void process(char ch)
{
std::cout << static_cast<long>(ch) << ' ';
}
int main()
{
for ( char ch = std::numeric_limits<char>::min(); ; ++ch )
{
process(ch);
if ( ch == std::numeric_limits<char>::max() )
break;
}
std::cout << '\n';
}
|
71,445,682 | 71,445,909 | How can I add function to vector in this case? | I have this case, I can't figure it out.
I want to add a function in a vector of functions from an object to his child like this:
Child:
std::vector<void (*)(STATE oldState, STATE newState)> stateChangeHandlers;
void Digital_Output::addOnStateChangeHandler(void (*function)(STATE oldState, STATE newState)) {
this->stateChangeHandlers.push_back(function);
}
Parent / Owner
Digital_Outputs::Digital_Outputs(json outputsConf) { //nlohmann::json
int idx = 0;
for (auto output: outputsConf) {
Digital_Output *DO = new Digital_Output(output["pin"].get<int>(), idx);
//from here
DO->addOnStateChangeHandler([DO](STATE oldState, STATE newState) -> void*{ //note the capture
json j;
j["state"] = newState;
std::string jsonStr = j.dump();
mqtt::message_ptr pubmsg = mqtt::make_message(std::string(this->getTopicBase() + "/" + DO->getName()), &jsonStr); //note the this
});
//to here
this->addOutput(DO);
std::cout << "Added Output name: " << DO->getName() << " forced: " << BoolToString(DO->isForced()) << ":" << DO->getForcedValue() << " retain: " << BoolToString(DO->isRetain()) << ": " << DO->getRetainValue() << " comment: " << DO->getComment() << std::endl;
idx++;
}
}
VSCode tell me :
there is no proper conversion function from "lambda []void *(STATE oldState, STATE newState)->void *" to "void (*)(STATE oldState, STATE
newState)"
Next, functions stored are executed by:
void Digital_Output::_onStateChange(STATE oldState, STATE newState) {
for(std::vector<void (*)(STATE oldState, STATE newState)>::iterator it = std::begin(this->stateChangeHandlers); it != std::end(this->stateChangeHandlers); ++it) {
(*it)(oldState, newState);
}
}
| Your vector holds C-style function pointers. However, a capturing lambda cannot be converted to a function pointer (which is what the error message is trying to tell you), only a non-capturing lambda can. To store capturing lambdas, you will have to use std::function instead.
Also, your lambda returns a void*, but your vector expects functions that return void instead.
Also, your lambda is trying to use this without capturing it.
Try this instead:
Child
using stateHandlerFunc = std::function<void(STATE, STATE)>;
std::vector<stateHandlerFunc> stateChangeHandlers;
void Digital_Output::addOnStateChangeHandler(stateHandlerFunc function) {
stateChangeHandlers.push_back(function);
}
Parent / Owner
Digital_Outputs::Digital_Outputs(json outputsConf) { //nlohmann::json
int idx = 0;
for (auto output: outputsConf) {
Digital_Output *DO = new Digital_Output(output["pin"].get<int>(), idx);
DO->addOnStateChangeHandler(
[this, DO](STATE oldState, STATE newState) {
json j;
j["state"] = newState;
std::string jsonStr = j.dump();
mqtt::message_ptr pubmsg = mqtt::make_message(std::string(this->getTopicBase() + "/" + DO->getName()), &jsonStr);
}
);
addOutput(DO);
std::cout << "Added Output name: " << DO->getName() << " forced: " << BoolToString(DO->isForced()) << ":" << DO->getForcedValue() << " retain: " << BoolToString(DO->isRetain()) << ": " << DO->getRetainValue() << " comment: " << DO->getComment() << std::endl;
idx++;
}
}
void Digital_Output::_onStateChange(STATE oldState, STATE newState) {
for(auto&& handler : stateChangeHandlers) {
handler(oldState, newState);
}
}
|
71,445,684 | 71,452,950 | Copy one vector to another in for loop c++ | I need to implement a simple version of schedule for monthly tasks. For example payment of electricity bills, subscription fees for communications, etc. I want to implement a set of the following operations:
ADD(i,s) - assign a case with name s to day i of the current month.
DUMP(i) - Display all tasks scheduled for day i of the current month.
NEXT - Go to the to-do list for the new month. When this command is executed, instead of the current (old) to-do list for the current month, a (new) to-do list for the next month is created and becomes active: all tasks from the old to-do list are copied to the new list. After executing this command, the new to-do list and the next month become the current month, and work with the old to-do list is stopped. When moving to a new month, you need to pay attention to the different number of days in months:
if the next month has more days than the current one, the "additional" days must be left empty (not containing cases);
if the next month has fewer days than the current one, cases from all "extra" days must be moved to the last day of the next month.
Basically I have a problem with "NEXT" step. Namely copying from old vector month to the new one. Here is my code:
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
int main(){
//q - number of operations to perform.
//day - on which day to plan operation.
//to_do - what exactly to do on some day.
//operation - which kind of operation to perform.
vector<int>day_mon = {31,28,31,30,31,30,31,31,30,31,30,31};
//m_ind - month index
int m_ind = 0;
int q,day;
string operation;
string to_do;
//vector of the current month
vector<vector<string>> current_month(31);
cin >> q;
//for q operations:
for(int i = 0;i< q;i++){
cin >> operation;
if(operation == "NEXT"){
//insert days in the next months
vector<vector<string>> next_month = current_month;
int days_diff = day_mon[m_ind] - day_mon[m_ind+1];
//if next month has less days as current month, write days into the last day
//of the next months
if(days_diff > 0){
for(int i = 0; i < days_diff;i++){
next_month[day_mon[m_ind]-1].insert(end(next_month[day_mon[m_ind]-1]), begin(next_month[day_mon[m_ind]+i]), end(next_month[day_mon[m_ind]+i]));
}
}
} else if(operation == "ADD"){
cin >> day >> to_do;
current_month[day].push_back(to_do);
} else if(operation == "DUMP"){
cin >> day;
for(int i = 0; i < current_month[day].size(); i++){
cout << current_month[day][i] << ' ';
}
cout << endl;
current_month[day].clear();
}
}
return 0;
}
My problem is, that I don't know how to convert next_month to current_month(efficiently). How can it be done in c++?
| What you need is a set of vectors for each month. Either another vector if you want to number the months 0 - 11, or maybe a map of month name to vector. Lets go with the former
Also too many nested vector is hard to read. Lets define some types.
typedef vector<string> day; // the tasks for a day
typedef vector<day> month; // a month
ok so now lets create a year
vector<month> year(12);
for (int days : day_mon) {
year.emplace_back(month(days));
}
now lets pick january as our current month
month& current_month = year[0];
and add a task to jan 4th
current_month[4].push_back("do dishes");
now lets switch month
current_month = year[5];
.....
|
71,445,747 | 71,445,772 | Check if number is period of sequence in C++ | I need to check if number is a period of sequence.
EXAMPLE: { 1, 3, 1, 4, 2, 1, 3, 1, 4, 2, 1, 3 }
Periods are 5 and 10. Base period is 5 because it is the smallest period.
#include <iostream>
#include <vector>
int p=0;
int period(std::vector<double>v , int x)
{
int p = 0;
for (int i = 1; !p && i < v.size(); i++)
{
int j = 0;
while (j < v.size() - i && v[j] == v[j + i]) ++j;
if ( j + i == v.size() ) p = i;
}
if(p!=x)
return false;
return true;
}
int main()
{
std::vector<double> v = { 1, 3, 1, 4, 2, 1, 3, 1, 4, 2, 1, 3 };
std::cout << period( v,10 ) << '\n';
}
My code checks if number is equal to base period. How could I check if it is equal to any of the periods and in that case return true?
| The function can be defined the following way
bool period( const std::vector<double> &v , size_t n )
{
bool is_period = false;
if ( n < v.size() )
{
size_t j = 0;
while ( j < v.size() - n && v[j] == v[j + n]) ++j;
is_period = j + n == v.size();
}
return is_period;
}
Here is a demonstration program.
#include <iostream>
#include <vector>
bool period( const std::vector<double> &v, size_t n )
{
bool is_period = false;
if (n < v.size())
{
size_t j = 0;
while (j < v.size() - n && v[j] == v[j + n]) ++j;
is_period = j + n == v.size();
}
return is_period;
}
int main()
{
std::vector<double> v = { 1, 3, 1, 4, 2, 1, 3, 1, 4, 2, 1, 3 };
if (period( v, 5 )) std::cout << 5 << " is a period\n";
if (period( v, 10 )) std::cout << 10 << " is a period\n";
}
The program output is
5 is a period
10 is a period
|
71,445,766 | 71,445,840 | How to properly call getInsertData and getDeleteData in main? Am I doing this part correct? | I am working on a linked list assignment, however I am having trouble figuring out how to properly call getInsertData() (get values from cin and put them in a list) and getDeleteData() (delete numbers in the list) in main().
The instructions say something about defining an instance variable of NumberList, which I have already done I believe. If it's wrong, please correct me.
(There is more to this assignment, but I'm just showing the part I am having an issue with)
#include <iostream>
#include <iomanip>
#include <sstream>
#include "NumberList.h"
using namespace std;
NumberList *getInsertData(istream &, NumberList *);
NumberList *getDeleteData(istream &, NumberList *);
int main() {
// Write your code here according to the instruction . . .
int NumberList;
// Assuming a getInsertData function goes here?
cout << "Displaying list after inserting numbers" << endl;
// getInsertData
// Assuming a getDeleteData function goes here?
cout << "Displaying list after deleting numbers" << endl;
// getDeleteData
return 0;
}
My input is:
My intended output is supposed to look like this:
| You are declaring a variable named NumberList of type int. You need to instead declare a variable of type NumberList.
Try something more like this:
int main() {
NumberList myList;
cout << "Displaying list after inserting numbers" << endl;
getInsertData(cin, &myList);
cout << "Displaying list after deleting numbers" << endl;
getDeleteData(cin, &myList);
return 0;
}
|
71,446,211 | 71,447,231 | Why there are so many duplicates while loading vector | I need to load vector with infinite loop and to print it. Loading is over when 0 entered.
OUTPUT:
Enter numbers: 1 3 1 4 2 1 3 1 4 2 1 3 0
1 3 1 4 2 1 3 1 4 2 1 3
Code:
#include <iostream>
#include <vector>
int main()
{
std::vector<double>vektor;
double a;
for(;;)
{
std::cout << "Enter numbers: ";
std::cin>>a;
if(a!=0)vektor.push_back(a);
if(a==0)break;
}
for(double a:vektor)
std::cout << a << " ";
return 0;
}
I get this output:
Enter numbers: 1 3 1 4 2 1 3 1 4 2 1 3 0
Enter numbers: Enter numbers: Enter numbers: Enter numbers: Enter numbers: Enter numbers: Enter numbers: Enter numbers: Enter numbers: Enter numbers: Enter numbers: Enter numbers: 1 3 1 4 2 1 3 1 4 2 1 3
Could you explain me why there are so many duplicates of string "Enter numbers: "? If I load numbers one by one I wouldn't get any duplicate, but I need to load them all in one line like in example output. How could I modify this code to do that?
|
Could you explain me why there are so many duplicates of string "Enter numbers: "?
Because you are outputting Enter numbers on every loop iteration before reading a new number. Simply move that statement above the loop instead.
Also, your loop can be simplified. You are ignoring the error state of the stream after each >> call.
Try this:
#include <iostream>
#include <vector>
int main()
{
std::vector<double>vektor;
double a;
std::cout << "Enter numbers: ";
while(std::cin >> a && a != 0)
{
vektor.push_back(a);
}
for(double a: vektor)
std::cout << a << " ";
return 0;
}
|
71,446,686 | 71,986,985 | how to properly link mingw libraries using cmake and vcpkg? | I've getting used to simple cmake codes like this
cmake_minimum_required(VERSION 3.20)
project(trial VERSION 0.1.0)
set(CMAKE_CXX_STANDARD 20)
find_package(fmt CONFIG REQUIRED)
add_executable(trial main.cpp)
target_link_libraries(trial PRIVATE fmt::fmt)
however, it doesn't work on Mingw, the errors are something like this
[build] C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: CMakeFiles\trial.dir/objects.a(main.cpp.obj): in function `void fmt::v8::print<std::vector<int, std::allocator<int> >&>(fmt::v8::basic_format_string<char, fmt::v8::type_identity<std::vector<int, std::allocator<int> >&>::type>, std::vector<int, std::allocator<int> >&)':
[build] C:/PROGRA~1/Vcpkg/INSTAL~1/X64-WI~1/include/fmt/core.h:3208: undefined reference to `__imp__ZN3fmt2v86vprintENS0_17basic_string_viewIcEENS0_17basic_format_argsINS0_20basic_format_contextINS0_8appenderEcEEEE'
soI have to specify the .a and .dll.a lib.
cmake_minimum_required(VERSION 3.20)
project(trial VERSION 0.1.0)
set(CMAKE_CXX_STANDARD 20)
# find_package(fmt CONFIG REQUIRED)
include_directories("C:/Program Files/Vcpkg/installed/x64-mingw-static/include")
add_executable(trial main.cpp)
target_link_libraries(trial "C:/Program Files/Vcpkg/installed/x64-mingw-static/lib/libfmt.a")
# target_link_libraries(trial PRIVATE fmt::fmt)
# target_link_libraries(trial fmt::fmt-header-only)
This is kind of strange, what should I do to properly link mingw libraries using cmake and vcpkg?
Makefile and Makefile2
| I am rather late, but here it in case it helps:
Specifying library locations by hand shouldn't be required, the problem is somewhere else.
This error is at build time so it seems that it is passed cmake configuration without errors. Can you post the cmake conf log? perhaps if you tried specifying both --triplet= and --host-triplet= ?
|
71,446,914 | 71,446,946 | Vector of a class resetting member variables after for loop | I have an assignment where we need to use this basic structure of vectors and classes to learn about parent and child classes and polymorphism. Here is the code of the function I'm supposed to write:
void assignStudents(vector<Student*>& v) {
for (int i = 0; i < 5; i++)
{
cout << "Enter a study level: ";
string input;
cin >> input;
if (input == "graduate")
{
Graduate inputClass;
Student* inputParentClassPtr = &inputClass;
v.push_back(inputParentClassPtr);
v[i]->addToVector(input);
inputParentClassPtr = nullptr;
}
else if (input == "undergraduate")
{
Undergraduate inputClass;
Student* inputParentClassPtr = &inputClass;
inputParentClassPtr->addToVector(input);
v.push_back(inputParentClassPtr);
}
else
{
cout << "Please enter a valid response, either graduate or undergraduate" << endl;
i--;
}
}
for (size_t i = 0; i < v.size(); i++)
{
vector<string> studyLevels = v[i]->getStudyLevels();
size_t size = studyLevels.size();
for (int j = 0; j < size; j++)
{
cout << studyLevels[j];
}
}
}
I debug the program and every time the first for loop moves on to the next iteration, every member variable inside each object in my vector goes blank, but then when I add a new object into the vector, then call the addToVector() function they come back.
I added the bottom for loop to check if any editing is happening, and once I get to that bottom for loop, every member variable is empty again.
I have the Student class vector where I am adding Undergraduate and Graduate classes to. Every Student class has a protected vector inside called levels. I need to add the class to vector that holds all my objects, then edit the member variable vector to include the string representing the type of class it is.
Why do the member variables (levels) go blank every time it finishes an iteration of the for loop?
| I'll just focus on one part, as the same issue appears twice in your code.
{
Graduate inputClass; // create local student "on the stack"
Student* inputParentClassPtr = &inputClass;
v.push_back(inputParentClassPtr); // store address of student
v[i]->addToVector(input);
inputParentClassPtr = nullptr; // has no real effect
} // inputClass goes out of scope and is destroyed here
When the block ends, the local "stack" variables from that block are destroyed. That means the Graduate object is no longer valid, and the pointer you stored in v is now pointing at something unusable.
To fix that, you need to create the objects in dynamic memory.
You should change your vector to store std::unique_ptr<Student>, and create the objects using std::make_unique(), like this:
auto inputParentClassPtr = std::make_unique<Graduate>();
v.push_back(std::move(inputParentClassPtr));
But, if you can't do that, you will need to use new instead, like this:
Student* inputParentClassPtr = new Graduate();
v.push_back(inputParentClassPtr);
Either way, even though inputParentClassPtr is still destroyed at the end of the block, it is only a pointer and the Graduate object it pointed to is still alive.
If you use new, you'll then need to delete all the objects in the vector when you are done using them, or you'll have a memory leak. Using std::unique_ptr will handle that for you.
|
71,447,012 | 71,451,246 | How to determine when a socket receives EOF? (C++20 boost asio coroutines) | Consider a simple echo server:
#include <boost/asio.hpp>
#include <boost/asio/experimental/as_tuple.hpp>
#include <iostream>
#include <vector>
using boost::asio::awaitable;
using boost::asio::buffer;
using boost::asio::co_spawn;
using boost::asio::io_context;
using boost::asio::detached;
namespace ip = boost::asio::ip;
using boost::asio::use_awaitable;
// echo server
awaitable<void> serve_coroutine(ip::tcp::socket s) {
std::vector<unsigned char> data_buf;
data_buf.resize(4096);
for (;;) {
auto n = co_await s.async_read_some(buffer(data_buf, data_buf.size()),
use_awaitable);
auto ep = s.remote_endpoint();
std::cout << "R from " << ep.address().to_string()
<< " " << ep.port() << " L=" << n << std::endl;
while (n) {
size_t written = co_await s.async_write_some(buffer(data_buf, n), use_awaitable);
n -= written;
}
}
}
awaitable<void> listen_coroutine(ip::tcp::acceptor& acceptor) {
for (;;) {
auto [e, client] = co_await acceptor.async_accept(
boost::asio::experimental::as_tuple(use_awaitable));
if (!e) {
auto ex = client.get_executor();
// create working coroutine for data-transmission
co_spawn(ex, serve_coroutine(std::move(client)), detached);
} else {
std::cerr << "accept failed: " << e.message() << std::endl;
}
}
}
int main(int argc, char** argv) {
if (argc < 3) {
std::cout << "Usage: " << argv[0]
<< " <bind_address> <bind_port>" << std::endl;
return 1;
}
try {
io_context ctx;
// bind address
ip::tcp::endpoint listen_endpoint{ip::make_address(argv[1]),
static_cast<ip::port_type>(std::stoi(argv[2]))};
// create acceptor
ip::tcp::acceptor acceptor{ctx, listen_endpoint};
// add coroutine to execution queue
co_spawn(ctx, listen_coroutine(acceptor), detached);
// start executing coroutines
ctx.run();
} catch (boost::system::system_error& e) {
std::cerr << "boost system error: " << e.what() << std::endl;
} catch (std::exception& e) {
std::cerr << "E: " << e.what() << std::endl;
}
return 0;
}
(Build with g++ -std=c++20 or clang++ -stdlib=libc++ -fcoroutines-ts)
When the remote peer closes connection, co_await async_read_some never returns
It seems that boost io_service simply destroyed everything when closing connection
If I insert an object into serve_coroutine and track its constructor and destructor, I could find it destructed when closing connection
Then what's the proper way to handle connection-closing events? If you are developing a game, you need to clear the player's data and tell everyone that he's gone offline when you determine his connection is closed
| You can catch the exception:
for (;;) {
try {
auto n = co_await s.async_read_some(
buffer(data_buf, data_buf.size()), use_awaitable);
auto ep = s.remote_endpoint();
std::cout << "R from " << ep.address().to_string() << " "
<< ep.port() << " L=" << n << std::endl;
while (n) {
size_t written = co_await s.async_write_some(
buffer(data_buf, n), use_awaitable);
n -= written;
}
} catch (std::exception& e) {
std::cerr << "boost system error: " << e.what() << std::endl;
}
}
Which will print
boost system error: End of file [asio.misc:2]
Or you can use an alternative method to receive the error_code. You can see an example in your very listing:
auto [e, client] = co_await acceptor.async_accept(
boost::asio::experimental::as_tuple(use_awaitable));
So, e.g.:
for (;;) {
auto [ec, n] = co_await s.async_read_some(
buffer(data_buf, data_buf.size()),
boost::asio::experimental::as_tuple(use_awaitable));
auto ep = s.remote_endpoint();
std::cout << "R from " << ep.address().to_string() << " " << ep.port()
<< " L=" << n << " (" << ec.message() << ")" << std::endl;
if (!ec)
break;
while (n) {
size_t written =
co_await s.async_write_some(buffer(data_buf, n), use_awaitable);
n -= written;
}
}
Will display things like:
R from 127.0.0.1 51586 L=4 (Success)
R from 127.0.0.1 51586 L=1 (Success)
R from 127.0.0.1 51586 L=1 (Success)
R from 127.0.0.1 51586 L=1 (Success)
R from 127.0.0.1 51586 L=0 (End of file)
R from 127.0.0.1 51590 L=1 (Success)
R from 127.0.0.1 51590 L=1 (Success)
R from 127.0.0.1 51590 L=0 (End of file)
|
71,447,337 | 71,447,540 | Find sum of bits of a char | I need a queue of size about 8 booleans. Every push should destroy an item from the tail. This can be achieved by a char in the resource limited application.
However I only care about the sum of those "flags", not their individual status. How can I find the sum of the set bits of an 8 bit char?
| I come up with two methods.
A method is using a varible to count the sum, whenever you push, you maintain the varible, the change of the varible depends on what you push and what will pop.
Another method is an algorithm called "lowbit"
int lowbit(int x) {
return x & -x;
}
it will return the last 1 int the binary representation of the x.
So this can get the number of '1' in the binary representation of x.
for example, code like this.
int sum_of_1(int x) {
int res = 0;
while (x != 0) res++, x -= lowbit(x);
return res;
}
|
71,447,402 | 71,447,428 | Unable to access helper functions not in the namespace: undeclared identifier | I currently have a namespace set up like this:
SomeClass.h
namespace somenamespace {
class SomeClass {
public:
foo();
}
}
SomeClass.cpp
namespace somenamespace {
SomeClass::foo() {
somehelperfunction();
}
}
void somehelperfunction() {
std::cout << "hejflsdjf\n";
}
Without changing my header file, I cannot find a way to implement this helper function in a way which allows my class implementation to access the helper function. I was under the impression that as long as the helper function was in the same file I would be able to access it within the class implementation. But I get a "undeclared identifier" error when trying to build.
| Functions must be declared before called.
|
71,447,915 | 71,448,255 | Calculating Integrals | I am trying to calculate a integral in C++ and i am trying to use Simpson's 3/8 Rule (Also known as Simpson's second Rule) to calculate it. I wrote a program but it gives the wrong result. When i used the same rule on paper it works. I don't know what's wrong.
simpsons.cpp :
#include <iostream>
double f(int x) {
return 3*(x*x)+2*x+5;
}
float integralf(int lower_end, int high_end) {
int a = lower_end;
int b = high_end;
double area = 0.0;
area = ((b - a)/8)*(f(a) + 3*f((2*a+b)/3) + 3*f((a+2*b)/3) + f(b));
return area;
}
int main() {
int lower = -3;
int high = 5;
std::cout << integralf(lower, high) << std::endl;
return 0;
}
It gives 194 but answer is 208. I tried the same integral with Reimann sum technique and it gave 166.24.
reimann.cpp :
#include <iostream>
double f(int x) {
return 3*(x*x)+2*x+5;
}
double integral(double low_end, double high_end, double steps) {
double step = (high_end - low_end)/steps;
double area = 0.0;
double y = 0;
double x = 0;
for(int i=0;i<=steps;++i) {
x = low_end + i * step;
y = f(x);
area += y * step;
}
return area;
}
int main() {
int low_end = -3;
int high_end = 5;
int steps = 100;
std::cout << integral(low_end, high_end, steps) << std::endl;
return 0;
}
I don't know what is wrong. Is there a better way to calculate integrals in cpp? Every advice is welcome.
SOLUTION
Edit : I did it. Final version of code (simpsons.cpp) :
#include <iostream>
double f(double x) {
return 3*(x*x)+2*x+5;
}
float integralf(double lower_end, double high_end) {
double a = lower_end;
double b = high_end;
double h = (b - a)/3;
double area = 0.0;
area = ((3*h)/8)*(f(a) + 3*f((2*a+b)/3) + 3*f((a+2*b)/3) + f(b));
return area;
}
int main() {
int lower = -3;
int high = 5;
std::cout << integralf(lower, high) << std::endl;
return 0;
}
It gave the answer 208.
| Final version of code (simpsons.cpp) :
#include <iostream>
double f(double x) {
return 3*(x*x)+2*x+5;
}
float integralf(double lower_end, double high_end) {
double a = lower_end;
double b = high_end;
double h = (b - a)/3;
double area = 0.0;
area = ((3*h)/8)*(f(a) + 3*f((2*a+b)/3) + 3*f((a+2*b)/3) + f(b));
return area;
}
int main() {
int lower = -3;
int high = 5;
std::cout << integralf(lower, high) << std::endl;
return 0;
}
It gave the answer 208.
|
71,447,954 | 71,449,539 | C++ where intermediate value store? | My question can be pointed out regarding any programming language, but I wanna know regarding C++. I want to know where the intermediate value will store in C++? For example in the below code:
int func1(int);
int func2(int);
int func3(int);
int main(){
int a = 10;
int b = func1(func2(func3(a)));
cout<<b<<endl;
}
where the return value of func3 will be stored? What about func2? Will it store in CPU cache? or Ram?
Also, regarding the below code where the result of a*b will be stored? Or any intermediate values:
int main(){
int a = 10;
int b = 15;
int c = a*b+10*15;
cout<<c<<endl;
}
If it is compiler dependent, please explain regarding any compiler, especially GCC.
| Since you only declared the function I will assume they are in separate compilation units. So the compiler has to generate a function call for them. No inlineing or specialization of the functions possible (lookup link time optimization for how that isn't always true).
The way functions are called, arguments are passed and and returned is defined in the calling convention for the architecture and ABI you are targeting. So this isn't compiler specific as object files from different compilers are supposed to be compatible if they follow the same ABI.
So this governs what happens in each function call taken on it's own. In between the function calls the values can be stored on the stack or in registers but generally compilers try to do the minimal amount of work to get things from where one function returns them to where the next function expects them.
PS: If the compiler sees the definition of the functions then all bets are of. It can do whatever it likes as long as no change is observable by the program itself.
|
71,448,113 | 71,448,170 | OpenMp warning: ignoring #pragma opm parallel | I am getting this warning After I enter "g++ test1.c -fopenmp -Wall" with OpenMP directives on Windows:
wtest1.c:6: warning: ignoring #pragma opm parallel [-Wunknown-pragmas] #pragma opm parallel for private(x)
OpenMp doesn't seem to beworking. Waht should I do?
| It's #pragmaomp, not #pragmaopm
|
71,448,160 | 71,448,225 | ERROR: Cannot use parentheses when declaring variable with deduced class template specialization type | Good afternoon! Can someone explain why an error occurs when using a function where only one vector is passed?
Well, that is, there you can transfer constants without pain: 3, "asdf" 2.3, etc., but named variables are not. But for some reason a crossbreed is possible. Why is this suddenly possible?
#include <iostream>
#include <vector>
template<typename... Args>
struct func
{
func(const Args&... args)
{
std::cout << "ok" << std::endl;
}
};
template <typename... Args>
func(Args...) -> func<Args...>;
int main()
{
const std::vector<int> v { 1, 2, 3 };
func(v); // error is here
func(v, 3); // no error
func("asdf"); // no error
}
ERROR: Cannot use parentheses when declaring variable with deduced class template specialization type
example: https://godbolt.org/z/jdnce5Gdv
| clang's error message is oddly specific – g++ and vc++ only complain about conflicting declarations of v– but note that it says "declaring a variable".
Since func is a type, and you can have parentheses around the identifier in a variable declaration, and because of the "if it can be interpreted as a declaration, it is a declaration" rule,
func(v);
is equivalent to
func v;
declaring a variable v of the type func.
Here is a shorter example of the same situation:
#include <vector>
int main() {
int v = 0;
std::vector<int>(v);
}
|
71,448,227 | 71,455,218 | boost::asio::ssl::context crash during construction | I can't figure why the following instruction crashes:
boost::asio::ssl::context ctx(boost::asio::ssl::context::tlsv12);
I got the following error: Process returned -1073741819 (0xC0000005)
There is nothing more to catch regarding exceptions and AFAIK the boost documentation doesn't mention incompatibility issues between the boost and openssl versions.
my environment:
gcc from cygwin: C:\cygwin64\x86_64-w64-mingw32-g++.exe
linker options: -lws2_32 -lcrypto -lssl
using boost 1.78 (dl from website) and cygwin's openssl 1.1.1m packages
here is the minimal example:
#include <iostream>
#include <boost/asio/ssl/context.hpp>
int main()
{
std::cout << "before" << std::endl;
try {
boost::asio::ssl::context ctx(boost::asio::ssl::context::tlsv12);
} catch (...) {
std::cout << "catch" << std::endl;
}
std::cout << "after" << std::endl;
return 0;
}
output:
before
| The openssl cygwin package I installed is not a stable one, so the include and lib files are missing and I'm using the wrong ones (incompatible with the x86_64-w64-mingw32-g++ compiler). I've installed another stable version and the desired files are available now.
|
71,448,594 | 71,449,660 | What is causing the threads to execute slower than the serial case? | I have a simple function which computes the sum of "n" numbers.
I am attempting to use threads to implement the sum in parallel. The code is as follows,
void Add(double &sum, const int startIndex, const int endIndex)
{
sum = 0.0;
for (int i = startIndex; i < endIndex; i++)
{
sum = sum + 0.1;
}
}
int main()
{
int n = 100'000'000;
double sum1;
double sum2;
std::thread t1(Add, std::ref(sum1), 0, n / 2);
std::thread t2(Add, std::ref(sum2), n / 2, n);
t1.join();
t2.join();
std::cout << "sum: " << sum1 + sum2 << std::endl;
// double serialSum;
// Add(serialSum, 0, n);
// std::cout << "sum: " << serialSum << std::endl;
return 0;
}
However, the code runs much slower than the serial version. If I modify the function such that it does not take in the sum variable, then I obtain the desired speed-up (nearly 2x).
I read several resources online but all seem to suggest that variables must not be accessed by multiple threads. I do not understand why that would be the case for this example.
Could someone please clarify my mistake?.
| The problem here is hardware.
You probably know that CPUs have caches to speed up operations. These caches are many times faster then memory but they work in units called cachelines. Probably 64 byte on your system. Your 2 doubles are each 8 byte large and near certainly will end up being in the same 64 byte region on the stack. And each core in a cpu generally have their own L1 cache while larger caches may be shared between cores.
Now when one thread accesses sum1 the core will load the relevant cacheline into the cache. When the second thread accesses sum2 the other core attempts to load the same cacheline into it's own cache. And the x86 architecture is so nice trying to help you it will ask the first cache to hand over the cacheline so both threads always see the same data.
So while you have 2 separate variables they are in the same cache line and on every access that cacheline bounces from one core to the other and back. Which is a rather slow operation. This is called false sharing.
So you need to put some separation between sum1 and sum2 to make this work fast. See std::hardware_destructive_interference_size for what distance you need to achieve.
Another, and probably way simpler, way is to modify the worker function to use local variables:
void Add(double &sum, const int startIndex, const int endIndex)
{
double t = 0.0;
for (int i = startIndex; i < endIndex; i++)
{
t = t + 0.1;
}
sum = t;
}
You still have false sharing and the two threads will fight over access to sum1 and sum2. But now it only happens once and becomes irrelevant.
|
71,448,813 | 71,448,814 | How can I override the C++ compiler CMake uses for CUDA? | I'm using a CUDA version which does not support the GCC version installed on my system (my GCC is too new). I'm trying to build a repository which uses CMake for build configuration.
I know how to override the C++ compiler, traditionally:
export CXX=/path/to/other/compiler-binary
and CMake picks this up. I can also use cmake -DCMAKE_CXX_COMPILER. However, neither of these options work when compiling CUDA host-side code: CMake still has CUDA try to use my default GCC version on my system.
How can I tell it to use the alternative C++ compiler for CUDA?
Additional info:
CMake 3.22.1
On Devuan GNU/Linux Chimaera
| CMake will not (for now) default to using your CMAKE_CXX_COMPILER as the C++ compiler for CUDA host-side code; there's a different setting for that. Run your build configuration like so:
cmake -DCMAKE_CUDA_HOST_COMPILER=/usr/bin/g++-9
(replace the path with to your chosen C++ compiler of course)
|
71,448,963 | 71,449,259 | Why can't I put an Object into the start of a vector C++ | I'm writing a program in which I have to read complex numbers from the console into a vector, containing Complex objects. I have overwritten the >> operator in order to do this, but my vector gets indexed in the in the interval [1..vector.size()] instead of [0..vector.size()). I want it to go from zero, but I can't figure it out.
Here is a minimal reproducible example:
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
class Complex
{
private:
double real, im;
public:
Complex(double v_real = 0, double v_im = 0): real(v_real), im(v_im) {};
// getters
double getReal() const
{
return this->real;
}
double getImaginary() const
{
return this->im;
}
// setters
void setReal(double v_real)
{
this->real = v_real;
}
void setImaginary(double v_im)
{
this->im = v_im;
}
};
void operator>>(istream& i, Complex& c)
{
string line;
getline(i,line);
istringstream ss (line);
double temp_real;
double temp_im;
char oper;
ss >> temp_real;
ss >> oper;
ss >> temp_im;
if (oper == '-') temp_im *= -1;
char junk_i;
ss >> junk_i;
c.setReal(temp_real);
c.setImaginary(temp_im);
}
ostream& operator<<(ostream& o, Complex c)
{
if (c.getImaginary() > 0)
{
o<<c.getReal()<<'+'<<c.getImaginary()<<'i'<<endl;
}
else
{
o<<c.getReal()<<c.getImaginary()<<'i'<<endl;
}
return o;
}
int main(){
cout << "How many numbers will you create?" << endl;
int num_of_complex;
cin >> num_of_complex;
vector<Complex> v;
Complex temp_c;
for (int i = 0; i < num_of_complex; i++)
{
cin >> temp_c;
v.push_back(temp_c);
}
for (int i = 0; i < v.size(); i++)
{
cout << v[i] << endl;
}
}
Here is the input/output:
| The problem is that you're reading the first number with cin >> num_of_complex;, but this does not move the cursor to a new line! This means that the next call (i.e. the first call to your overridden >>) with getline will read only an empty line and try to convert nothing into a complex number.
You can fix this by ignoring everything in the input buffer until the next newline or to the end of the buffer after reading the first number. This is done with the method:
cin.ignore(numeric_limits<streamsize>::max(), '\n');
Full working example:
#include <iostream>
#include <vector>
#include <stream>
#include <limits>
using namespace std;
class Complex
{
private:
double real, im;
public:
Complex(double v_real = 0, double v_im = 0): real(v_real), im(v_im) {};
// Getters.
double getReal() const
{
return this->real;
}
double getImaginary() const
{
return this->im;
}
// Setters.
void setReal(double v_real)
{
this->real = v_real;
}
void setImaginary(double v_im)
{
this->im = v_im;
}
};
istream& operator>>(istream& i, Complex& c)
{
string line;
getline(i, line);
istringstream ss (line);
double temp_real;
double temp_im;
char oper;
ss >> temp_real;
ss >> oper;
ss >> temp_im;
if (oper == '-') temp_im *= -1;
char junk_i;
ss >> junk_i;
c.setReal(temp_real);
c.setImaginary(temp_im);
return i;
}
ostream& operator<<(ostream& o, Complex c)
{
if (c.getImaginary() > 0)
o << c.getReal() << '+' << c.getImaginary() << 'i' << endl;
else
o << c.getReal() << c.getImaginary() << 'i' << endl;
return o;
}
int main()
{
cout << "How many numbers will you create?" << endl;
int num_of_complex;
cin >> num_of_complex;
// Ignore everything in the input buffer until a new line or the end
// of the buffer.
cin.ignore(numeric_limits<streamsize>::max(), '\n');
vector<Complex> v;
Complex temp_c;
for (int i = 0; i < num_of_complex; i++)
{
cin >> temp_c;
v.push_back(temp_c);
}
for (int i = 0; i < v.size(); i++)
{
cout << v[i] << endl;
}
}
|
71,449,293 | 71,449,425 | Which one is faster? raw pointers vs thrust vectors | I am a beginner in Cuda, and I just wanted to ask a simple question that I could not find any clear answer for.
I know that we can define our array in Device memory using a raw pointer:
int *raw_ptr;
cudaMalloc((void **) &raw_ptr, N * sizeof(int));
And, we can also use Thrust to define a vector and push_back our items:
thrust::device_vector<int> D;
Actually, I need a huge amount of memory (like 500M int variables) to apply too many kernels on them in parallel. In terms of accessing the memory by kernels, is (when) using raw pointers faster than Thrust::vector?
| The data in thrust::device_vector is ordinary global memory, there is no difference in access speed.
Note however that the two alternatives you present are not equivalent. cudaMalloc returns uninitialized memory. Memory in thrust::device_vector will be initialized. After allocation it launches a kernel for the initialization of its elements, followed by cudaDeviceSynchronize. This could slow down the code. You need to benchmark your code.
|
71,449,580 | 71,449,783 | Return type is a template of templates | I have the following class:
class Inject{
template<template <class> class Daemon>
RETURNTYPE register_inj();
}
There are a number of implementation to this template function where the template arguments are explicitly specified one example is returning a class ServiceA which has one template argument that in this case is chosen to be class CacheA. The rule is that the template function will always have one template argument, but that template argument can have multiple template template arguments. E.g. ServiceB<typename A, typename B>
For serviceA the funtion template is implemented to:
template<>
auto register_inj<ServiceA<CacheA>>
{ impl... }
My question is what should RETURNTYPE be set to in the header file?
| I believe this question mixes two separate things.
The number of template arguments of the function template argument Daemon has nothing to with the return type. In fact, your specialisation for ServiceA indicates that you are not even asking for a template template argument. ServiceA<CacheA> is not a template - it is a normal type (which happens to be an instantiation of a template). Your function should therefore simply be declared as template <class Daemon> RETURNTYPE register_inj(). It will then work with ServiceA<CacheA> as well as with ServiceB<CacheB,ResolverB> (both of them are just types). You only need a template template parameter if you are instantiating that template within the body of your function.
In the header, the function return type could simply be declared to auto. That effectively declares the function to have a deduced return type.
However, you won't be able to use that function until it is defined (every call-site needs to know the return type of that function). You will therefore have to inline the function definition into your header as-well. If you want to avoid that, you will have to explicitly write the return type using meta-programming techniques, e.g. as follows:
// you need at least a forward definition of your services here,
// as well as the return types
template <typename Cache>
class ServiceA<Cache>;
template <typename Cache, typename Resolver>
class ServiceB<Cache,Resolver>;
class ServiceARegisterResult;
template <typename Resolver>
class ServiceBRegisterResult<Resolver>;
namespace detail {
template <typename Service>
struct register_inj_return_type {};
template <typename Cache>
struct register_inj_return_type<ServiceA<Cache>> : {
using type = ServiceARegisterResult;
};
template <typename Cache, typename Resolver>
struct register_inj_return_type<ServiceB<Cache,Resolver>> : {
using type = ServiceBRegisterResult<Resolver>;
};
}
class Inject{
template<class Daemon>
typename detail::register_inj_return_type<Daemon>::type
register_inj();
};
|
71,449,644 | 71,449,668 | Java equivalent of memcpy'ing a char[] to short | In Java or Kotlin, what would be the equivalent of this C++ code:
char* data = new char[size];
//read file to this array
short version = 0;
memcpy(&version, data, 2);
I tried this:
//java equivalent of the kotlin code below
Integer.parseInt(String(Arrays.copyOfRange(data, 0, 2)))
//kotlin:
data.copyOfRange(0, 2).concatToString().toInt()
but it doesn't work.
ByteBuffer doesn't work as well:
data[0] is 14
data[1] is 0
ByteBuffer.wrap(data).getShort() is 3584, memcpy is 14
data[2] is -28
data[3] is 45
data[4] is 0
data[5] is 0
ByteBuffer.wrap(data).getInt(2) is -466812928, memcpy is 11748
| Try using ByteBuffer:
byte[] data = new byte[size];
ByteBuffer buffer = ByteBuffer.wrap(data);
short version = buffer.getShort();
If needed you can also change the byte order
|
71,451,712 | 71,452,148 | Different behaviour in C++ std::vector construction with gcc and clang | In the example below I am expecting v to have 1 element, whos var will be of type Vector and will contain two "int" Variants 10 and 20.
This is the behaviour I can see with gcc.
With clang, 'v' contains two elements which are the two "int" Variants 10 and 20.
I think gcc's vector is created via the initializer_list constructor while clang's via the move constructor
Is this a bug in one of the compilers? Do I need to make the Variant's constructors explicit (which will force me to use it like Variant::Vector v{Variant{Variant::Vector{10, 20}}};. Is there any other way to avoid this issue if I want to keep the constructors non explicit?
Tried this code with all gcc and clang versions in https://wandbox.org/ and it behaves the same. Here are some links to try it directly: gcc, clang
#include <iostream>
#include <variant>
#include <vector>
struct Variant
{
using Vector = std::vector<Variant>;
Variant(const Vector & value)
{
var = value;
}
Variant(Vector && value)
{
var = std::move(value);
}
Variant(int value)
{
var = value;
}
std::variant<Vector, int> var;
};
int main()
{
Variant::Vector v{Variant::Vector{10, 20}};
std::cout << "v size: " << v.size() << ", index: " << v.at(0).var.index() << std::endl;
return 0;
}
| This is CWG 2137, which only gcc implements at present.
Clang bug: https://github.com/llvm/llvm-project/issues/24186
See also C++ constructor taking an std::initializer_list of size one - this is slightly more complicated in that the initializer list element is constructible from its argument (of the type being initialized), but the diagnosis is the same, and I can't do any better than T.C.'s description:
Clang implemented DR 1467 (brace-initializing a T from a T behaves as if you didn't use braces) but has yet to implement DR 2137 (on second thought, do that only for aggregates).
If you're OK changing your program syntax slightly, you could add another level of braces:
Variant::Vector v{{Variant::Vector{10, 20}}};
Or add parentheses:
Variant::Vector v({Variant::Vector{10, 20}});
|
71,451,719 | 71,451,820 | How can you generate a JSON compilation database using the CLI? | As described here one can generate a JSON compilation database using the UI of Visual Studio. Is it possible to do this in the CLI?
(The use case for this is to use the database with clangd to provide autocompletion to another editor)
| Apparently there is a powershell script that can be used like this:
clang-build -export-jsondb
If this generates a compile_commands.json file in the current directory of the projects in current directory.
|
71,451,996 | 71,452,190 | Why do I get "functions that differ only by return type cant't be overloaded" error when nothing is really overloaded? | I have following example of c++ code in visual studio 2022:
#include<iostream>
#include<string>
employee get_employee() {
employee out = { 1, "John"};
return out;
}
class employee {
public:
int id;
std::string name;
};
int main() {
std::cout << get_employee().name;
return 0;
}
But when I run it, I get compiler complaining about get_employee(), specifically that "functions that differ only by return type cant't be overloaded".
But why does it do so, if I dont have another get_employee() definition anywhere in my code?
I know that I can't create an instance of an class before I define the class itself, and moving get_employee() definition below employee class definition really solves the issue, but it doesn't explain why compiler says that "functions that differ only by return type cant't be overloaded" instead of saying that you "cant crate an istance of a class before defining the class itself", and I would like to know why.
| The problem here is fairly simple. You're trying to use employee before you've defined what it means. Move your definition of employee before the definition of get_employee.
#include<iostream>
#include<string>
class employee {
public:
int id;
std::string name;
};
employee get_employee() {
employee out = { 1, "John"};
return out;
}
int main() {
std::cout << get_employee().name;
return 0;
}
As to why the compiler gives a poor error message, my guess is that somehow or other the undefined name for the return type is tricking it into accepting the call to get_employee as it would have in old C, where a function without a declaration is presumed to return type int.
Then when it encounters the actual definition of get_employee, it has one entry already saying get_employee returns int and takes no arguments, and now sees what it's thinking is an attempt at overloading that also takes no arguments, but returns a client instead.
And that convinces it that what it's seeing is an attempt at overloading that uses the same parameter list (i.e., no parameters) but a different return type.
|
71,452,118 | 71,474,093 | Bazel: Tests cannot see library headers but app can | I have a pretty simple C++ project with Bazel that I am trying to implement gtest in and it has 3 BUILD files when including the test one. The problem I am having is that my headers in my library are visible to the app directory but not the test one and when I try to build my simple test it fails.
My project structure is:
- WORKSPACE
- app
|- BUILD
|- main.cpp
- lib
|- BUILD
|- foo
|- foo.hpp
|- foo.cpp
|- bar
|- bar.hpp
|- bar.cpp
- test
|- BUILD
|- lib_test.cpp
WORKSPACE contains the following to enable boost and gtest:
workspace(name = "my-app")
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
git_repository(
name = "com_github_nelhage_rules_boost",
commit = "fce83babe3f6287bccb45d2df013a309fa3194b8",
remote = "https://github.com/nelhage/rules_boost",
shallow_since = "1591047380 -0700",
)
load("@com_github_nelhage_rules_boost//:boost/boost.bzl", "boost_deps")
boost_deps()
git_repository(
name = "gtest",
remote = "https://github.com/google/googletest",
branch = "v1.10.x",
)
lib/BUILD contains rules for the library:
load("@rules_cc//cc:defs.bzl", "cc_library")
cc_library(
name = "app-lib",
srcs = glob(["*/*.cpp"]),
hdrs = glob(["*/*.hpp"]),
deps = [
"@boost//:log",
"@boost//:date_time",
"@boost//:filesystem",
"@boost//:program_options",
],
visibility = [
"//app:__pkg__",
"//test:__pkg__",
],
)
app/BUILD has the following to build the main binary:
load("@rules_cc//cc:defs.bzl", "cc_binary")
cc_binary(
name = "my-app",
srcs = ["main.cpp"],
deps = [
"//lib:app-lib",
],
copts = ["-Ilib"],
)
test/BUILD has the following in my attempts to get gtest working
cc_test(
name = "lib-test",
srcs = [
"lib_test.cpp",
],
copts = ["-Ilib"],
deps = [
"//lib:app-lib",
"@gtest//:gtest",
"@gtest//:gtest_main",
],
)
Now in my main.cpp I have included my library with the following includes:
#include "foo/foo.hpp"
#include "bar/bar.hpp"
and this builds my binary without issue however in my lib_test.cpp I have tried the same includes as well as full relative path include:
#include "lib/foo/foo.hpp"
#include "lib/bar/bar.hpp"
however when I try to run bazel test test:lib-test I get the following error:
lib/foo/foo.hpp: No such file or directory
Edit 1:
I'm using VSCode and have the following c_cpp_properties.json for include paths:
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**",
"${workspaceFolder}/lib/",
"/home/user/Projects/my-app/bazel-my-app/external/boost"
],
"defines": [],
"compilerPath": "/usr/bin/gcc",
"cStandard": "gnu17",
"cppStandard": "gnu++17",
"intelliSenseMode": "linux-gcc-x64"
}
],
"version": 4
}
| Instead of copts = ["-Ilib"], use includes = ["."] on the cc_library. That tells Bazel that anything which depends on that cc_library should get that directory on the include path, regardless of the relative path to get there.
Specifically, remove all the copts = ["-Ilib"], and change lib/BUILD to this:
load("@rules_cc//cc:defs.bzl", "cc_library")
cc_library(
name = "app-lib",
srcs = glob(["*/*.cpp"]),
hdrs = glob(["*/*.hpp"]),
includes = ["."],
deps = [
"@boost//:log",
"@boost//:date_time",
"@boost//:filesystem",
"@boost//:program_options",
],
visibility = [
"//app:__pkg__",
"//test:__pkg__",
],
)
|
71,452,848 | 71,452,874 | Error while trying to use a member class in a vector | I'm creating a container with files and directories, file and directory are a derived class from a parent class called resource, my problem appears while trying to use a member function of the directory class, find() searches for a name in the contents of a directory, this contents can either be file or directory find() works just fine when but when I try to use it in a directory inside a directory I get this
error: ‘class sdds::Resource’ has no member named ‘find’
here is the find() function ** the error comes from the second for loop while trying to use find in a Resource pointer to a directory.
Resource* find(const std::string& know, const std::vector<OpFlags>& ff =std::vector<OpFlags>()) {
auto result = std::find(begin(ff), end(ff), OpFlags::RECURSIVE);
std::string wh = "";
Resource* qq = nullptr;
if(result == std::end(ff)){
for (auto it = std::begin (m_contents); it != std::end (m_contents); ++it) {
if((*it)->name() == know){
return *it;
}
}
return nullptr;
}
else{
for (auto ip = std::begin (m_contents); ip != std::end (m_contents) || qq != nullptr; ++ip) {
while((*ip)->type()==NodeType::FILE){
++ip;
}
qq = (*ip)->find(*ip->name());
}
}
return qq;
}
name () returns the name of the member,
the OpFlags argument determines whether or not it should look inside the directories inside the directory,
NodeType returns the type of the content
this is the Directory class
class Directory: public Resource{
std::vector<Resource *> m_contents;
int ccount = 0;
public:
//stuff
};
this is the Resource class
class Resource {
protected:
// Stores the name of the resource
std::string m_name{};
// Stores the absolute path of the folder where the resource is located
std::string m_parent_path = "/";
public:
virtual void update_parent_path(const std::string&) = 0;
virtual std::string name() const = 0;
virtual int count() const = 0;
virtual std::string path() const = 0;
virtual size_t size() const = 0;
virtual NodeType type() const = 0;
virtual ~Resource() {}
};
as you can see Resource has no such find() member I know that, I also know this question might be hard to understand and I apologize for that, what I want to know is how to use find() in directories inside the directory, just to note: I can not modify the Resource class, the entirety of my code works but that part.
| Just remove (*ip)-> from qq = (*ip)->find(*ip->name());. find is not a member function.
qq = find((*ip)->name());
Perhaps the flags should be passed to the call
qq = find((*ip)->name(), ff);
|
71,453,109 | 71,453,186 | Is this Union Find really O(n) as they claim? | I am solving a problem on LeetCode:
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time. So for nums = [100,4,200,1,3,2], the output is 4.
The Union Find solution to solve this is as below:
class Solution {
public:
vector<int> parent, sz;
int find(int i) {
if(parent[i]==i) return i;
return parent[i]=find(parent[i]);
}
void merge(int i, int j) {
int p1=find(i);
int p2=find(j);
if(p1==p2) return;
if(sz[p1]>sz[p2]) {
sz[p1]+=sz[p2];
parent[p2]=p1;
} else {
sz[p2]+=sz[p1];
parent[p1]=p2;
}
}
int longestConsecutive(vector<int>& nums) {
sz.resize(nums.size(),1);
parent.resize(nums.size(),0);
iota(begin(parent),end(parent),0);
unordered_map<int, int> m;
for(int i=0; i<nums.size(); i++) {
int n=nums[i];
if(m.count(n)) continue;
if(m.count(n-1)) merge(i,m[n-1]);
if(m.count(n+1)) merge(i,m[n+1]);
m[n]=i;
}
int res=0;
for(int i=0; i<parent.size(); i++) {
if(parent[i]==i && sz[i]>res) {
res=sz[i];
}
}
return res;
}
};
This gets accepted by the OJ (Runtime: 80 ms, faster than 76.03% of C++ online submissions for Longest Consecutive Sequence), but is this really O(n), as claimed by many answers, such as this one? My understanding is that Union Find is an O(NlogN) algorithm.
Are they right? Or, am I missing something?
| They are right. A properly implemented Union Find with path compression and union by rank has linear run time complexity as a whole, while any individual operation has an amortized constant run time complexity. The exact complexity of m operations of any type is O(m * alpha(n)) where alpha is the inverse Ackerman function. For any possible n in the physical world, the inverse Ackerman function doesn't exceed 4. Thus, we can state that individual operations are constant and algorithm as a whole linear.
The key part for path compression in your code is here:
return parent[i]=find(parent[i])
vs the following that doesn't employ path compression:
return find(parent[i])
What this part of the code does is that it flattens the structure of the nodes in the hierarchy and links each node directly to the final root. Only in the first run of find will you traverse the whole structure. The next time you'll get a direct hit since you set the node's parent to its ultimate root. Notice that the second code snippet works perfectly fine, but it just does redundant work when you are not interested in the path itself and only in the final root.
Union by rank is evident here:
if(sz[p1]>sz[p2]) {...
It makes sure that the node with more children becomes the root of the node with less children. Therefore, less nodes need to be reassigned a new parent, hence less work.
Note: The above was updated and corrected based on feedback from @Matt-Timmermans and @kcsquared.
|
71,453,531 | 71,453,629 | SFML: image gets drawn and moves when I press a key, but doesn't move when I try to create a vector of them | The following code works... Basically when I press the spacebar, it draws a line, which continually moves in the Y direction on the screen.
// <Code that initializes window>
// set the shape
sf::CircleShape triangle(50, 3);
triangle.setPosition(300, 500);
sf::RectangleShape line;
// Start the game loop
while (window.isOpen())
{
window.clear(sf::Color::White);
// Process events
sf::Event event;
while (window.pollEvent(event))
{
// Close window: exit
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Space) {
line.setSize(sf::Vector2f(100,3));
line.setRotation(90);
line.setPosition(triangle.getPosition());
}
}
// Clear screen
window.clear();
line.move(0, -0.1);
window.draw(line);
window.draw(triangle);
// Update the window
window.display();
}
The issue is that I can only draw one line at a time, when I want to draw multiple moving lines everytime I press the spacebar button. Therefore I've tried to create a vector of line objects. However, while drawing the lines work, the lines don't move in the Y direction like the previous code.
// set the shape
sf::CircleShape triangle(50, 3);
triangle.setPosition(300, 500);
sf::RectangleShape line;
std::vector<sf::RectangleShape> laserStack;
while (window.isOpen())
{
window.clear(sf::Color::White);
// Process events
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Space) {
line.setSize(sf::Vector2f(100,3));
line.setRotation(90);
line.setPosition(triangle.getPosition());
laserStack.push_back(line);
}
}
// Clear screen
window.clear();
for (sf::RectangleShape l : laserStack) {
l.move(0, -0.3);
}
for (sf::RectangleShape laser : laserStack) {
window.draw(laser);
}
window.draw(triangle);
// Update the window
window.display();
}
(Picture below shows that the lines get drawn, however they don't move).
I don't understand why the first code works, and the line moves upwards but the second code doesn't work... It seems like they should be equivalent?
| When iterating over the lines, you create copies of the rectangles, and then move those copies, instead of the instances stored in the vector.
Use reference in your for-range loops.
for (sf::RectangleShape& l : laserStack) {
l.move(0, -0.3);
}
for (sf::RectangleShape& laser : laserStack) {
window.draw(laser);
}
|
71,453,536 | 71,453,603 | C++ edit function, return vector | May I ask how to modify the vector<CContact>& addContact(const CContact &c) method to pass this assert? Am I correct that the function should return a vector according to the assignment? I am adding reduced important functions.
class CTimeStamp
{
public:
CTimeStamp(int year, int month, int day, int hour, int minute, int second);
...
};
CTimeStamp::CTimeStamp(int year, int month, int day, int hour, int minute, int second)
: m_Year(year), m_Month(month), m_Day(day), m_Hour(hour), m_Minute(minute), m_Second(second)
{
}
class CContact
{
public:
CContact( CTimeStamp date, int numberFirst, int numberSecond );
private:
CTimeStamp m_Date;
int m_NumberFirst, m_NumberSecond;
};
CContact::CContact( CTimeStamp date, int numberFirst, int numberSecond )
: m_Date(date), m_NumberFirst(numberFirst), m_NumberSecond(numberSecond)
{
}
class CEFaceMask
{
public:
vector<CContact>& CEFaceMask::addContact(const CContact &c)
{
m_Db.push_back(c);
return m_Db;
}
private:
vector<CContact> m_Db;
};
int main ()
{
CEFaceMask test;
test . addContact ( CContact ( CTimeStamp ( 2021, 1, 12, 12, 40, 10 ), 123456789, 111222333 ) )
. addContact ( CContact ( CTimeStamp ( 2021, 2, 5, 15, 30, 28 ), 999888777, 555000222 ) );
}
| The way your methods are written, you cannot chain addContact() with another addContact() (or any other CEFaceMask method).
Either change the way you are calling addContact() the second time:
test.addContact ( CContact ( CTimeStamp ( 2021, 1, 12, 12, 40, 10 ), 123456789, 111222333 ) );
test.addContact ( CContact ( CTimeStamp ( 2021, 2, 5, 15, 30, 28 ), 999888777, 555000222 ) );
or change the signature of addContact() so that it can chain calls:
CEFaceMask& CEFaceMask::addContact(const CContact &c)
{
m_Db.push_back(c);
return *this;
}
|
71,453,555 | 71,454,661 | How do you convert an FString of delimited floats to a TArray<uint16> using Unreal C++ | Given an FString of "123.2222,446.4444,55234.2342" how do you convert this to a TArray of type uint16?
Current attempt is to parse the string into an array using
TArray<FString> Parsed;
HeightMapData.ParseIntoArray(Parsed, TEXT(","), false);
This seems to work well. Next is the problem of how do I convert this to uint16.
I am trying
const TArray<uint16*>& parsedArray = reinterpret_cast<const TArray<uint16*>&>(Parsed);
But it is not working. Error: Parent address is invalid for parsedArray
| You can't reinterpret_cast and pretend your array of strings is an array of integers. You need to convert each string to an integer in a new array:
TArray<uint16> intArray;
for (const auto& str : Parsed)
intArray.Add(FCString::Atoi(str));
Ref: https://docs.unrealengine.com/4.26/en-US/ProgrammingAndScripting/ProgrammingWithCPP/UnrealArchitecture/StringHandling/FString/
|
71,453,755 | 71,454,485 | Is it legal to use an unexpanded parameter pack as the type of a template template parameter's non-type template parameter? | gcc and clang disagree about whether the following code should compile:
template <typename... Args>
struct tuple {};
template <typename>
struct Test;
template <
typename... Types,
template <Types> typename... Outer, // XXX
Types... Inner
>
struct Test<tuple<Outer<Inner>...>> {};
template <long T> struct O1 {};
template <unsigned T> struct O2 {};
Test<tuple<O1<1>, O2<2>>> test;
clang accepts the code, deducing Types = {long, unsigned}, Outer = {O1, O2}, Inner={1L, 2U}. Structurally, this seems correct.
gcc rejects the code with a deduction failure. Interestingly, it does accept if O2 is changed to take a long non-type template parameter, which seems inconsistent to me. It suggests that Types can be expanded if Types = {long, long} but not if Types = {long, unsigned}.
However, it's not clear to me from the standard which compiler is correct. The core question is: on the line denoted XXX, is it valid to have a parameter pack as the type of the template template parameter's non-type template parameter? Should it expand the way that clang claims it does?
| It is not valid because:
a type parameter pack cannot be expanded in its own parameter clause.
As from [temp.param]/17:
If a template-parameter is a type-parameter with an ellipsis prior to its optional identifier or is a parameter-declaration that declares a pack ([dcl.fct]), then the template-parameter is a template parameter pack. A template parameter pack that is a parameter-declaration whose type contains one or more unexpanded packs is a pack expansion. ... A template parameter pack that is a pack expansion shall not expand a template parameter pack declared in the same template-parameter-list.
So consider the following invalid example:
template<typename... Ts, Ts... vals> struct mytuple {}; //invalid
The above example is invalid because the template type parameter pack Ts cannot be expanded in its own parameter list.
For the same reason, your code example is invalid.
|
71,454,015 | 71,454,148 | Passing Array into Function in C++ | I am currently working on a c++ program that uses the function. When I run the code, I am getting 3 error that
error: ‘userInput’ was not declared in this scope
error: ‘displaySum’ was not declared in this scope
error: ‘displayAverage’ was not declared in this scope
I'm not sure if the problem is the passing the array into function or I forgot to declare the function itself.
Here is the code.
#include <iostream>
using namespace std;
int main()
{
int numbers[10];
userInput(numbers, 10);
displaySum(numbers, 10);
displayAverage(numbers, 10);
return 0;
}
void userInput(int input[], int num)
{
for (int i = 0; i <= num; i++)
{
cout << "Enter #" << i <<": ";
cin >> input[i];
}
}
void displaySum(int averageResult[], int num, int sum)
{
for (int i = 0; i <= num; i++)
{
sum += averageResult[i];
cout << "\nSum:" << sum;
}
}
void displayAverage(int averageResult[], int num, int sum, int average)
{
for (int i = 0; i <= num; i++)
{
sum += averageResult[i];
average = sum / i;
cout << "Average:" << average;
}
}
| userInput(numbers, 10);
When your C++ compiler reaches this line it will have absolutely no idea what this mysterious function called userInput() is all about. The C++ program gets compiled in logical order, from beginning to the end, and this function has not been declared yet.
You will need to add a forward declaration at the beginning of the file:
void userInput(int input[], int num);
This declares the function. The actual definition of the function can remain where it is, after your main. This forward declaration tells your C++ compiler what this function is all about.
The same thing applies to the other functions in your program.
Additionally, your program has one more fatal bug that you will discover after fixing this compilation error:
for (int i = 0; i <= num; i++)
{
cout << "Enter #" << i <<": ";
cin >> input[i];
}
Your num array has 10 values, it is declared as int numbers[10];. In C++ array indexes begin with 0, not 1, so this means that the values in your array are numbers[0] through numbers[9].
If you work out, on paper and pencil, what the above for loop does: you will discover that it iterates with values of i ranging from 0 to 10. The loop's condition is i <= num, with num being 10, so 10 <= 10 is obviously true.
Subsequently this loop will attempt to initialize numbers[10] which does not exist, resulting in undefined behavior and a likely crash.
You will need to fix this bug here, and in your other for loops, which all have the same bug.
|
71,454,051 | 71,461,439 | What is clang version 10.0.7 for Android NDK? | I did
strings Image | grep -i clang
to my Poco M3 kernel extracted from an official ROM for Android 11 and got
Linux version 4.19.113-perf-ga223430d113c (builder@m1-xm-ota-bd331.bj.idc.xiaomi.com) (clang version 10.0.7 for Android NDK) #1 SMP PREEMPT Tue Feb 8 18:34:58 CST 2022 %s version %s (builder@m1-xm-ota-bd331.bj.idc.xiaomi.com) (clang version 10.0.7 for Android NDK) %s Linux version 4.19.113-perf-ga223430d113c (builder@m1-xm-ota-bd331.bj.idc.xiaomi.com) (clang version 10.0.7 for Android NDK) #1 SMP PREEMPT Tue Feb 8 18:34:58 CST 2022
But I don´t know what is clang version 10.0.7 for Android NDK). I download the 5 latest NDKs and the old ones use clang 9.x.x and then suddenly they jump to clang 11.x.x, without even using the 10.x.x. So, which clang was used to compile this kernel?
| Turns out it comes from Snapdragon's LLVM compiler https://developer.qualcomm.com/software/snapdragon-llvm-compiler-android
but the version 10.0.7 is not downloadable directly, it looks like you need to use the Qualcomm Package Manager, but it won't install on my ubuntu
|
71,454,585 | 71,454,637 | C++ [heap-use-after-free error] with referencing and push_back to vector | Below is my code and the execution result.
#include<vector>
#include<algorithm>
typedef struct Block {
int value;
Block(int value): value(value) {}
} Block;
int main() {
std::vector<Block> blocks;
blocks.emplace_back(1);
Block& block = blocks[0];
blocks.emplace_back(2);
std::max(1, block.value + 1);
return 0;
}
00699 ➤ g++ -std=c++11 -fsanitize=address question.cpp; ./a.out
=================================================================
==32403==ERROR: AddressSanitizer: heap-use-after-free on address 0x000106c00730 at pc 0x0001028fbd90 bp 0x00016d507310 sp 0x00016d507308
READ of size 4 at 0x000106c00730 thread T0
#0 0x1028fbd8c in main+0x300 (a.out:arm64+0x100003d8c)
#1 0x1029490f0 in start+0x204 (dyld:arm64e+0x50f0)
....
In my opinion, the combination of reference and emplace_back is wrong.
But why? What happened?
| because after emplace new element to blocks, may element's address have change (internal vector expanding operation )-> you save previous address is incorrect. to fix it you just change order of commands.
std::vector<Block> blocks;
blocks.emplace_back(1);
blocks.emplace_back(2);
Block &block = blocks[0];
std::max(1, block.value + 1);
show diffence address after each emplace_back
std::vector<Block> blocks;
blocks.emplace_back(1);
Block block = blocks[0];
cout << "&blocks[0]" << & blocks[0] << "\n";
blocks.emplace_back(2);
cout << "&blocks[0]" << & blocks[0] << "\n";
std::max(1, blocks[0].value + 1);
result:
&blocks[0]0xae1eb0
destructor ,value 1
&blocks[0]0xae2ee0
destructor ,value 1
destructor ,value 1
destructor ,value 2
https://godbolt.org/z/Y9xrv64aq
|
71,454,588 | 71,454,718 | MINSIGSTKSZ error after update in my manjaro linux | After I update my system with
sudo pacman -Syu
I can’t run my college coursework and get this error
> make
g++ -c -Wall -Wpedantic -Werror -Wextra -std=c++14 main_test.cpp
In file included from /usr/include/signal.h:328,
from catch.hpp:8034,
from main_test.cpp:2:
catch.hpp:10822:58: error: call to non-‘constexpr’ function ‘long int sysconf(int)’
10822 | static constexpr std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
| ^~~~~~~~~~~
In file included from /usr/include/bits/sigstksz.h:24,
from /usr/include/signal.h:328,
from catch.hpp:8034,
from main_test.cpp:2:
/usr/include/unistd.h:640:17: note: ‘long int sysconf(int)’ declared here
640 | extern long int sysconf (int __name) __THROW;
| ^~~~~~~
In file included from main_test.cpp:2:
catch.hpp:10881:45: error: size of array ‘altStackMem’ is not an integral constant-expression
10881 | char FatalConditionHandler::altStackMem[sigStackSize] = {};
| ^~~~~~~~~~~~
make: *** [makefile:33: main_test.o] Error 1
before I update the system, it’s run well without an error
How I can fix this? I really need to fix this for my coursework
| Suprisingly https://sourceware.org/git/?p=glibc.git;a=blob;f=NEWS;h=85e84fe53699fe9e392edffa993612ce08b2954a;hb=HEAD :
When _SC_SIGSTKSZ_SOURCE or _GNU_SOURCE are defined, MINSIGSTKSZ and SIGSTKSZ are no longer constant on Linux.
I fear this change will bite many programs. This is odd, because in POSIX MINSIGSTKSZ is a constant. It is a big change.
How I can fix this?
You can:
downgrade your system to previous glibc or use a system with previous glibc
or add something like the following before the definition of sigStackSize:
#undef MINSIGSTKSZ
#define MINSIGSTKSZ 16384
or fix catch.hpp so that it doesn't assume that MINSIGSTKSZ is a constant expression, and instead mallocs the alternate stack
or compile without _GNU_SOURCE and without _SC_SIGSTKSZ_SOURCE macros.
|
71,454,904 | 71,479,615 | Is there possible ways to print a returning stack from a fuction? | I try to use stack function to convert decimal number to binary number and return the stack function value to main function but I am not able to output the correct result to the screen.(sorry for my English)
#include<iostream>
#include<stack>
using namespace std;
stack<int> BinaryNum(int k, stack<int> st){
if(k >= 1){
st.push(k % 2);
return BinaryNum(k / 2, st);
}
if(k < 1)
return st;
}
int main(){
int k;
cin >> k;
stack<int> st;
BinaryNum(k,st);
while(!st.empty()){
cout << st.top();
st.pop();
}
}
| You discard the result of BinaryNum in main, and are passing copies of your stack around.
Either use the result
int main(){
int k;
cin >> k;
stack<int> st;
st = BinaryNum(k,st);
while(!st.empty()){
cout << st.top();
st.pop();
}
}
or take st by reference in BinaryNum
stack<int> BinaryNum(int k, stack<int> & st){
if(k >= 1){
st.push(k % 2);
return BinaryNum(k / 2, st);
}
if(k < 1)
return st;
}
|
71,455,206 | 71,455,269 | Why does shared_ptr<int> p; p=nullptr; compile? | Since the constructor of std::shared_ptr is marked as explicit one, so expressions like auto p = std::make_shared<int>(1); p = new int(6); is wrong.
My question is why does std::make_shared<int>(1); p = nullptr; compile?
Here is the aforementioned code snippet:
#include <memory>
#include <iostream>
int main()
{
auto p = std::make_shared<int>(1);
//p = new int(6);
p = nullptr;
if(!p)
{
std::cout << "not accessable any more" << std::endl;
}
p.reset();
}
Such code is seen at std::shared_ptr: reset() vs. assignment
| The raw pointer constructor is explicit to prevent you accidentally taking ownership of a pointer. As there is no concern taking ownership of nullptr the constructor taking std::nullptr_t is not marked explicit.
Note that this only applies to nullptr these other assignments of a null pointer might not work (depending on your compiler):
auto p = std::make_shared<int>(1);
p = NULL;
int * a = nullptr;
p = a;
|
71,455,365 | 71,455,384 | CPP: Capturing returned reference by value (i.e; in an lvalue of the referred type) | I tried this code to test how the returned reference gets propagated if captured by value:
int& give_rint()
{
std::unique_ptr<int> x(new int(32));
return *x;
}
int main()
{
int b = give_rint();
std::cout << b << std::endl; // prints 0
return 0;
}
I expected this to print 32, assuming that b would copy the value referred to by the returned type (which I again "assumed" would be alive for the line int b = give_rint();
While asking for an understanding of the series of events happening at above line. My question is also, can I somehow emulate the same behavior within a function, say something like(presented below doesn't work the same):
int main()
{
int b;
{
std::unique_ptr<int> x(new int(32));
int& c = *x;
b = c;
}
std::cout << b << std::endl; // prints 32;
return 0;
}
|
I expected this to print 32
When the function returns, unique pointer is destroyed, and the allocated memory is deallocated. The returned reference is always invalid.
When you indirect through the invalid reference by using it to initialise b, the behaviour of the program is undefined.
can I somehow emulate the same behavior within a function
Producing an invalid reference is challenging within a single function, but producing an invalid pointer is easy, and equally undefined. However, since the behaviour is undefined, there are no guarantees that it would be same undefined behaviour.
This is what clang says when the program is compiled:
warning: reference to stack memory associated with local variable 'x' returned [-Wreturn-stack-address]
return *x;
^
And this is what happens at runtime:
==1==ERROR: AddressSanitizer: heap-use-after-free
|
71,455,960 | 71,456,095 | Why program stops after constructor? | I am learning operator overloading and I read somewhere that when you assign a r-value to object then it creates a temporary object but this program stops after calling constructor for r-value.
Class.h
class Foo{
int *num;
public :
Foo(int x);
Foo& operator=(Foo &&rhs);
Foo& operator=(const Foo &rhs);
Foo(Foo &f);
Foo(Foo &&f);
void set(int x);
void show();
~Foo();
};
Class.cpp
#include <iostream>
#include "class.h"
#include <cstring>
Foo::Foo(int x){
num = new int;
*num = x;
std::cout << "Constructor for " << *num << std::endl;
};
Foo::~Foo(){
std::cout << "Destructor for " << *num << std::endl;
delete num;
}
void Foo::show(){
std::cout << *num << std::endl;
}
void Foo::set(int x){
*num = x;
std::cout << "INSIDE SETTER" << std::endl;
}
Foo& Foo::operator=(Foo &&rhs){
num = rhs.num;
rhs.num = nullptr;
return *this;
}
Foo& Foo::operator=(const Foo &rhs){
*num = *rhs.num;
return *this;
}
Foo::Foo(Foo &f){
num = new int;
*num = *f.num;
std::cout << "Copy constructor used " << std::endl;
}
Foo::Foo(Foo &&f)
: num{f.num}{
std::cout << "Move constructor used " << std::endl;
f.num = nullptr;
}
int main(){
Foo f1(10);
Foo f2(20);
Foo f3(30);
f1.show();
f2.show();
f3.show();
f1 = 60;
f1.show();
f2.show();
f3.show();
return 0;
}
Program stops after calling constructor for 60.
OUTPUT
Constructor for 10
Constructor for 20
Constructor for 30
10
20
30
Constructor for 60
[Done] exited with code=3221225477 in 1.458 seconds
It works when I use char *str instead of int *num
| Your problem is in the destructor. It tries to access *num, but move assignment operator sets num to nullptr.
Either guard logging against nullptr (there is no need to guard delete, as it is guaranteed to work properly on null pointers):
Foo::~Foo(){
if (num) {
std::cout << "Destructor for " << *num << std::endl;
} else {
std::cout << "Destructor for null pointer" << std::endl;
}
delete num;
}
Or use swap in move assignment and let rhs to delete it eventually(this also will fix memory leak: you never delete old value of num)
Foo& Foo::operator=(Foo &&rhs)
{
std::swap(num, rhs.num);
return *this;
}
Output for swap solution:
Constructor for 10
Constructor for 20
Constructor for 30
10
20
30
Constructor for 60
Destructor for 10
60
20
30
Destructor for 30
Destructor for 20
Destructor for 60
|
71,456,594 | 71,476,129 | Is there an efficient algorithm to redistribute a vector over processes based on how many elements each process has to give up or recieve? | I'm trying to redistribute an array (mesh-like) over a set of processes for load-balancing needs. My special requirement is that array elements should only be moved to the spatially adjacent processes as only the elements near the front between elements can be moved easily.
In the above example setup, all first three processes should donate elements to the last one:
# Process, Neighbors, Nbr. of Elements to move in/out
0, (1 2), -23
1, (0 3), -32
2, (0 3), -13
3, (1 2), +68
Currently, I'm planning to implement this with blocking Two-way MPI comms where transactions happen similarly to the following:
P0 sends 23 elements to P1
P1 sends 55 elements to P3 (Should only send 32 originally, + the 23 it got from P0)
P2 sends 13 elements to P3
So, I was wondering if there is a known (easily-parallelized through Two-way MPI comms preferably) algorithm to deal with this kind of situations.
Also, I've thought about "flatting out" the processes, and considering they form a simple ring. This simplifies things but has the potential of being noisy and may not scale well:
P0 sends 23 elements to P1
P1 sends 55 elements to P2 (Even though it's not one of its spacial neighbors)
P2 sends 68 elements to P3
Can Metis/ParMetis library handle this?
| I'll generalize your question: you are looking for an algorithm for load balancing where processes are connected through a graph, and can only move load to graph-connected processes. This algorithm exists: it's known as "diffusion based load balancing" and it was originally proposed by Cybenko. A simple web search will give you a ton of references.
|
71,457,335 | 71,460,305 | Where is a ordinary variable defined inside a __device__ function placed? | In CUDA, I understand that the variable would be placed in shared memory if it was defined as __ shared __ and one would be placed in constant memory if it was defined as __ constant __.Also, those being allocated memory using cudamalloc() are put in GPU global memory. But
where are those variable without prefixs like __ shared __ , __ constant __ and register placed? For example, the variable i as follow:
__device__ void func(){
int i=0;
return;
}
| Automatic variables, i.e. variables without memory space specification within the scope of functions, are placed in one of the following locations:
When optimized away:
1.1 Nowhere - if the variable isn't actually necessary. This actually happens a lot, since CUDA functions are often inlined, with some variables becoming copies of a variable in the calling function. Example (note the x from foo() in the compilation of bar() - completely gone).
1.2 Immediate values in the program's compiled code - if the variable's value is constant, and doesn't get updated, its value may simply be "plugged" into the code. Here's an example with two variables taking constants, which are replaced with the constant which is their sum.
When not optimized away:
2.1 Registers - If your variable can't be optimized-away, the better alternative is to keep it in a hardware register on (one of the symmetric multiprocessor core on) the GPU. Example (the variables x and y are placed in registers %r1 and %r2).
the best and most performant option, which the compiler
2.2 'Local' memory - The 'local memory' of a CUDA thread is an area in global device memory which is (in principle) accessible only by that thread.
Now, obviously, local memory is much slower to use. When will the compiler choose it, then?
The CUDA Programming Guide gives us the answer:
When the automatic variable is too large to fit in the register file for the current thread (each thread typically gets between 63 and 255 4-byte registers).
When the automatic variable is an array, or has an array member, which is indexed with a non-constant offset. Unfortunately, NVIDIA GPU multiprocessors don't support register indexing.
When the kernel is overusing its available quota of registers is already full with other variables or uses by the compiled code - even if the variable itself is very small. This is referred to as register spilling.
|
71,457,376 | 71,463,556 | How to specify style sheets for my classes in QT | I have a class that inherits from qframe, the "darksheetstyle" qss file is:
/* (dot) .QFrame fix #141, #126, #123 */
.QFrame {
border-radius: 4px;
border: 1px solid #455364;
/* No frame */
/* HLine */
/* HLine */
}
.QFrame[frameShape="0"] {
border-radius: 4px;
border: 1px transparent #455364;
}
.QFrame[frameShape="4"] {
max-height: 2px;
border: none;
background-color: #455364;
}
.QFrame[frameShape="5"] {
max-width: 2px;
border: none;
background-color: #455364;
}
the QFrame has no border, so I wrote my class qss in the same qss file:
BorderFrame {
border-radius: 4px;
border: 2px solid #455364;
/* No frame */
/* HLine */
/* HLine */
}
the cpp code is:
class ULTRA_PLOT_EXPORT BorderedFrame : public QFrame
{
Q_OBJECT
public:
explicit BorderedFrame(QWidget* parent) : QFrame(parent)
{
setParent(parent);
}
~BorderedFrame() override = default;
BorderedFrame(const BorderedFrame&) = delete;
BorderedFrame& operator=(const BorderedFrame&) = delete;
BorderedFrame(BorderedFrame&&) = delete;
BorderedFrame& operator=(BorderedFrame&&) = delete;
void paintEvent(QPaintEvent* event) override
{
QStyleOption opt;
opt.initFrom(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);//绘制样式
}
};
then, My own QFrame class still has no borders, how to fixed it ?
| This works as expected for me:
#include <QtWidgets>
class BorderedFrame : public QFrame
{
Q_OBJECT
public:
using QFrame::QFrame;
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
app.setStyleSheet("BorderedFrame { border-radius: 4px; border: 2px solid #ff0000; }");
BorderedFrame w;
w.show();
return app.exec();
}
#include "main.moc"
|
71,457,810 | 71,457,869 | Can we have an out of class definition for a class template that is a member of a class template | I know that the following snippet is valid:
template<typename T>
struct Custom
{
template<typename V> void func();
};
//valid
template<typename T>
template<typename V>
void Custom<T>::func()
{
}
But can we do the same for a class template instead of a member function template. Take for example,
template<typename T>
struct Custom
{ //declaration here
template<typename V> struct InnerCustom;
};
//can we define the class template `InnerCustom` outside?
template<typename T>
template<typename V>
Custom<T>::InnerCustom
{
};
My question is that can we have an out of class definition for the class template member InnerCustom just like we had for the member function template func? If so, how can i do that. Also, if not what is the reason for this difference.
| Yes, you can make an out of class definition for InnerCustom:
template <typename T>
template <typename V>
struct Custom<T>::InnerCustom { // note: `struct` added
// ...
};
|
71,457,938 | 71,458,628 | User input used as a parameter in a function c++ | While I understand why my code is wrong as well as brute-forcing my way around it, I'm wondering if there is way to do it the way I imagined it, so:
(just for context I'm making a simple game called Tower of Hanoi and this is the function I made that works when I manually input my stack as parameters)
void putOn(std::stack<int> &first, std::stack<int> &second){
if(first.empty()){
std::cout << "Your stack is empty, try again";
}else if(first.top() && second.empty()){
second.push(first.top());
first.pop();
}else if(first.top() < second.top()){
second.push(first.top());
first.pop();
}else if(first.top() > second.top()){
std::cout << "You can only put larger pieces on top." << std::endl;
}
}
Later in my code I'm using switch-case(for input, move towers, etc.) What I'm trying to do is translate my line putOn(x,y) into a variable input like so:
case 1:
char a,b;
std::cout << "Enter the tower u want to move from(x, y, z): ";
std::cin >> a;
std::cout << std::endl;
std::cout << "To(x, y, z): ";
std::cin >> b;
std::cout << std::endl;
// putOn(&a,&b);
// putOn(a,b);
break;
You can tell where I'm going with this and obviously I get get an error that says: candidate function not viable: no known conversion from 'char *' to 'std::stack<int> &' for 1st argument void putOn(std::stack<int> &first, std::stack<int> &second){
Is there a "python-like" way to do this where my user input directly translates character variables a and b into x,y or z as parameters, thank you for your time
| Try this:
std::map<char, std::stack<int>*> m = {{'x', &x}, {'y', &y}, {'z', &z}};
//...
putOn(*m[a], *m[b]);
|
71,458,228 | 71,459,364 | C++ : Calling a constructor from a class inside another class | I am working on a code which contains three classes: date, note, and student.
Date is made up of: int, int, int
Note is made up of: string, double, int
In ex3.h:
class student;
class date {
private:
//---------declaration of attributes-----
int j ; // day
int m ; // month
int a ; //year
// --------------
public:
date( int , int , int ) ;
date( const date & );
friend class student;
};
class note {
private:
//---------declaration of attributes-----
string matiere ;
double n ; // grade
int coef ; //coefficient
// --------------
public:
note( string , double , int ) ;
friend class student;
};
note::note(string mat , double no, int c ){matiere=mat;n=no;coef=c;}
date::date(int a1 , int b , int c){j=a1;m=b;a=c;}
Date and note work fine.
I want student to be made up of: string , string, date, note , note, note
Here is what I have written:
class student{
private:
//---------declaration of attributes-----
string nom ; // surname
string prenom ; // first name
date ddn ; //date of birth
note n1;
note n2;
note n3;
double mean;
// --------------
public:
student( string , string, date, note , note, note ) ;
student::student(string nomi, string prenomi, date di, note nte1, note nte2, note nte3 ){
nom=nomi;prenom=prenomi;ddn=di;n1=nte1;n2=nte2;n3=nte3;}
I tried to create a student with the following, in ex3.cpp:
date d1(12,10,2000);
note nt1("Math",20,2);
note nt2("Math",20,2);
note nt3("English",19.5,3);
student e1("Appleseed","Johnny",d1,nt1,nt2,nt3);
I get the following errors for the last line:
"error: no matching function for call to 'date::date()' "
"error: no matching function for call to 'note::note()' " (twice, since note is in the function twice)
I have tried changing the arguments of the last line, the arguments of the constructor... I'm out of ideas on how to make the student class functional.
Can anyone help me?
Thanks!
I have copied bits of my code, so I hope nothing is missing.
Original code is not English, so I translated it the best I could.
PS: I am new to stack overflow, so please bear with me as I ask my first question ^^'
| When you create an object of student type, the members of it are created with default constructors before the constructor of the student starts execution. So, the compiler tries to call the default constructor of the date type object, and then in the body of the student's constructor, it makes a call to the copy assignment. The same problem applies to the note objects. By defining a custom constructor, you deleted the default constructor of those classes.
The way to solve it is to use an initializer list. The code below would solve your problem.
student::student(string nomi, string prenomi, date di, note nte1, note nte2, note nte3)
: ddn(di), n1(nte1), n2(nte2), n3(nte3)
{
nom = nomi;
prenom = prenomi;
}
You can also explicitly say that you need the default constructor by typing the following in each class.
class date {
public:
date() = default;
/** ... **/
};
class note {
public:
note() = default;
/** ... **/
};
By the way, the indentation and the organization of your code make it hard to read. I suggest you work clean to learn more efficiently.
|
71,458,432 | 71,458,494 | Disambiguate template function specializations - value vs. reference | This question requires a bit of context - if you're feeling impatient, skip past the line break... I have a Vector-3,4 and Matrix-3,4 library defined in terms of template specializations; i.e., Vector<n> and Matrix<n> are defined in Matrix.hh, while non-trivial implementations (e.g., matrix multiplication, matrix inverse) have explicit specializations or instantiations in Matrix.cc for N = {3,4}.
This approach has worked well. In theory, an app could instantiate a Matrix<100>, but couldn't multiply or invert the matrix, as there are no implementation templates visible in the header. Only N = {3,4} are instantiated in Matrix.cc
Recently, I've been adding robust methods to complement any operation that involves an inner product - including matrix multiplications, matrix transforms of vectors, etc. Most 3D transforms (projections / orientations) are relatively well-conditioned, and any minor precision errors are not a problem since shared vertices / edges yield a consistent rasterization.
There are some operations that must be numerically robust. I can't do anything about how a GPU does dot products and matrix operations when rendering; but I cannot have control / camera parameters choke on valid geometry - and inner products are notorious for pathological cancellation errors, so the robust methods use compensated summation, products, dot products, etc.
This works fine for, say, Vector inner product in Matrix.hh :
////////////////////////////////////////////////////////////////////////////////
//
// inner product:
template <int n> float
inner (const GL0::Vector<n> & v0, const GL0::Vector<n> & v1)
{
float r = v0[0] * v1[0];
for (int i = 1; i < n; i++)
r += v0[i] * v1[i];
return r; // the running sum for the inner product.
}
float
robust_inner (const GL0::Vector<3> &, const GL0::Vector<3> &);
float
robust_inner (const GL0::Vector<4> &, const GL0::Vector<4> &);
////////////////////////////////////////////////////////////////////////////////
The implementations in Matrix.cc are not trivial.
I'm in more dubious territory when adding a robust method for [A]<-[A][B] matrix multiplication; perhaps the naming is not ideal:
template <int n> GL0::Matrix<n> &
operator *= (GL0::Matrix<n> & m0, const GL0::Matrix<n> & m1);
// (external instantiation)
GL0::Matrix<3> &
robust_multiply (GL0::Matrix<3> &, const GL0::Matrix<3> &);
GL0::Matrix<4> &
robust_multiply (GL0::Matrix<4> &, const GL0::Matrix<4> &);
There is a N = {3,4} implementation for the operator *= in Matrix.cc, but it relies on the naive inner product and is not robust - though typically good enough for GL / visualization. The robust_multiply functions are also implemented in Matrix.cc.
Now of course, I want the Matrix multiplication operator:
template <int n> GL0::Matrix<n>
operator * (GL0::Matrix<n> m0, const GL0::Matrix<n> & m1) {
return (m0 *= m1);
}
Leading me to the problematic definitions:
inline GL0::Matrix<3>
robust_multiply (GL0::Matrix<3> m0, const GL0::Matrix<3> & m1) {
return robust_multiply(m0, m1);
}
inline GL0::Matrix<4>
robust_multiply (GL0::Matrix<4> m0, const GL0::Matrix<4> & m1) {
return robust_multiply(m0, m1);
}
The call to robust_multiply(m0, m1) is ambiguous. Q: How can I force the LHS argument to be interpreted as a reference, ensuring a call to the previous function that modifies the (m0) argument. Obviously I can name robust_multiply as something else, but I'm more interested in utilizing the type system. I feel I'm missing something obvious in <utility> or <functional>. How do I force a call to the correct function?
(Sorry about the word count - I'm trying to clarify my own thinking as I write)
| You named robust_multiply wrong.
*= and * are fundamentally different operations. They are related, but not the same operation - different verbs.
Overloading should be used when you are doing the same operation on different nouns.
If you do that, then your problems almost certainly evaporate. Sensible overloads are easy to write.
In your case, you want to change between writing to an argument or not based on its l/r value category. That leads to ambiguity problems.
I mean, there are workarounds to your problem -- use std::ref or pointers, for example, or &, && and const& overloads -- but they are patches here.
Naming this in programming is hard. And here is a case were you should do that hard bit.
...
Now one thing you could do is bless the arguments.
template<class T>
struct robust{
T t;
explicit operator T&()&{return t;}
explicit operator T()&&{
return std::forward<T>(t);
}
// also get() methods
explicit robust(T&&tin):
t(std::forward<T>(tin))
{}
};
then override *= and * for robust wrapped matrices.
robust{a}*=b;
(have lhs must be robust to keep overload count down).
Now the verb is clear, I just dressed up the nouns.
But this is just an idea, and not use-tested.
|
71,458,568 | 71,465,607 | Turn relay on from Bluetooth for certain amount of seconds | I am working on two way communication between arduino and android phone. Currently everything is working, however I have couple of issues I have been trying to solve recently.
How I can ignite ignition for 5 seconds? I mean if IgnitionPin is on HIGH, run it for 5 seconds then automatically turn off? There is an easy way with delay, but it will not work in my case as don't want any other delays to slow up my script.
I am using Arduino Uno. I want to start my Arduino with pin in OFF position. Why pin 10 always turns ON then shuts down, even with digitalWrite(IgnitionPin, HIGH); I have tried other pins and they work fine -> turned OFF on start.
SoftwareSerial BTserial(12,13);
char choice;
const int loopDelay = 50;
int IgnitionPin = 10;
const long ignitionInterval = 5000;
int ignitionState = HIGH;
unsigned long previousMillis = 0;
void setup()
{
BTserial.begin(115200);
digitalWrite(IgnitionPin, HIGH);
pinMode(IgnitionPin, OUTPUT);
}
void loop()
{
if (BTserial.available())
{
choice = BTserial.read();
}
if( choice == 'm' )
{
ignitionState = HIGH;
digitalWrite(IgnitionPin, ignitionState);
ignitionCountTime = millis();
}
if (ignitionCountTime - previousMillis >= ignitionInterval) {
previousMillis = ignitionCountTime;
if (ignitionState == HIGH)
{
ignitionState = LOW;
}
digitalWrite(IgnitionPin, ignitionState);
}
delay(loopDelay);
}
EDIT:
SoftwareSerial BTserial(12,13);
char choice;
const int loopDelay = 50;
int IgnitionPin = 10;
unsigned long startTime;
unsigned long ignitionInterval = 30000;
unsigned long ignitionCountTime = 0;
void setup()
{
BTserial.begin(115200);
digitalWrite(IgnitionPin, HIGH);
pinMode(IgnitionPin, OUTPUT);
}
void loop()
{
if (BTserial.available())
{
choice = BTserial.read();
}
if( choice == 'm' )
{
digitalWrite(IgnitionPin, HIGH);
ignitionCountTime = millis();
}
if (ignitionCountTime - startTime >= ignitionInterval)
{
digitalWrite(IgnitionPin, LOW);
}
delay(loopDelay);
}
| #1
Use the TimerOne library or setup an ISR.
Run the ISR at, 5 times per second.
uint32_t timeout = 5 * 60;
uint8_t flag = 1;
digitalWrite (myPin, HIGH);
if (timeout && flag) {
timeout--;
} else {
digitalWrite (myPin, LOW);
flag = 0;
}
OR
by checking time elapsed since some specific point in time.
unsigned long startTime;
unsigned long interval = 60000;
const byte aPin = 13;
void setup()
{
pinMode(aPin, OUTPUT);
digitalWrite(aPin, HIGH);
}
void loop()
{
if (millis() - startTime >= interval)
{
digitalWrite(aPin, LOW);
}
}
EDIT
Arduino is a microcontroller, it can do only one thing at once.
SoftwareSerial BTserial(12,13);
char choice;
const int loopDelay = 50;
int IgnitionPin = 10;
uint32_t timeout = 5 * 60;
uint8_t flag = 0;
void setup()
{
BTserial.begin(115200);
pinMode(IgnitionPin, OUTPUT);
digitalWrite(IgnitionPin, LOW);
}
void loop()
{
if (BTserial.available())
{
choice = BTserial.read();
}
if (choice == "m")
{
timeout = 5 * 60; //modify this timeout.
flag = 1;
digitalWrite(IgnitionPin, HIGH);
}
else if ((timeout > 0) && (flag == 1))
{
timeout--;
}
else
{
digitalWrite(IgnitionPin, LOW);
flag = 0;
}
delay(loopDelay);
}
#2 - In setup you are running 'digitalWrite(IgnitionPin, HIGH);' this will make it high
just use pinMode(IgnitionPin, OUTPUT); for setting pin as output pin
void setup()
{
Serial.begin(115200);
Serial.println("Enter AT commands:");
BTserial.begin(115200);
sensors.begin();
// Set Pin as an output pin
pinMode(IgnitionPin, OUTPUT);
digitalWrite(IgnitionPin, LOW);
}
If you want IgnitionPin as LOW at each restart - use 'digitalWrite(IgnitionPin, LOW);' in setup() after pinMode call.
|
71,458,630 | 71,458,863 | GetSystemMetrics(SM_CYSCREEN); | Gives wrong value| but GetSystemMetrics(SM_CXSCREEN); gives correct value | I have a problem with GetSystemMetrics(SM_CYSCREEN); – the height this function returns is random each time I run the program but the width function, GetSystemMetrics(SM_CXSCREEN); gives the correct value.
Here is my code:
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
int MessageBoxPrintf(const wchar_t * szCaption, const wchar_t * szFormat, ...) {
wchar_t buffer[1024];
va_list v1;
va_start(v1, szFormat);
wchar_t* c = va_arg(v1, wchar_t*);
wsprintf(buffer, szFormat, c); //gives formated output to buffer
va_end(v1);
return MessageBox(NULL, buffer, szCaption, 0);
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) {
int cxScreen, cyScreen;
cxScreen = GetSystemMetrics(SM_CXSCREEN);
cyScreen = GetSystemMetrics(SM_CYSCREEN);
MessageBoxPrintf(TEXT("ScreenRes"), TEXT("The screen is %i pixels wide by %i pixels high"), cxScreen, cyScreen);
return 0;
}
This program basically just is a Format string Message box with the WinAPI and C++.
| The code you have posted shows (almost certainly) undefined behaviour, because of the incorrect way you handle the variadic argument list in your MessageBoxPrintf function.
In the wchar_t* c = va_arg(v1, wchar_t*); line, you are 'assuming' a single wchar_t argument – but, in your main function, you are passing two int arguments. This may or not produce meaningful results; – in your case, it seems that the first int argument is correctly interpreted by the subsequent call to wsprintf but the second is somewhat "lost in translation" (manifesting the aforementioned undefined behaviour).
To correctly handle that variadic argument list, you need to extract it, then pass it unprocessed to the vswprintf function, which can then properly interpret that argument list:
int MessageBoxPrintf(const wchar_t* szCaption, const wchar_t* szFormat, ...)
{
wchar_t buffer[1024];
va_list v1;
va_start(v1, szFormat);
vswprintf(buffer, 1024, szFormat, v1);
va_end(v1);
return MessageBox(NULL, buffer, szCaption, 0);
}
|
71,458,888 | 71,459,130 | how to split a string_view into multiple string_view objects without any dynamic allocations | The snippet below comes from this answer.
#include <string>
#include <vector>
void tokenize(std::string str, std::vector<string> &token_v){
size_t start = str.find_first_not_of(DELIMITER), end=start;
while (start != std::string::npos){
// Find next occurence of delimiter
end = str.find(DELIMITER, start);
// Push back the token found into vector
token_v.push_back(str.substr(start, end-start));
// Skip all occurences of the delimiter to find new start
start = str.find_first_not_of(DELIMITER, end);
}
}
Now for a buffer like this:
std::array<char, 150> buffer;
I want to have a sting_view (that points to the buffer) and pass it to the tokenizer function and the tokens should be returned in the form of std::string_views via an out parameter (and not a vector) and also it will return the numbers of tokens that were extracted. The interface looks like this:
size_t tokenize( const std::string_view inputStr,
const std::span< std::string_view > foundTokens_OUT,
const size_t expectedTokenCount )
{
// implementation
}
int main( )
{
std::array<char, 150> buffer { " @a hgs -- " };
const std::string_view sv { buffer.data( ), buffer.size( ) };
const size_t expectedTokenCount { 4 };
std::array< std::string_view, expectedTokenCount > foundTokens; // the span for storing found tokens
const size_t num_of_found_tokens { tokenize( sv, foundTokens, expectedTokenCount ) };
if ( num_of_found_tokens == expectedTokenCount )
{
// do something
std::clog << "success\n" << num_of_found_tokens << '\n';
}
for ( size_t idx { }; idx < num_of_found_tokens; ++idx )
{
std::cout << std::quoted( foundTokens[ idx ] ) << '\n';
}
}
I would appreciate it if someone could implement a similar tokenize function but for string_view that splits based on space and tab characters. I tried to write one myself but it didn't work as expected (didn't support the tab). Also, I want this function to stop the work and return expectedTokenCount + 1 if the number of tokens found in inputStr exceeds the expectedTokenCount. This is obviously more efficient.
Here is my dummy version:
size_t tokenize( const std::string_view inputStr,
const std::span< std::string_view > foundTokens_OUT,
const size_t expectedTokenCount )
{
if ( inputStr.empty( ) )
{
return 0;
}
size_t start { inputStr.find_first_not_of( ' ' ) };
size_t end { start };
size_t foundTokensCount { };
while ( start != std::string_view::npos && foundTokensCount < expectedTokenCount )
{
end = inputStr.find( ' ', start );
foundTokens_OUT[ foundTokensCount++ ] = inputStr.substr( start, end - start );
start = inputStr.find_first_not_of( ' ', end );
}
return foundTokensCount;
}
Note: The ranges library does not have proper support yet (at least on GCC) so I'm trying to avoid that.
|
I tried to write one myself but it didn't work as expected (didn't
support the tab).
If you want to support splitting with spaces and tabs, then you can use another overload of find_first_not_of:
size_type find_first_not_of(const CharT* s, size_type pos = 0) const;
which will finds the first character equal to none of characters in string pointed to by s.
So your implementation only needs to change find_first_not_of(' ') and find(' ') to find_first_not_of(" \t") and find_first_of(" \t").
Demo
|
71,459,523 | 71,459,649 | Does mulithreaded http processing with boost asio require strands? | In the boost asio documentation for strands it says:
Strands may be either implicit or explicit, as illustrated by the following alternative approaches:
...
Where there is a single chain of asynchronous operations associated with a connection (e.g. in a half duplex protocol implementation like HTTP) there is no possibility of concurrent execution of the handlers. This is an implicit strand.
...
However, in boost beast's example for a multithreaded asynchronous http server the boost::asio::ip::tcp::acceptor as well as each boost::asio::ip::tcp::socket get their own strand explicitly (see line 373 and 425). As far as I can see, this should not be necessary, since all of these objects are only ever going to be accessed in sequentially registered/running CompletionHandlers.¹ Precisely, a new async operation for one of these objects is only ever registered at the end of a CompletionHandler registered on the same object, making any object be used in a single chain of asynchronous operations.²
Thus, I'd assume that - despite of multiple threads running concurrently - strands could be omitted all together in this example and the io_context may be used for scheduling any async operation directly. Is that correct? If not, what issues of synchronization am I missing? Am I misunderstanding the statement in the documentation above?
¹: Of course, two sockets or a socket and the acceptor may be worked with concurrently but due to the use of multiple stands this is not prevented in the example either.
²: Admittedly, the CompletionHandler registered at the end of the current CompletionHandler may be started on another thread before the current handler actually finished, i. e. returns. But I would assume that this is not a circumstance risking synchronization problems. Correct me, if I am wrong.
| If the async chain of operations creates a logical strand, then often you don't need explicit strands.
Also, if the execution context is only ever run/polled from a single thread then all async operations will effective be on that implicit strand.
The examples serve more than one purpose.
On the one hand. they're obviously kept simple. Naturally there will be minimum number of threads or simplistic chains of operations.
However, that leads to over-simplified examples that have too little relation to real life.
Therefore, even if it's not absolutely required, the samples often show good practice or advanced patterns. Sometimes (often IME) this is even explicitly commented. E.g. in your very linked example L277:
// We need to be executing within a strand to perform async operations
// on the I/O objects in this session. Although not strictly necessary
// for single-threaded contexts, this example code is written to be
// thread-safe by default.
net::dispatch(stream_.get_executor(),
beast::bind_front_handler(
&session::do_read,
shared_from_this()));
Motivational example
This allows people to solve their next non-trivial task. For example, imagine you wanted to add stop() to the listener class from the linked example. There's no way to do that safely without a strand. You would need to "inject" a call to acceptor.cancel() inside the logical "strand", the async operation chain containing async_accept. But you can't, because async_accept is "logically blocking" that chain. So you actually do need to post to an explicit strand:
void stop() {
post(acceptor_.get_executor(), [this] { acceptor_.cancel(); });
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.