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 |
|---|---|---|---|---|
68,060,170 | 68,060,212 | Return type and argument type confusion in template | In this code, both return type and argument type of template is 'T' and I have returned boolean. And in argument, integer/float is passed. But my code is running successfully. How is that possible?
#include <iostream>
using namespace std;
template<class T>
T SearchInArray(T x[], T element) {
int j;
for(j=0;j<5;j... | bool is implicitly convertible to int, which in turn is convertible (implicitly) to a float, double, etc.
True is convertible to 1, while false is convertible to 0.
To prove that this is the case, change the int type of n and the int[] type of arr to std::string and std::string[], respectively. For me, this is what the... |
68,060,510 | 68,060,702 | How should I deallocate pointers allocated using new stored on std::stack | I have a program that allocates pointers on a stack.
#include <stack>
class A{};
int main()
{
std::stack<A*> pAs;
for (int i = 0; i < 100; i++)
{
A* pA = new A{};
pAs.push(pA);
}
}
The following is what I was doing.
while (!pAs.empty())
{
delete pAs.top();
p... |
How should I deallocate pointers allocated using new
By storing them in a smart pointer upon creation, and destroying that smart pointer when you desire to deallocate.
stored on std::stack
Example:
{
std::stack<std::unique_ptr<A>> pAs;
pAs.push(std::make_unique<A>());
} // the dynamic object is correctly d... |
68,060,789 | 68,060,820 | How does this code work? Specifically, the WorkerCompare struct | (Sorry if this question sounds vague. I'll add more information if needed.)
The task of the program is to simulate parallel processing. One solution I found on the internet contains this code which works but I don't know how. Specifically, why and how WorkerCompare was used:
class Worker {
public:
int id;
... |
priority_queue<Worker, vector<Worker>, WorkerCompare> pq;
I assume that this is the std::priority_queue from the standard library.
Priority queues work by comparing elements. That is what WorkerCompare is used for. It compares objects of type Worker.
|
68,061,026 | 68,061,038 | Why this code gives run time error on mid calculation? | int main() {
int start = 0;
int end = 2;
int ret1 = 0;
int mid = start + (end-start)/2;
ret1 = mid;
return ret1;
}
Why is this code giving runtime error?
https://ideone.com/iAdQO0
| A nonzero return code from main() indicates an error to many operating systems.
|
68,061,097 | 68,065,173 | _CtrlsValidHeapPointer(Block) | I'm new to c++ and I use c++ to learn data structure recently. I stuck when the error occurs, I've tried to debug but It's still confused me. So, this error is I try to implement two operations concatenate and merge, my terminal shows the result that seems to successful on logical. However, the error is coming in the n... | Yes it's the problem in destructor, after Concatenate, the c2 list has been appended to c1 list, the elements are destroyed twice, once in c1's destructor, the second time in c2's destructor. This is a memory issue that may lead to a crash.
I suggest fix it like this:
Transfer the ownership to c1, then we avoid destroy... |
68,061,883 | 68,062,037 | R-value reference to a temporary object does not segfault | I was going over this stack overflow answer and I was trying out my own things for my understanding. In the answer, the author says in the line
auto&& __range=exp;
Your exp creates a temporary object, then returns a reference to
within it. The temporary dies after that line, so you have a dangling
reference in the res... | If you build the program with address sanitizer, you get:
SUMMARY: AddressSanitizer: heap-use-after-free
At this line:
uto &&x = S().func();
Memory issues may not crash your program immediately, but they may crash a long-running program at other functions or other threads, lead to very weird crash scenarios.
|
68,061,993 | 68,062,076 | Can I use curl on c++ | Iam searching on internet to use curl on C++ but it got more Confused
I use curl to send message from my telegram bot like this
curl -F text="<My Text>" https://api.telegram.org/bot<Bot Token>/sendMessage?chat_id=<Chat id>
Is there any way I can do the same thing in c++
| Yes, you can run
curl -F text="<My Text>" https://api.telegram.org/bot<Bot Token>/sendMessage?chat_id=<Chat id> --libcurl example.c
This will generate a C code in the example.c that performs exactly your request. You can use this example in your C++ code.
/********* Sample code generated by the curl command line tool... |
68,062,096 | 68,062,161 | Sign & Unsigned Char is not working in C++ | In C++ Primer 5th Edition I saw this
when I tried to use it---
At this time it didn't work, but the program's output did give a weird symbol, but signed is totally blank And also they give some warnings when I tried to compile it. But C++ primer and so many webs said it should work... So I don't think they give the w... |
But C++ primer ... said it should work
No it doesn't. The quote from C++ primer doesn't use std::cout at all. The output that you see doesn't contradict with what the book says.
So I don't think they give the wrong information
No1.
did I do something wrong?
It seems that you've possibly misunderstood what the va... |
68,062,168 | 68,074,502 | Xplot for jupyter: "no template named decay_t in namespace std" | I am trying to include a couple xplot files, but I get this very cryptic error message:
Does anyone know why? I have already installed xplot and xeus-cling via conda.
| I have just solved this problem: it turns out std::decay_t is only supported in c++14 and later, so I switched my kernel to c++14 and now it works properly.
|
68,062,171 | 68,092,376 | QChart and using QGradients with accelerated OpenGL rendering | What is going wrong:
Currently my chart works completely fine, it has gradients, and single colored series for example:
This works fine, but when I enable openGL acceleration (for more performance) on the 3 series using fooSeries->setUseOpenGL(true) the graph turns into this:
As you can see the color for the gradient... | After more research, I seemed to have missed an important detail in the documentation:
Pen styles and marker shapes are ignored for accelerated series. Only solid lines and plain scatter dots are supported. The scatter dots may be circular or rectangular, depending on the underlying graphics hardware and drivers.
I s... |
68,062,704 | 68,062,756 | compiler error on calling derived class function using base class pointer which is not in base class | I am learning C++ virtual functions.
#include<iostream>
class Base{
virtual void fun(){
std::cout<<"Base\n";
}
};
class Derived:public Base{
void fun(){
std::cout<<"Derived\n";
}
virtual void fun1(){
std::cout<<"Derived 1 \n";
}
};
int main(){
Base* b=new Derived()... | You can't call any Base or Derived member functions from outside the classes since the functions are private. You need to make them public
The other problem:
fun1 is not a member of Base so you can't call fun1 via a base class pointer.
Two possible solutions:
Declare a pure virtual void fun1() = 0 in Base. Demo
Cast b... |
68,062,733 | 68,064,104 | How to handle exception for parallel std algorithms | I am executing n task using std::for_each and these tasks can be canceled. So for doing that I have a flag that is set to true if tasks to be canceled which in turn throws some exception in the task's code. And it works fine if I use normal std::for_each, but it aborts if I use any of std execution_policy. Is there a w... | You can't let an exception out of the callable you pass to for_each, under pain of std::terminate, as you have seen. But you don't need an exception, you know that you are cancelling tasks.
[&](const int& x) {
std::this_thread::sleep_for(2s);
if (toBeCancelled)
return;
}
Aside: in C++20 we get std::sto... |
68,062,969 | 68,063,584 | no operator "=" matches these operands error | i have tried this code. I'm getting the error
no operator "=" matches these operands -- operand types are:
std::pair<__gnu_cxx::__normal_iterator<const char *,
std::__cxx11::basic_string<char, std::char_traits<char>,
std::allocator<char>>>, __gnu_cxx::__normal_iterator<char *,
std::__cxx11::basic_string<char, std::char... | The immediate problem was identified by @S.M., position1 is not the correct type. There are other code improvements that you should consider:
Use automatic type deduction. @Someprogrammerdude suggests using auto position1 ... which is available in C++11 onwards.
@Evg suggests you use std::begin() and std::end() instea... |
68,063,509 | 68,066,669 | NodeJS Addon build error C3861: '_alloca': identifier not found | When trying to build a simple node addon with boost,the compiler fails with this error
absolute\path\to\boost_1_76_0\boost_1_76_0\boost\asio\detail\impl\socket_ops.ipp(2481,34): error C3861: '_alloca': identifier not found [absolute\path\to\project\src\nativeSimpl
e\build\nativesimple-native.vcxproj]
absolute\path\to\b... | boost\asio\detail\impl\socket_ops.ipp doesn't include <malloc.h> which is the required header for the _alloca function.
You can work around this by including <malloc.h> in your code before including the boost headers.
You should raise a bug with boost asio with a full example of how to reproduce the issue to get this f... |
68,063,726 | 68,064,063 | c++ returning reference actually returns garbage value | I'm learning OpenGL with scarce C++ background. Please see below code snippet which I minimalized my problem as possible as I can:
#include <glm/glm.hpp>
class TestObj
{
private:
glm::mat4 t;
public:
TestObj()
{
t = glm::mat4(1);
}
const glm::mat4& GetT()
{
return t;
}
... | As you noted, GetT()[3] is a glm::vec4, so it needs conversion to got glm::vec3.
So your code is mostly equivalent to
const glm::vec3& GetPos()
{
const glm::vec4& vec4 = GetT()[3];
glm::vec3 vec3{vec4}; // Conversion
return vec3;
}
Returning dangling pointer.
|
68,064,119 | 68,064,453 | Undefined Behavior When Serializing filesystem::path Object | I have the following code that works perfectly fine when testing the serializing and deserializing of the filesystem::path object:
#include <filesystem>
#include <array>
#include <iostream>
int main() {
namespace fs = std::filesystem;
std::array<char, sizeof(fs::path)> arr;
fs::path currentPath("./Icon");
... | This answer is for libcxx std::filesystem (Clang) but I assume other STL implementations have the same:
a fs::path object only has one field: string_type __pn_;
the operator= simply copies or moves the string: __pn_ = __p.__pn_;.
That means that when you do currentPath = fs::path("./Icon");, the existing string is fr... |
68,064,190 | 68,064,798 | How to get exact result with unsigned long multiplication? | I am struggling with strange result for basic program.
I checked tutorialspoint site and it says unsigned long is 8byte.
I am multiplying unsigned long and unsigned int.
And it seems that multiplying result does not exceeds the maximum value of unsigned long(18,446,744,073,709,551,615).
But I get 56557 instead of 85,... | The width of unsigned long depends on the C or C++ implementation. The C standard and the C++ standard only require it to be at least 32 bits.
To calculate sizes of objects, include <stddef.h> in C or <cstddef> in C++ and use the size_t type in C or std::size_t in C++. It is intended to be a type suitable for working w... |
68,064,576 | 68,065,003 | How to safely allow single argument templated constructor without using explicit? | I have a Value class which I use for wrapping and converting basic types.
class Value {
public:
template <typename T>
Value(const T &value) : value_(StringMaker<T>(value)) {} // Not marked explicit
// Example -> Convert to String
std::string AsString() const;
// Example -> Convert to Int
int AsInt(bool *... |
Thus, is there a safe way to keep the static analysis tools happy [...]
Yes, make the converting constructor explicit ;)
You can only disable or ignore the warning or make the constructor explicit. Though the warning exists for a reason, implicit conversions can be a source of confusion. Because Values constructor is... |
68,064,868 | 68,064,948 | How to implement the header of a function such that the following code works? | vector<int> v1{4, 2, 1, 6, 3, -4};
assert(fct<int>(v1) == 6);
vector<int> v2;
try {
fct<int>(v2);
assert(false);
}
catch (exception& exc) {
assert(true);
}
vector<double> v3{2, 10.5, 6.33, -100, 9, 1.212};
assert(fct<double>(v3) == 10.5);
vector<string> v4{"y", "q", "a", "m"};
assert(fct<string>(v4) ==... | I guess you meant the function declaration (not "header"), so that's what it should look like:
template<typename T>
T fct(const std::vector<T>& v);
PS:
You should not name that function "fct", but give it an appropriate name, like "max_element" or something (or use the function std::max_element provided by the standa... |
68,064,984 | 68,074,150 | What is preventing compile time evaluation of this constexpr function? | I'm working on a class for representing a set of hardware pins of a microcontroller (STM32). The selected pins may be discontinuous on the port, but they are assumed to be ordered. For example, if this PortSegment object is created to represent PA2, PA3 & PA6 pins, I want to be able to make an assignment like segment =... | You have set optimisation to level 1 in Godbolt! Try -O3 instead of -O1.
|
68,065,566 | 68,065,806 | When should I return TRUE and when FALSE on DialogProc | I had another SO question and people there helped me solve an issue. I don't understand what DialogProc is supposed to return on each case. What does DialogProc returning TRUE mean? How does it compare to FALSE? What's the difference?
MSDN states that there is no return value.
INT_PTR CALLBACK DialogProc(HWND hWnd, UIN... | The basic idea is that you have a default: return FALSE;, while each case: returns TRUE. But Windows doesn't read your code. Windows doesn't even require your code to be written in C++, and other languages may implement the same idea in other ways. That's why the documentation describes the behavior, not how you should... |
68,065,629 | 68,065,973 | Dynamic array creation without default constructor | Disclaimer: I already know that raw arrays are not first class elements in C++ and that in many places, we are expected to replace them with vectors. But I still hope an other way...
Context:
I am trying to build a multi-dimensional container library using contiguous data instead of vectors of vectors. A simple analogy... |
I am unsure of how to correctly use that and whether it is compatible with new[] and delete[].
It isn't compatible with new T[], but it is compatible with new char[].
template <typename T>
class Holder
{
size_t sz; // size of the array
bool owning; // true if the array should be deleted
T* d... |
68,066,670 | 68,066,873 | How to declare a concept for binary operations properly | I'm implementing the generic fast power algorithm from the elements of programming book.
This is a very naive version
template <typename R, typename I, typename Op>
requires std::integral<R> && std::integral<I> && std::is_binary_op<Op, R, I, I>
R power(I acc, I a, I n, Op op) {
while (n-- != I{0}) {
acc = op(acc,... |
Any idea how to fix this ?
Why there are no concepts in the standard library checking if a function is unary or binary, etc...
There is a trait, for particular argument types. You shouldn't add a concept to namespace std.
template <typename Op, typename Arg1, typename Arg2>
concept binary_op = std::is_invocable_v<Op,... |
68,066,689 | 68,066,805 | WaitOnAddress doesn't wake after the variable changed | According to WaitOnAddress doc, WaitOnAddress should block until the value at the given address changes.
#include <synchapi.h>
#include <thread>
#include <chrono>
using namespace std::chrono_literals;
#pragma comment(lib,"Synchronization.lib")
namespace __monitorVaribleChangeTest
{
void startAThreadToWaitAVaribl... | According to the documentation that you linked, you will need to signal that the value at the given address has changed, by calling either WakeByAddressSingle or WakeByAddressAll:
The address on which to wait. If the value at Address differs from the
value at CompareAddress, the function returns immediately. If the
va... |
68,066,744 | 68,066,855 | I get an illegal reference and a type name not allowed, why? | I have come futher in my project but alas im stuck again.
I've got the game loop running from 1 class now.
I'm trying to get the player variables to update in the player class upon a key press(see line 57 to 68 in game.cpp).
These variables are saved in private variables and then pushed into public referneces.
Then the... | Give GameFunction a reference to the player and let it store it:
// Inside the GameFunction class
GameFunction(Player& player) : p(player) {}
Player& p;
Then you can access members of p inside OnUserUpdate:
bool OnUserUpdate(float fElapsedTime) override {
Fill(0, 0, ScreenWidth(), ScreenHeight(), L' ');
Fill(... |
68,066,939 | 68,067,020 | Base and derived objects held in vector of base class type get sliced | So I've just learned basics of vector template and I'm trying to make a vector holding both, objects of Base and objects of Derived classess. But derived objects get sliced (only the baseVariable is printed although it should also print DerivedVariable. So i have two questions, first:
Is creating a new object with user... | There is no slicing in your code. You forgot to declare Base::display as virtual, hence calling display on a Base* will call Base::display.
class Base
{
protected:
string baseVariable_;
public:
virtual void display() {
// ^^----------------------------------------------- !!!
cout << "BaseVar: " << b... |
68,066,985 | 68,081,281 | How to write specific time interval of GstSamples (RTP over UDP H264 packets)? | The Setup
I am sending H.264 encoded packets over RTP UDP via the following Gstreamer CLI pipeline:
gst-launch-1.0 videotestsrc is-live=true ! video/x-raw,framerate=30/1 ! timeoverlay ! videoconvert ! x264enc ! h264parse ! rtph264pay pt=96 ! udpsink host=127.0.0.1 port=5000
Note that timeoverlay element will come in ha... | So problem actually relates to the key frames as the recording pipeline will only start writing the video from the first key frame it finds, all the delta frames are discarded. And the reason why I miss a lot of seconds in the requested interval is because of the configuration of the sender pipeline sending one key fra... |
68,067,105 | 68,067,914 | Make users of my library to call function with primitive values and class names as well | I have got an untypical requirement. I'm writing a setup library function, which should be called with only constant values and class names. I made something like this:
template <unsigned index, class layerClass, typename...Args>
void setup_layers() {
//add layer
//recursively call yourself
setup_layers<... | Here's one option to resolve the ambiguity: You could rename the function doing the actual setup implementation. I've called it setup_impl:
template <unsigned index, class layerClass>
void setup_impl() {
//add layer
std::cout << index << '\n';
}
template <unsigned index, class layerClass, class... Args>
void s... |
68,067,280 | 68,068,243 | How to get resizeEvent-already-executed? | I have a QDialog-inherited class and one of its sub-window is initialized on resizeEvent like this.
void OpenGLWindow::resizeEvent(QResizeEvent *event) {
QWindow::resizeEvent(event);
// initialize on first call
if (m_context == nullptr)
initOpenGL();
resizeGL(width(), height());
}
Because O... | As @pptaszni mentioned in his comment, initOpenGL() doesn't look like it needs size information. So first I would reconsider the design.
As for the question:
The resize event is scheduled after the show and delivered when GUI events are processed. That's after your function returns.
You can simply delay the call by pos... |
68,067,612 | 68,068,702 | What is the difference between the split_view and the lazy_split_view in C++? | I have read the latest draft where lazy_split_view is added.
But later on, I realized that split_view was renamed into lazy_split_view, and the split_view was renewed.
libstdc++ also recently implemented this by using GCC Trunk version https://godbolt.org/z/9qG5T9n5h
I have a simple naive program here that shows the us... | I've looked at the relevant paper (P2210R2 from Barry Revzin) and split_view has been renamed to lazy_split_view. The new split_view is different in that it provides you with a different result type that preserves the category of the source range.
For example, our string str is a contiguous range, so split will yield a... |
68,067,897 | 68,068,305 | Is it possible to create std future with blocking destructor without calling std async? | There is a remark on cppreference about the destructor of std::future that it will block:
it may block if all of the following are true: the shared state was created by a call to std::async, the shared state is not yet ready, and this was the last reference to the shared state.
So, basically if I create future via pr... | You could make a light wrapper for the std::future.
#include <future>
template <typename T>
class MyBlockingFuture {
std::future<T> future;
public:
MyBlockingFuture(std::future<T>&& f) : future(std::move(f)) {}
~MyBlockingFuture() {
if (future.valid()) {
future.wait();
}
... |
68,068,122 | 68,068,384 | inserting a try again feature with function c++ | I am a first year college student struggling to put a try again feature in my program.
The program's output is supposed to make the user choose between square, cube and double the integer that is entered and then at the end of the program, it will ask the user if it wants to try again or to end the program.
The whole p... | You can use a while or do-while loop. Your main could look like this (main must return int by the way):
int main() {
do {
show_main_menu_and_process_user_input();
} while(user_wants_to_start_from_the_beginning());
}
I'll leave it to you to implement those two functions. The first simply contains the co... |
68,068,514 | 68,068,634 | Rendering a grayscale texture with glBlitFramebuffer | I want to render a texture to the screen. For RGB and RGBA images
the following code works fine:
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image_data); // or GL_RGBA for RGBA images
glGenerateMip... | Swizzles are applied to the components of a texel before they are returned to the shader. This means that it will be applied to the texels when the texture is looked up (e.g. view texture). However, glBlitFramebuffer is a copy operation. Swizzles are not applied to copy operations.
|
68,068,567 | 68,070,437 | OpenGL building hierarchy transform system | I'm trying to build transform system, imitating Unity's. See my code:
void BaseObject::RecalculateTransform()
{
// For top object
if (parent.expired())
{
worldTransform = localTransform = glm::mat4(1);
return;
}
// bunch of shit
localTransform = glm::translate(glm::mat4(1), loca... | It was due to my stupid mistake. When I was initializing localRotation quaternion value, I was doing
localRotation = glm::quat(0, 0, 0, 1);
I don't know exactly why, but with debugger it negated the position value every time when the rotation matrix from this has multiplied.
The correct initialization is
localRotation... |
68,068,589 | 68,069,086 | Is returning declval UB if the template is never called outside of unevaluated context? | I am writing some metafunctions, and I had the idea to write them using C++17's if constexpr combined with deduced return type. Here is an example :
#include <tuple>
#include <type_traits>
#include <string>
template<typename TupleType, std::size_t I = 0, typename... ReturnData>
constexpr auto filterImpl()
{
if con... | Because you must instantiate the function template to determine its return type, there is a function that odr-uses std::declval<…>, so the program is ill-formed. MSVC is in error to accept it (without a warning), although it could be argued that this rule oughtn’t require a diagnostic to allow the obvious implementati... |
68,068,670 | 68,069,196 | G++-11 destruction order changed from G++9 | We have following code(it's more complicated ofc, I tried to make a minimal example).
#include <iostream>
#include <vector>
#include <string>
#include <memory>
template<typename T>
struct use_type
{
use_type(T& v) : value(v) {}
T& value;
};
template<typename T>
use_type<T> use(T& value) { return use_type<T>(v... | In
p << "", use(vec{"abc", "bcd"}), use(vec{"new", "old", "real"});
You create 3 temporaries
printer<vec> from p << "")
vec{"abc", "bcd"}
vec{"new", "old", "real"}
without sequence between them (see note below), so they may be created in any order.
Only destruction from left to right is correct (so construction from... |
68,069,501 | 70,565,254 | How do I read from a correct address of LIDAR using Arduino in I2C? | I need to read the distance data from a lidar in I2C using an Arduino Nano. Currently, this is the code I've written.
unsigned int readDistance()
{
unsigned int dist = 0 ; // LiDAR actually measured distance value. static so we can return previous dist
// step 1: instruct sensor to read echoes
Wire.beginTransm... | According to the data sheet the correct read command is five bytes: 5A 05 00 01 60. It doesn't work like a typically i2c device.
unsigned int readDistance()
{
unsigned int dist = 0 ; // LiDAR actually measured distance value
// step 1: instruct sensor to read echoes
Wire.beginTransmission(0x10) ; // transmit t... |
68,069,554 | 68,086,264 | Error when trying to compile scripts C++ - Unreal Engine 5 | When I try to compile scripts I get these errors and I don't know how to solve them. Does anyone know how to solve them?
Errors
Error 1:
Expecting to find a type to be declared in a module rules named 'RD' in UE5Rules, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null. This type must derive from the 'ModuleRules' ... | I found out the problem, in my case I use Rider from Jetbrains as IDE, and when I asked to install the RiderLink plugin I installed it in the Engine, and not in the project, and as it is still in early access, Rider is also having some bugs and when I install this plugin in the Engine, it returns these errors.
|
68,069,787 | 68,070,085 | Storing String content in map on the basis of <key, value> c++ | I have a string "parrot -color green -peak". I want to store this string in map with <key, value> format. where in this first string is considered as binary executable object rest of the values should be stored in map<key, value> format, where (-string represents key) the very next string considered as value for that p... | Your code is rather complicated and could benefit from using std::stringstream and std::getline. The string functions are very suspectible to passing invalid indices. I suggest you to use a debugger to find where your expectations are off. Splitting strings is straightforward with getline and a stream. A slightly simp... |
68,070,216 | 68,070,966 | Dynamic allocation with template | I create a class Vector that contain two variables that are template variable, I am trying to build such a dictionary that tell mark of a specific student.
The problem is I am struggling dynamic allocating memory with template. I have to do this without map or STL help. Can you explain, how to allocate them properly.
#... | To allocate n elements of type T you use:
T* array = new T[n];
so to allocate space for your keys and values:
// be aware: this will call the constructor for each element!!!
_keys = new U[n];
_data = new T[n];
If your "Vector" has a fixed capacity, this should be done in your constructor:
template<class U, class T>
i... |
68,070,262 | 68,070,957 | Crash during erase from map | I have a crash as consequence of unexpected behaviour.. I want to ask how could I modify the code to defence against this crash what happened.
void SubscManag::handleNotif(Notif notif)
{
std::cout << "Current subscribe size: " << subs_.size();
std::map<int, SubscData>::iterator it;
{
... | You are trying to do lock based concurrency.
Lock based concurrency doesn't compose. Locally correct operations, when concatenated, generate garbage.
Here, the problem is your it is generated in one lock, then you unlock. During that unlock, the it may or may not be valid. Then you relock and presume it is still val... |
68,070,436 | 68,071,244 | how does the short(vector.size()) command conversion work in C++? | I don't know any other way to return the size of a vector other than the .size() command, and it works very well, but, it return a variable of type long long unsigned int, and this in very cases are very good, but I'm sure my program will never have a vector so big that it need all that size of return, short int is mor... | Forget for a moment that this involves a for loop; that's important for the underlying code, but it's a distraction from what's going on with the conversion.
short X = Vector.size();
That line calls Vector.size(), which returns a value of type std::size_t. std::size_t is an unsigned type, large enough to hold the size... |
68,070,499 | 68,074,628 | Closing Popup and setting button label | I'm writing a C++ wxWidgets calculator application. I want to compress trigonometric function buttons into a single one to save on space, using what's basically a split button. If you left click on it, the current option is used. If you right click, a popup menu is opened, which contains all the buttons; when you click... |
when I choose an option from the menu, the main button's ID changes
(because when I reopen the menu the previously clicked button is light
up as its ID and the big button's ID match), but the label does not.
If you're creating the popup menu like in your previous post, you had a popup window with a panel as its child... |
68,070,962 | 68,071,025 | How to let users re-enter input in menu selection? | I'm trying to create a menu that will let user try again until they enter a valid selection which is (1-5). If user enters something else, I want it to show a error message and keep letting them try again. Clearly my problem here is in my while loop, but I'm not sure how to solve this bug. Can someone help me to restru... | The condition (selection != 1) || (selection != 2) || (selection != 3) || (selection != 4) || (selection != 5) with char selection; will always be true because no integer is equal to 1 and 2 at the same time.
You should use && (logical AND) instead of || (logical OR).
Also you may want to compare the input with charact... |
68,071,017 | 68,076,394 | How to capture a keypress in CEF? | I would like to intercept key presses in CEF, so I can actually implement a few key shortcuts.
I've read in the CEF API docs [1] that in order to listen to KeyPress events it's necessary to implement the interface, or inherit from, ClientKeyHandler. Then overwrite two methods: OnKeyEvent and OnPreKeyEvent. The latter i... | I fixed this issue.
It's necessary to overwrite the method GetKeyboardHandler and return the object that is now implementing CefKeyboardHandler, very much like how it works for other handlers (CefDisplayHandler, CefLifespanHandler, etc):
--- a/examples/minimal/client_minimal.h
+++ b/examples/minimal/client_minimal.h
@@... |
68,071,230 | 68,071,296 | Getting error while trying to exercise on objects and vectors and how they run together | #include <iostream>
#include <vector>
using namespace std;
class Bank_Account
{
private:
string Account_Owner_Name;
string Account_Owner_Surname;
float Account_Balance;
float Account_Remaining_Loan;
public:
Bank_Account()
{
}
Bank_Account(string... | To do
New_Account(Register_Name, Register_Surname);
An operator() that takes two arguments has to be defined in the class Bank_Account.
It looks like you wanted to do
New_Account = Bank_Account(Register_Name, Register_Surname);
|
68,071,867 | 68,071,934 | Need Help In Making C++ Template For Printing Vector<pair<int,int>> | I have already created a template for printing vector, see below
template<class T> void _print(vector<T> v1){cerr<<"[ ";for(T i:v1){_print(i);cerr<<" ";}cerr<<"]";}
But the problem is that i also wanted to create template for printing vector<pair<int,int>> but i don't know how i can create new one for pair<int,int>,... | Your problem is that you don't have an overload of _print for the argument type pair, so your template instantiation for T = std::pair<int,int> does not compile.
If you declare another function such as below, it should work.
void _print(const std::pair<int, int> &a) {
cerr<< "{"; _print(a.first); cerr << ", "; _print... |
68,072,423 | 68,072,526 | Generic macro to delete copy ctor, assignment operator for given class | Is there any way to create a generic macro to delete copy ctor, assignment operator
//Below two lines are class specific, and looking to replace with some generic way
//without mentioning hardcoded class name
#define NO_COPY Original(_In_ const Original&) = delete;
#define NO_ASSIGNMENT ... | boost::noncopyable is this:
class noncopyable
{
protected:
#if !defined(BOOST_NO_CXX11_DEFAULTED_FUNCTIONS) && !defined(BOOST_NO_CXX11_NON_PUBLIC_DEFAULTED_FUNCTIONS)
BOOST_CONSTEXPR noncopyable() = default;
~noncopyable() = default;
#else
noncopyable() {}
~noncopyable() {}
#endif
#if !de... |
68,072,629 | 68,072,738 | How to define a type for an iterator for a const and non-const container version | Consider this example:
template <typename T> struct A {
using Iter = typename T::iterator;
Iter iter;
A(T& cont) {
iter = cont.begin();
}
typename Iter::reference value() { return *iter; }
};
void f(std::vector<int>& v) {
A a(v);
a.value() = 10;
}
It work fine, buy if you add const... | Idea 1: check the type of the iterator directly.
Implementation:
using Iter = decltype(std::declval<T>()::begin());
Idea 2: check if the type is const and define iterator using this knowledge.
Implementation:
#include <vector>
#include <type_traits>
template <typename T> struct A {
using Iter = std::conditiona... |
68,072,877 | 68,073,204 | Replacing nested for loops in C++ | So I wrote this code but the problem is I have a restriction in my assignment that I can't use nested for loops in my code.
#include<iostream>
using namespace std;
void Exchange(int* a, int* b) {
int var;
var = *a; //For swapping or exchanging values. O_o
*a = *b;
*b = var;
}
void Algorithm(in... | One loop using modulus on the one loop counter:
#include <utility> // std::swap
void Algorithm(int array[], int nerd) {
int max = nerd * (nerd - 1);
for(int i = 1; i < max; ++i) {
// If at start of the removed inner loop, skip i % nerd == 0
if(i % nerd == 0) ++i;
if (array[i % nerd] <... |
68,072,958 | 68,291,997 | C++20 coroutine capture with reference weird crash with `unique_ptr` | Here is a code that crash when, in main, line (2) version is used (and line (1) is commented). Weird enough, this code compiles fines with a simple replacement implementation (line (1)) that mimic the behavior of line (2). Of course, if it's an undefined behavior, it can't have a good explanation, but I don't understan... | I think I figured out why it crashes.
Without the details, I will try to explain it what happens step by step.
Let's focus on this part:
int x = 10;
auto a = [&]() -> generator<int> {
x = 20;
co_yield x;
};
We may be used to these lambdas, but sometimes we forget the basics and what happens... |
68,073,057 | 68,077,810 | QFile is not allowed to change permissions for the file | I create QFile and set up permissions like this:
/*Reading information to file*/
file.setPermissions(QFile::ReadOwner | QFile::ReadOther | QFile::ReadGroup | QFile::WriteOwner | QFile::WriteOther | QFile::WriteGroup)
file.close()
Than I make this file as a resources file and connect it to my project. But something lik... | Modifying resources compiled into the executable is not possible - if you want to modify such a file you have to write it out the the filesystem and modify it there.
|
68,073,195 | 68,073,369 | Which is better to get return value, by const&, by &&, or just by value? | #include <vector>
std::vector<int> f()
{
return std::vector<int>(1024);
}
void use_1(std::vector<int> const&)
{}
void use_2(std::vector<int> const&)
{}
int main()
{
{
auto const& v = f(); // style 1
use_1(v);
use_2(v);
}
{
auto&& v = f(); // style 2
use_1(v);... | By-value won't be wrong and it's no-less efficient. The life-time is clear, it won't ever dangle. Reference versions are error-prone. Take this example:
#include <utility>
struct Bar {};
template <class T>
auto&& foo(T&& t) {
return std::forward<T>(t);
}
int main() {
auto&& bar = foo(Bar{});
// bar dangles
}
... |
68,074,743 | 68,074,763 | How to derive from incomplete class in C++ | I have 3 classes: Context, A, and B.
B should inherit from A, and should use Context and A in its methods.
A is an abstract class. A and Context dependent classes with forward declaration in headers.
Code in Context:
#pragma once
#include "A.h"
class A;
class Context {
...
A* someMethod();
};
Code in A:
#pr... | If you have forward declarations, then you usually do not need to include the specified header.
Context.h should NOT include A.h, nor apparently should A.h include Context.h.
Since B actually uses the A class directly (you cannot derived from an incomplete class), it will need to include A.h.
Code in Context:
#pragma o... |
68,075,411 | 68,075,434 | Why do I get an ambiguous function error from this? the function arguments are clearly different | #include "iostream"
void func(int Y)
{
std::cout << Y;
}
void func(float X)
{
std::cout << X;
}
int main()
{
func(5);
func(5.0);
}
When I switch the argument type from float to double this works I get no errors. is the compiler treating float as int?
| 5.0 is a double not a float, so both functions are an equal match.
Use 5.0f for float.
|
68,075,846 | 68,076,491 | How can I add multiple WinForms Toolbox Controls from one VSIX Project? | I followed this; Create a Windows Forms Toolbox Control from msdn, and was able to successfully create my own custom toolbox control and install it and use it. Perfect.
But, when I try to add another control file to it-for example in solution explorer I have ProjectName and then inside of that I have CustomToolboxContr... | Nevermind, I solved it.
I did everything correctly, but the Visual Studio Instance was just buggy. I decided to close VS, try installing the VSIX project anyways, and then testing it on an actual new WinForm project rather than just a debug instance of VS. It showed up just fine in the toolbox there. Was able to drag b... |
68,076,266 | 68,081,905 | C++ Class Superclass | I'm currently making a C++ version of python's svg.path. There are multiple types of paths, like a Line, CubicBezier, etc. which are separate classes (with no inheritance, except for Line and Close which are inherited from Linear but that can be removed if necessary). There's also a Path class, which in python has a li... | Since you're not using inheritance, you'll need a different tool. It appears you want something like std::variant<Line, CubicBezier, Arc>.
The downside of this approach is that you'll need to handle all the different cases yourself, since there's no common base class interface.
|
68,076,336 | 68,076,360 | How to create a template function that accepts a vector of values, with the vector type specified? | Weird question but let me explain. I'm creating a Deserializer that needs to have specialized functions for Deserializing different types, including primitives, arrays, and vectors. An example of this is the integral function, which looks like this:
/** Reads an integral. */
template<typename T, std::enable_if_... | Yes, you can suppose std::vector as the template parameter, and get the element type from std::vector::value_type. E.g.
template<typename V, std::enable_if_t<std::is_integral<typename V::value_type>::value, bool> = true>
// ^^^^^^^^^^^^^^^^^^^^^^ check the element typ... |
68,076,474 | 68,189,052 | strange logging timestamp with chrono::sleep_until | I am testing application's latency during UDP communication on windows 10.
I tried to send a message every 1 second and receive a response sent immediately from the remote.
Send thread
It works every 1 second.
auto start = std::chrono::system_clock::now();
unsigned int count = 1;
while (destroyFlag.load(std::memory_ord... | std::chrono::steady_clock is working.
It made my charts straight.
And another way, turn off the windows automatically time synchronize.
|
68,076,555 | 68,076,610 | C++ convert counted char const * data to double without using std::from_chars | This problem is a programming issue, even though it is specific to the Raspberry Pi. If the community thinks I should move this to the Pi specific Stack Exchange I can do so.
That said, the root cause of the problem is caused by what appears to be a failure to support non-integer types when using std::from_chars() wit... | Options (off the top of my head; there are definitely others):
Use a more modern version of gcc (specifically, a more modern libstdc++).
copy the data into a std::string and then call strtod on the result of calling c_str on that string (which provides a null terminator).
Manually copy the data into some array, and st... |
68,076,710 | 68,077,124 | Is there any method to solve this output problem or to initialize i | These are two of the same code, the first one is in C++, and the other is in Java. The C++ code is compiling successfully, while the Java code gives an error:
last is not initialized
but at the end, the value of i will be the last. But it is throwing an error, please help me to figure it out.
C++ code:
#include <iost... | It seems to me that you didn't initialise the variable first. Initializing them is setting them equal to a value:
int a; // This is a declaration
a = 0; // This is an initialization
int b = 1; // This is a declaration and initialization
Please note, Java primitives have default values but as one user ... |
68,077,039 | 68,090,490 | MFC How to change link text color of CLinkCtrl? | From this post, I have set up the code by putting in the OnInitDialog event:
LITEM* pItem = new LITEM;
pItem->iLink = 0; // Url index is 0
//LIF_ITEMINDEX is required for iLink, LIF_STATE is required for modifing state
pItem->mask = LIF_ITEMINDEX | LIF_STATE;
//using LIS_DEFAULTCOLORS state
pItem->state = LIS_EN... | You may not be setting the control state correctly.
Please try the MFC way (it works for me). Add to your dialog class:
CLinkCtrl syslink;
Connect it to the resource ID of your link:
void CMFCApplication4Dlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_SYSLINK1, sy... |
68,077,909 | 68,078,047 | Don't fully understand the concept of Vertex Attributes | I was following the OpenGL tutorial on learnopengl.com, and decided to test if I've fully grasped the concept of Vertex Attributes. I tried tweaking the code just to see if it works behind the scenes the way I think it does.
Here's what my modified vertices array looks like:
float vertices[] = {
-0.5f, -0.5f, 0.0f,... | The last argument of glVertexAttribPointer is a byte offset into the buffer object's data store. The offset of the 3rd component is 3 * sizeof(float) instead of 3:
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*) 3);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE,
5 * sizeof(float), (void... |
68,077,995 | 68,087,265 | Would a derived class ever have an implicit copy constructor or assignment operator when it's deleted in the base class? | Qt defines Q_DISABLE_COPY as follows:
#define Q_DISABLE_COPY(Class) \
Class(const Class &) = delete;\
Class &operator=(const Class &) = delete;
Q_DISABLE_COPY is used in the QObject class, but the documentation for it says that it should be used in all of its subclasses as well:
when you create your own subcl... | Prior to commit a2b38f6, QT_DISABLE_COPY was instead defined like this (credit to Swift - Friday Pie for pointing this out in a comment):
#define Q_DISABLE_COPY(Class) \
Class(const Class &) Q_DECL_EQ_DELETE;\
Class &operator=(const Class &) Q_DECL_EQ_DELETE;
And Q_DECL_EQ_DELETE like this:
#ifdef Q_COMPILER_D... |
68,078,640 | 68,080,394 | (Chess) Problem with negamax search missing checkmate | I'm implementing a search algorithm into the search function with Negamax with alpha-beta pruning. However, it often misses forced checkmate.
(Note: "Mate in X" counts whole turns, while "depth" and "move(s)" relies on half moves.)
Example
The position with the following FEN: 1k1r4/pp1b1R2/3q2pp/4p3/2B5/4Q3/PPP2B2/2K5 ... | I think you need to call the function "quiescenceSearch" when the depth is 0 in "negaMax". Also you need to check for "checks" too in "quiescenceSearch" along with captures since they are not quiet moves. Also Matedistance pruning works only when positions are properly scored(https://www.chessprogramming.org/Mate_Dista... |
68,078,777 | 68,079,737 | Declaration error when defining a boost library lock free queue in c++ | I am new to c++ and I am trying to create a lock free queue in c++98 using the boost library (version 1.53). When I compile my code in c++98 I get the following error:
error: ‘q’ was not declared in this scope
boost::lockfree::queue<T *, boost::lockfree::capacity<SIZE>> q;
When I remove the capacity option (boost::l... | Before C++11, << or >> in any place (including templates argument list) would be interpreted as operator. You need to separate every bracket with a space:
boost::lockfree::queue<T *, boost::lockfree::capacity<SIZE> > q;
With C++11 or later, your original line should compile as-is.
|
68,079,083 | 68,079,234 | Is there any simple way to store an input in vector in C++ ,other then the one i have implemented below? | We were given an input which we have to store in vector and do something. The input was like this
123
Now I'm currently working on it to understand the basics and working of vector like i have learned the arrays in C lang & python. Here's what I have implemented;
#include<bits/stdc++.h>
using namespace std;
int main... | If it's guaranteed that the input only consists of digits only, then you can use std::cin to input, then minus each character by '0' to get the integer.
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::string inp;
std::cin >> inp;
std::vector<int>result;
for (char c : inp) { r... |
68,080,522 | 68,080,659 | QFile seek() vs. FILE* seekg() | I am replacing some FILE* data members to QFile, and I realized that FILE*::seek() moves the cursor relative to the current position when used with ios_base::cur flag. QFile::seek() sets the cursor always relative to the file start. Is there a way to use QFile's seek() the way it works for FILE*? (Other than implementi... | Seeking forward is easy:
file.skip(offset);
Seeking backward slightly less so:
file.seek(file.pos() - offset);
|
68,080,564 | 68,081,018 | Difference between std::optional and boost::optional when its value is a variant | In embedded programming memory allocations are things that we want to avoid. So using design patterns like state design pattern is cumbersome. If we know how many states we will have then we can use placement new operations. But in this article the functional approach avoids all memory manipulations. Only drawback is t... | boost::optional doesn't have a constructor that takes arguments to pass to the underlying type but std::optional does (see constructor number 8)
You need to explicitly call the optional constructor:
boost::optional<boost::variant<int, std::string>> f()
{
return boost::optional<boost::variant<int, std::string>>{5};
... |
68,081,147 | 68,135,258 | perf record with --call-stack fp fails to unwind main function | I have a C++ test program that keeps the CPU busy:
#include <cstdint>
#include <iostream>
// Linear-feedback shift register
uint64_t lfsr1(uint64_t max_ix)
{
uint64_t start_state = 0xACE1u; /* Any nonzero start state will work. */
uint64_t lfsr = start_state;
uint64_t bit; /* Must be 16... | Like Peter said in his comment, the problem resolves itself when a version of glibc with frame pointers is used. On Ubuntu 20.04, there is a package with such a glibc.
sudo apt install libc6-prof
# To use this library:
env LD_LIBRARY_PATH=/lib/libc6-prof/x86_64-linux-gnu perf record …
Then, the [unknown] is resolved t... |
68,081,219 | 68,081,441 | How to properly structure an event handling Application? | I need to write an application using C++ which handles input signal from various sources and end up with something like this:
InputManager: handle input signals and convert them to messages.
Processor: it will receive all messages from the input. Put it in a
queue and operating one by one.
Other modules.
// define... | Use the following answer (which I took from a comment by Aconcagua):
I'd write one class per signal type, create one class instance per
concrete signal and have all of them keep a link to the single queue
instance. If you give the classes one common base class, you might
even put all of them into a single std::vector ... |
68,081,475 | 68,081,556 | strtol is pointing to original string | #include <cinttypes>
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;
uint64_t descendingOrder(uint64_t a)
{
string str = to_string(a);
sort(str.begin(),str.end(),[](unsigned char a , unsigned char b) { return a>b;});
cout<<"sorted string:" <<str<<endl;
cout<<"value :... | 9887777655433322200 is out of range for a long on your architecture.
That's why errno gets set to ERANGE and LONG_MAX (which happens to be your input) is returned. Note that an implementation may also use LLONG_MIN or LLONG_MIN or even LONG_MIN. You need to check errno in order to know whether the conversion with strto... |
68,081,481 | 68,081,482 | How can I build Qt 5.13.2 with GCC 11.1 on Windows? | I have been building Qt 5 for a long time successfully on Windows using GCC/MinGW-w64. When I try the same with GCC 11.1, the build fails with a strange error message. What can I do to make it work?
I have built the compiler myself using the develop branch of https://github.com/niXman/mingw-builds with this command:
..... | There are several issues to solve.
First I have to patch Qt, since with GCC 11 some header dependencies have changed and Qt 5.13.2 does not always include the right headers (see https://gcc.gnu.org/gcc-11/porting_to.html or How Can I Include Header Files by Compilation Flags?).
Therefore I add the line
#include <limits... |
68,081,725 | 68,082,950 | how to get char casted from int to 'appear' in console out? | I have a vector and want to cast ints to chars, and then pushback the casted char to the vector.
what i am getting is 'invisible' elements in the vector, which cause no obvious errors, increase the vec.size() count, however do not display during console output. how do i fix this so they appear as a normal / 'visible' c... | Thanks for all the suggestions and comments. in order to provide clarity here is what i was trying to acheive.
#include <iostream>
#include <vector>
int main(int argc, const char * argv[]) {
std::vector<char> test{'a','b'};
int i = 12345 ;
std::string w = std::to_string(i);
for(... |
68,082,513 | 68,083,329 | Why does GCC 11.1 warn about "use of possibly-NULL 'operator new(32)' where non-null expected"? | I am using GCC 11.1 and I have enabled the static analyzer with the option -fanalyzer. Now in this line:
std::pair<NodeIterator, bool> result = idNodeMap.emplace(id,
new Node(id, point));
I get the following warning:
..\src\Mesh\Mesh.cpp: In member function 'void Ct::Geometry::Mesh::addNode(int, const ... | This is GCC bug #94355.
Some work has been done, but the issue is still open and there's a comment in there with this specific issue.
It sounds like it doesn't yet differentiate operator new that throws std::bad_alloc on allocation failure from (a hypothetical) one that returns nullptr.
|
68,082,568 | 68,082,733 | How to use templates to build compile-time generated metadata | In trying to call a variadic template, I was getting errors.
This question has now been split into the error, and the deeper goal which is in Is it possible to build a const array at compile time using a c++ variadic template?
To test the variadic template in isolation, I tried to just print out the values. So I'm obvi... | You must remember that templates are templates.
template<typename T, typename ...Args>
void test(T first, Args... args) {
cout << sizeof(first) << '\n';
test(args...);
}
int main() {
test(123_u32, 1234_u64, 1.23_f32, 1.23456_f64);
}
This will expand to
void test(uint32_t first, uint64_t arg1, float32_t arg2, f... |
68,082,945 | 68,083,601 | Issue with running a code on VSC due to no file or directory | I am a beginner to VSC and when I try to run the c++ code I wrote in VSC I get this error it would be really grateful if I can get a reply soon as I have an assignment to do :)
Picture of the error.
| Is the name of the file you're trying to compile "Assignment 9.cpp"? If so, it appears the compiler is seeing
g++ Assignment 9.cpp
and then assuming that it should be able to find two files, one called "Assignment" and one called "9.cpp".
If you run the command g++ "Assignment 9.cpp" -o "Assignment 9", it should compil... |
68,083,080 | 68,083,215 | Is this behaviour of std::quote bug? | I want to do the same thing as std::quote with a custom type, but I thinking about miss used of this kind of API with a temporary rvalue. After some dinging with std::quoted, I discovered the following problem:
To be efficient std::quoted force to store a const reference or a pointer to avoid a deep copy of the source ... | This is to be expected. Or rather: this is not to be expected to work.
From cppreference:
Allows insertion and extraction of quoted strings, such as the ones
found in CSV or XML.
When used in an expression out << quoted(s, delim, escape), where out
is an output stream with char_type equal to CharT and, for overloads
2... |
68,083,471 | 68,096,741 | Maya C++ API : Function causes undefined crash without entering the function | I'm currently working on a plugin to stream data from Maya to a custom 3D engine.
When I'm fetching existing data:
Point Light Function
Including the commented function above causes the Maya to crash after the plugin is succesfully initialized:
Crash Position
But the "pSendPointLightData()" function or the switch case... | The call stack didn't tell me much other than that the initializePlugin() function had been called. pSendPointLightData() was empty and only accepted a pointer reference to a MObject. The plugin was dynamically linked as a .mll file.
However, updating visual studio seems to have solved the issue.
|
68,083,878 | 68,084,564 | no instance of "getline" matches the argument list | I'm using GeeksForGeeks ReadCSV function to read CSV files, I copied the code exactly as it is and I get this error: "no instance of "getline" matches the argument list" can anyone provide me with why it happens?
Here's the full code:
void ReadCSV(std::string filename, std::vector<RowVector*>& data)
{
data.clear();... | The third argument for getline is a single character (see below). When you pass it ', ' you are trying to pass two characters in single quotes.
https://www.cplusplus.com/reference/string/string/getline/
istream& getline (istream& is, string& str, char delim);
Change your delimiter to just ',' (a single character) and... |
68,084,572 | 68,085,059 | How to implement static variable functionality for templates in C++ | I'm dealing with a design dilemma and would appreciate your thoughts.
I have implemented a template class PacketManager which implements the functionality of a resource manager for different types of packets given as a template. For every TYPE of packet, I have just one instance (singleton) and I want to have a counter... | This is a false premise:
However for templates I can't have just one static variables for all template instances.
Yes you can:
#include <iostream>
struct Base {
static int counter;
Base() { counter++; }
};
int Base::counter = 0;
template <typename T>
struct Foo : Base {};
int main(int argc, char** argv) ... |
68,084,758 | 68,085,211 | Is calling x = std::array<T, N> () same as declaring std::array<T, N> x? | I am writing custom move constructor and move assignment operator for class_name. I would like to know if calling std::array as std::array<T, N> () is correct or not.
class_name::class_name(class_name&& other) :
mem_A(std::exchange(other.memA, class_memA())),
arr_memB(std::exchange(other.arr_memB, std::array<T,... | Yes, your use of array is fine, provided that is how arr_memB is declared to begin with. You could use decltype instead to avoid guessing.
But you do need to remove the redundant member name references when calling exchange() in the move assignment operator. Calling a member's constructor by its name works only in a co... |
68,084,781 | 68,084,833 | Vector and smart_pointer. I don't get the actual numbers | I have this code:
#include <iostream>
#include <memory>
#include <vector>
class Test {
private:
int data;
public:
Test() : data{} { std::cout << "\tctor Test(" << data << ")\n"; }
Test(int data) : data{ data } {
std::cout << "\tctor Test(" << data << ")\n";
}
int get_data() const { return d... | Your Test class has the get_data() function to get the number, so use that.
Changing the line
std::cout << vec[i] << std::endl;
to
std::cout << vec[i] << " : " << vec[i]->get_data() << std::endl;
will give you something like this:
0x18f4190 : 1
0x18f41f0 : 2
0x18f41d0 : 3
|
68,085,378 | 68,085,412 | Pointers c++ "w does not name a type" | When im trying to compile code below im getting an error
wskazniki.cpp:7:1: error: 'w' does not name a type w = &liczba;
//wybieramy zeby wskazywal na zmienna liczba
#include <iostream>
using namespace std;
int liczba=144;//wskaznik to zmienna ktora przechowuje adres innej zmiennej
int *w; //tworzymy wskaznik typu... | You cannot place statements like
w = &liczba; //wybieramy zeby wskazywal na zmienna liczba
outside function body.
You should put that inside function body
#include <iostream>
using namespace std;
int liczba=144;//wskaznik to zmienna ktora przechowuje adres innej zmiennej
int *w; //tworzymy wskaznik typu int
int mai... |
68,085,764 | 68,085,841 | Increment tuples in a map | I have the following member of a class I am using:
std::map<std::string, std::tuple<double, double, int>> errors;
The idea is we loop over a series of bins each with a std::string name, and 3 values associated with it.
We would like to add each bank to the map when the error is over a certain threshold and sum the thr... | In C++17, with Structured binding, you might unconditionally do:
auto& [err_mean, err_stddev, err_count] = errors[binname];
err_mean += mean;
err_stddev += stddev;
err_count += 1;
errors[binname] will create default entry ({0., 0., 0}) if not present.
For pre-c++17,
auto& tup = errors[binname];
std::get<0>(tup) += mea... |
68,086,180 | 68,088,653 | Problem with multi-threaded construction of Nef Polyhedrons from a same Polyhedron | I have a multi-thread program in which a set of 3D Nef Polyhedrons might be constructed from a same polyhedron, the simplified code can be demonstrated as:
#include <iostream>
#include <vector>
#include <fstream>
#include <future>
#include <CGAL/Exact_predicates_exact_constructions_kernel.h>
#include <CGAL/Polyhedron_3... | On linux, your program aborts with
free(): corrupted unsorted chunks
CGAL::Exact_predicates_exact_constructions_kernel is not thread-safe currently, reading the same number in 2 threads can lead to corruption. There is a PR to make it thread-safe: https://github.com/CGAL/cgal/pull/5402 but it hasn't been merged yet.
... |
68,086,323 | 68,086,829 | C++ Concepts Compound Requirements without noexcept and return-type-requirement vs Simple Requirements | template<class T>
concept C1 = requires(T a, T b) { a + b; };
template<class T>
concept C2 = requires(T a, T b) { { a + b }; };
Would there be a difference between C1 vs C2 functionally?
Edit: grammar
| They are equivalent. The standard even has an example of it:
template<typename T> concept C1 = requires(T x) {
{x++};
};
The compound-requirement in C1 requires that x++ is a valid expression. It is equivalent to the simple-requirement x++;.
Compound requirements are able to test some aspect of the expression such ... |
68,086,468 | 68,104,873 | Getting Fatal error when calling MPI_Reduce inside a loop | I have a problem in this part of code (which is common between the tasks):
for (i = 0; i < m; i++) {
// some code
MPI_Reduce(&res, &mn, 1, MPI_INT, MPI_MIN, 0, MPI_COMM_WORLD);
// some code
}
This is working fine, but for large values of m I get this error:
Fatal error in PMPI_Reduce: Other MPI error, ... | You seem to be overtaxing MPI with your communication pattern. Note the 261895 unexpected messages queued error message. That's quite a lot of messages. As MPI tries to send data for small messages (like your single-element reductions) eagerly, running hundreds of thousands of MPI_Reduce calls in a loop can lead to res... |
68,086,980 | 68,087,059 | One extra line being read in file handling | I am trying to get the number of lines and words from a text file in c++. But one extra line is being read by compiler.
#include <iostream>
#include<fstream>
using namespace std;
int main(void)
{
ifstream f;
string name;
char a;
int line, words;
line = 0;
words = 0;
f.open("file.txt");
... | You are not checking if f.get() succeeds or fails. When it does fail, a is not updated, and you are not breaking the loop yet, so you end up acting on a's previous value again. And then the next loop iteration detects the failure and breaks the loop.
Change this:
while (f) {
f.get(a);
...
}
to this instead:
w... |
68,087,119 | 68,087,176 | What is the scope of std::mutex object? | Here is the sample code:
#include <iostream>
#include <thread>
#include <mutex>
int value = 0;
void criticalSection(int changeValue)
{
std::mutex mtx;
std::unique_lock<std::mutex> uniqueLock(mtx);
value = changeValue;
std::cout << value << std::endl;
uniqueLock.unlock();
uniqueLock.lock();
... | There are no special scoping rules for mutexes. Their scope ends on the next }. In your code every call to criticalSection creates a new mutex instance. Hence, the mutex cannot possibly be used to synchronize the two threads. To do so, both threads would need to use the same mutex.
You can pass a reference to a mutex t... |
68,087,458 | 68,087,520 | Preprocessor directive in middle of c++ function? | void VoxelTerrain::set_stream(Ref<VoxelStream> p_stream) {
if (p_stream == _stream) {
return;
}
_stream = p_stream;
#ifdef TOOLS_ENABLED
if (_stream.is_valid()) {
if (Engine::get_singleton()->is_editor_hint()) {
Ref<Script> script = _stream->get_script();
if (sc... |
When does the #ifdef execute in the above function?
It is executed before "the compiler" sees the code. If the preprocessor knows what the TOOLS_ENABLED symbol is, then the preprocessor continues to pass this code to the compiler.
If the preprocessor does not know what TOOLS_ENABLED is, then it will skip this chunk ... |
68,087,801 | 68,088,300 | How do I get the template function type when passing a std::vector<T>? | I'm trying to implement a templated function that takes as argument either a std::vector<float>& or a std::vector<std::vector<float>>. Below a simplified version of my code.
I'm getting errors like:
C2440 'initializing' cannot convert from initializer list
when I tried to implement this when calling function PlotData... | Here you will have to use if constexpr
if constexpr (std::is_same<T, std::vector<std::vector<float>>>::value)
{
...
}
else if constexpr (std::is_same<T, std::vector<float>>::value)
{
...
}
But now you have a function template that works only for 2 very specific types and doesn't do anything for any other ... |
68,087,828 | 68,095,371 | Boost.Multiindex composite_key key storage | Let's say I form a composite_key of three integer members for a boost::multi_index_container. The keys will span every combination of three integers within some range ({0, 0, 0}, {0, 0, 1}, {0, 0, 2}, etc). Internally, does boost store each of these combinations of integers as a key such that the total number of keys w... | The size/overhead of a hashed index is 2+1/LF pointers per element, where LF is the index load factor. LF typically ranges between MLF/2 and MLF, where MLF is the maximum load factor allowed, by default 1, so the overhead ranges between 2+2=4 and 2+1=3 pointers per element, which is 3.5 pointers per element on average.... |
68,088,590 | 68,089,552 | How to open a second QMainWindow from my first/original MainWindow? | I am creating a desktop app with Qt6 and C++ and I have my original MainWindow class. Using Qt Creator I generated ui,h,cpp for a new SummaryClass (QMainWindow).
I want to be able to click a button located in MainWindow so that I can open the SummaryWindow.
void MainWindow::openSummary()
{
SummaryWindow windo... | one alternative is that you define a list of pointers to the summaryClass and you create and show as many instances of the summary as you need in the slot for the button in the mainWindow
your mainwindow.h
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~Main... |
68,088,652 | 68,092,156 | Create a Titleless/Borderless draggable wxFrame in wxWidgets | Hi i am trying to create a wxApp that will have not have a titlebar(including the minimize, maximize and close) icons that are by default provided. The code that i have is as follows:
main.h
class MyApp : public wxApp
{
public:
virtual bool OnInit();
};
main.cpp
bool MyApp::OnInit()
{
MyFrame *prop = new M... | Here's the simplest example I can think of how to create a frame with a pseudo titlebar that can be clicked to drag the frame around. This example shows which mouse events need to be handled to drag the window around and how to do the calculations needed in those event handlers.
Note that moving the frame needs to be ... |
68,090,461 | 68,090,590 | C++ unsigned and signed conversion | I've seen this kind of question asked before, but supplied answers don't clear everything for me. When this question is posted it is usually accompanied by next example:
#include <iostream>
int main()
{
unsigned int u = 10;
int i = -42;
std::cout << i + i << std::endl;
std::cout << i + u << s... | After:
unsigned int u = 10;
int i = -3;
the evaluation of i + u proceeds by first converting i to unsigned int. For a 32-bit unsigned int, this conversion wraps modulo 232, which is 4,294,967,296. The result of this wrapping is −3 + 4,294,967,296 = 4,294,967,293.
After the conversion, we are adding 4,294,967,... |
68,090,660 | 68,090,759 | parse libcurl response with nlohmann json or rapidjson | My libcurl code returns me a json string:
{"object":"user","attributes":{"id":000,"admin":false,"username":"un","email":"google@gmail.com","first_name":"leopold95","last_name":"leopold95","language":"en"}}
I want parse this string in my objects (my problem isn't in it).
But when I try parsing this with nlohmann or rap... | The json.exception.parse_error you get is due to the fact that "id":000 not valid JSON. It should most likely be "id":0.
The proper way to fix this is to ask the other end to correct the mistake.
How could I replace all " to \" in my respose?
That wouldn't help and would in fact make the JSON even more invalid. The \... |
68,091,023 | 68,091,897 | Finding all first elements in a vector of pairs | I am trying to perform averages on some values in a vector of pairs that have the same first element, and then storing it inside of a map. For example:
std::vector<std::pair<int, double>> test;
test.push_back(std::make_pair(1,100.0));
test.push_back(std::make_pair(1,200.0));
test.push_back(std::make_pair(1,400.0));
tes... | Assuming you have your vector sorted sequentially by the first pair element you can do something like:
double sum {0.0};
int count {0};
int key {pair[0].first};
for (auto pair : vec) {
if (pair.first != key) {
map.insert(key, sum / count);
key = pair;
sum = 0.0;
count = 0;
}
sum += pair.second;
... |
68,091,047 | 68,091,384 | Understanding the time and space complexity of this problem | I have the following code. I have been told that the time complexity of this is O(n).
But I am having a hard time understanding how. To me it seems like it is
O(n) + O(n) + O(n) = O(3n)
and the space complexity is O(3n) as well because 3 vectors that get populated to the size of n.
Is my understanding correct ?
void pr... | I think you are missing the point of the asymptotic notation. That code is O(3n) but it is also O(n) and the latter is what matters.
O(3n) and O(n) are equivalent by definition.
We say f(x) is O( g(x) ) if there exist two constants m and k such that f(x) < m * g(x) for all x greater than k. Basically f(x) is O(g(x)) if... |
68,091,178 | 68,102,441 | How can I send a GraphQL request from Unreal Engine C++? | I successfully made a regular HTTP request and got the response back. Now I am trying to do the same with GraphQL. The GraphQL request is returning 200 in Postman with the expected JSON body, but when I try to do the same in C++, I get a 400 Bad Request. My code is below, with access tokens removed.
AApiClient::AApiCli... | I got it to work. One of the problems I was running into is explained here:
Shopify doesn't support cookies in POST requests that use basic HTTP
authentication. Any POST requests that use basic authentication and
include cookies will fail with a 200 error code.
From here: https://shopify.dev/tutorials/authenticate-a-... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.