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
67,068,566
67,068,691
Proper way to convert std::string to/from enum class
For the assignment I'm currently working on, I have defined an enum class for differing class semesters. enum class Semester { FALL, SPRING, SUMMER }; In my overloaded << operator, I am to print out the lowercase string equivalent of Semester type. I've done so by creating a map with Semester k...
Don't bother with a std::map, just use a function: //As an aside, avoid uppercase enum names enum class Semester { Fall, Spring, Summer }; std::string to_string(const Semester& s) { switch(s) { case Semester::Fall: return "fall"; case Semester::Spring: return "spring"; case Seme...
67,069,136
67,069,968
Time complexity for Regular Expression Matching
I was solving the problem Regular Expression Matching on leetcode. I solved it using recursion as below: if (p.empty()) return s.empty(); if ('*' == p[1]) // x* matches empty string or at least one character: x* -> xx* // *s is to ensure s is non-empty return (isMatch(s, p.substr...
Assume T(t,p) is the time complexity of function isMatch(text, pattern) where t is text.length() and p is pattern.length() / 2 First T(x,0) = 1 for all x Then if pattern[1] == '*', T(t,p) = T(t,p-1) + T(t-1,p) + O(t + p) Otherwise T(t,p) = T(t-1, p-0.5) + O(t + p) Obviously the first case is worse Think about the Combi...
67,069,586
67,071,051
How do I get two different random numbers in the same srand() seed? C++
I am trying to create a random password generator. When I call the function multiple times it returns the same character value. QQpQ;7Q7pQ;p I have tried adding srand(time(0)); or srand((unsigned int) time(NULL)); in my main function. Looking at other stack over flow posts I see that srand helps create different charac...
randomCharacterTypes is an array of 4 characters, for each character class you'll always get the same character. If you want to generate a new character each time you could use function pointers instead: string randomGenerator(int numberOfCharacters){ char (*randomCharacterTypes[])() = {randomLowerCharacter,randomI...
67,070,589
67,070,765
C++ Is there any guarantee that literals conditions generated by a template will be optimized away?
Excuse any mistakes in my code, I'm still learning C++ syntax. My question is not about whether the code is correct but whether a literal expression will be optimized away. Let's say I have a function generated from a non-type template like this: template <bool add> int addIt(int a, int b) { if (add) { return...
This is never guaranteed for regular if (although I would say chaneces are pretty high). There are two ways to be sure. Simpler one requires C++17 (btw addIt seems to return wrong type): template <bool add> int addIt(int a, int b) { if constexpr (add) { return a + b; } else { return a - b; } } i...
67,071,188
67,071,259
'mutex': is not a member of 'std' error in msvc
The following code which resides in one of my header files produces the error. There was no problem when the mutex was in a source file and I was using it with extern as a global variable. Thank you! #include <memory> struct MyStruct { std::mutex m; };
you want include the file where std::mutex is located at, in <mutex> #include <mutex> struct MyStruct { std::mutex m; }
67,071,563
67,071,754
Can't the double pointer be used like a dictionary?
i'm trying to make apt of subject char test; char* testPtr = &test; char** testPPtr; testPptr = new char* [100]; for (int i = 0; i < 5; i++) { cin >> testPtr; testPPtr[i] = testPtr; // math, eng, history, kor, science } for (int j = 0; j < 5; j++) { cout << testPPtr[j] << endl; } i think testPPtr[0] is ...
cin >> testPtr; has undefined behaviour. It tries to write characters after test. Even if you fix that, e.g. by declaring std::string test;, there is only one string in your program, so all the pointers point to the same place. std::vector<std::string> subjects(5); // Creates 5 empty strings for (std::string & subject...
67,071,683
67,074,178
Losing data when passing uint8_t* to void* parameter function?
I wrote this function to generate a texture in OpenGL. It correctly generates the texture I want which is a wooden box. // This works bool GenerateTextureFromFile(const int32_t mipMapLevel) { int32_t width, height, channels; uint8_t* data = stbi_load(mProps.mPath.c_str(), &width, &height, &channels, 0); i...
The issue is here just realized accidentally put objectID instead of GL_TEXTURE_2D glTextureParameteri(mObjectID, GL_TEXTURE_MIN_FILTER, mProps.mFilterMin); glTextureParameteri(mObjectID, GL_TEXTURE_MAG_FILTER, mProps.mFilterMax); glTextureParameteri(mObjectID, GL_TEXTURE_WRAP_S, mProps.mWrapS); glTextureParameteri(mOb...
67,071,795
67,074,653
Calling parallel C++ code in Python using Pybind11
I have a C++ code that runs in parallel with OpenMP, performing some long calculations. This part works great. Now, I'm using Python to make a GUI around this code. So, I'd like to call my C++ code inside my python program. For that, I use Pybind11 (but I guess I could use something else if needed). The problem is that...
It's not really a good answer (too long for a comment thought), because I did not reproduce your problem, but maybe you can isolate the issue in your code by trying this example that works for me: C++ code: #include "OpenMpExample.hpp" #include <algorithm> #include <iostream> #include <random> #include <vector> #incl...
67,072,609
67,073,848
Shell_NotifyIcon not working even in Microsoft example
Shell_NotifyIcon does not show balloon tips for me. The icon shows up for a millisecond and disappears, and no text is shown. So, I downloaded Microsoft's NotificationIcon example from GitHub, and built it. Had to change Windows SDK in the project from 8.1 to 10.0.17763.0. The example runs, and the icon is shown in not...
With Windows 10, balloons are not shown anymore (too intrusive). Instead, you'll get a new notification available in the notification area:
67,072,647
67,072,811
Extract a value from a JsonDocument
noob question about float number in arduino and extracting values from a json doc. I'm doing an HTTP request to Ipstack to get latitude and longitude values with this function: void gps(){ //Declare an object of class HTTPClient HTTPClient http; //Specify request destination and fields http.begin(...
According to arduino documentation of function print, float values are rounded to 2 digits by default. You can, however, specify how many digits you want to have in a second parameter of print, e.g. as Serial.println(latitudine, 4); Note that datatype float might not be able to represent all the digits contained in yo...
67,072,798
67,073,123
Aligning text in the form of vertical list/or a text in C++
I want the following output to get aligned properly in the form of a table: My attempt: I created a class with member function(a function to display the products available in a store) and member variables. Then in the main function I initialized all the member variables and passed control to the user defined function ...
By default when setw is set, << operator uses right-alignment. By printing TAB characters the right-alignment is broken and the rest of the line gets shifted. Try to avoid using \t in combination with setw, and set alignment to left in the beginning: void product::display_productdetails() { cout << left; cout <...
67,072,896
67,076,384
Making third party I/O DLL asynchronous
I need to use a third-party DLL which implements a TCP socket client (in C++) using blocking calls. So basically (pseudocode); void DoRequest() { send(myblockingSocket,data); recv(myblockingSocket,responsedata); } What is the recommended way to make these calls accessible in .NET as asynchronous calls using async...
What is the recommended way to make these calls accessible in .NET as asynchronous calls using async-await (without changing the original DLL) ? There is no recommended solution because this isn't possible. Either the DLL itself must be changed/replaced so that it supports asynchrony, or the asynchronous calls will j...
67,073,357
67,073,480
Call the same method for all fields in a struct/class
Consider the following code. struct Data { int a = 100; char* b = nullptr; }; struct Data2 { int c = 100; char* d = nullptr; }; template<typename T> struct Test { T field; T field2; }; int main() { Test<Data> test; test.field.a = 500; test.field2.a = 500; Test<Data2> test2; test2.field.c = 100...
How about something like this? (utilizing data-member-pointers) struct Data { int a; }; template<class T> struct test { T field1, field2; template <class U, U (T::* p)> void set(U value) { field1.*p = value; field2.*p = value; } }; int main() { test<Data> t; t.set<int,...
67,073,874
67,073,924
Declare methods with pointer outside class in C++
I want to declare the methods of the following code outside the class but i get the following error whenever the method is a pointer to private member variable: "no instance of function template "std::next" matches the required typeC/C++(386)". class Node { private: int data; Node *next; public: Node() {}...
This is wrong Node Node::*GetNext() { return next; } This is right Node* Node::GetNext() { return next; } The name of function is Node::GetNext and not GetNext.
67,073,933
67,074,065
JsonCpp - modify an array of objects
I have a following array of objects in JsonCpp::Value: [{"foo": "bar", "baz": ["Hello", "World"]}, {"Hello": "99bottles", "baz": ["bar", "foo"]}, {"beer": "hello", "world": ["foo"]}.... ] I have to iterate over them and alternate them (remove some elements, add another one). I can easily iterate over JsonArray with: f...
You are using get() which must return a value instead of a reference, because you can call with with an invalid i and it will return the default value you provide. I.e. for an array of size 2, you should be able to call array.get(17, Json::Value()) and you'll get back a default initialized Json::Value. If you're certai...
67,073,995
67,075,092
cmake building shared lib from object library results in undefined symbol
I'm building a shared library using cmake. Here are the steps that I take, starting with building a shared library A_shared using an object library A_obj. add_library(A_obj OBJECT ${A_SRCS}) add_library(A_shared SHARED) target_link_libraries(A_shared PUBLIC A_obj) This process works. Now I wish to build another shared...
This comes from the behaviour of shared libraries on Windows in general: See this question. I have to manually export the symbols. The interaction with the object library wasn't creating issues.
67,074,201
67,075,258
How to override previous array value
I am trying to write a function (method?) clearSquares() that resets this array: string squares[25] = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14"," 15","16","17","18","19"," 20","21","22","23","24"," 25"}; after it is altered, back to its original values when called void clearSquares() { string ...
You have two variables; one global and one local to clearSquares. These have nothing to do with each other. Since you can't assign to arrays, avoiding having a local one will not help. But you only need one function, both for initial setup and clearing. Something like void resetSquares() { int i = 1; for (auto&...
67,074,429
67,074,508
(c++)can u nest namespaces from extern sources
i have a few headers with namespaces which all follow a certain namepattern right now they all have a prefix infront of their actual name such as namespace Xname{//inside name.h //stuff here }; namespace Xsomething{//inside something.h //stuff here }; now this works pretty good for my usage atm, but my idea is to ...
You could define the new namespaces inside each other like so #include <iostream> namespace Xname{//inside name.h const int x = 0; }; namespace Xsomething{//inside something.h const int y = 1; }; // Your other header namespace X { namespace name = Xname; namespace something = Xsomething; } int main() { std::co...
67,074,476
67,184,374
qt5 multiline button with multiple style for each line
Can I make button, that have multiple lines, and each line have different style? When I use gtkmm, I can put widgets inside buttons, so I can make vbox with two different style labels and put it into button. But it looks, like I can't insert widgets into buttons in qt. Maybe there another way, to make multiline button ...
After all, I found a solution. I cat put layout of widgest just like in gtkmm. I just use method setLayout() of QPushButton. With this method I can put layout of multiple labels inside button. QLabel* label = new QLabel( this ); QGridLayout* layout = new QGridLayout( this ); QPushButton* button = new QPushButton( this ...
67,074,687
67,074,870
Template instead of macro as class field
I'm trying to modernize my code with the help of some clang-tidy suggestions. Say I have a class like this: class Config { public: static constexpr auto FIELD1 = "FIELD1"; static constexpr auto FIELD2 = "FIELD2"; }; Since the list of fields grows bigger, I have a simple macro: #define CONFIG_PARAM(param) \ sta...
What it is suggesting is this: template <T> constexpr T* config_param(const T* v) { return v; } class Config { public: auto FIELD1 = config_param("FIELD1"); } I would ignore it, and leave it like it is.
67,074,767
67,074,876
SDL2 Segmentation fault when trying to Poll Event
I want to create a little program, which should draw some Math Functions. At first a just wrote the code, that should create a little Window, that should just be visisble until I hit the X at the window. #include <iostream> #include <SDL2/SDL.h> SDL_Window* window; SDL_Renderer* renderer; bool running = true; bool in...
You never create the SDL_Event struct that you are using: void loop() { SDL_Event* event; while(SDL_PollEvent(event)) onEvent(event); } should be this void loop() { SDL_Event event; while(SDL_PollEvent(&event)) onEvent(&event); }
67,074,951
67,075,640
Creating an Array C++
I have two int values: v_y v_x That I would like to convert to a size 2 char array then write to my serial port. I currently have this code that isn't working: void Array2 (char charArray[], int sizeOfArray); ........ } { char one[] = { ...
// data.h or similar, you need this for both the arduino and desktop machine struct Data { double v_x; double v_y; } On your arduino: To write Data data = { .v_x = 1.0, // Example put your values here .v_y = 2.0, }; // This should write from your Arduino to the computer Serial::WriteData((const char*)data...
67,075,163
67,125,907
Arduino very randomly freezes on printing float to string via String and sprintf
TLDR: I am getting consistent freezes when printing floats to a String via arduinos String class. Previously I was getting the same freeze with sprintf and %f. I've solved the problem using the PString class, but I would like to understand the issue. FULL STORY: I have a rather large c++ codebase for arduino SAMD archi...
After a lot of debugging, it seems that the issue indeed does have to do with ability of Arduino to print floats to string, and not with pointers or non-terminated string issues in my code. It seems to be stalling in the dtostrf() call of the String constructor: // ~/.platformio/packages/framework-arduino-samd/cores/ar...
67,075,701
67,075,922
How can I do dynamic assignment to a struct inside a struct in C++?
Currently I am making dynamic allocation of structs within structs in C++. So, I made a code that can be dynamically allocated that I think. Here is the code that I made it : #include<iostream> using namespace std; int cnt = 0; struct num{ int x; int y; }; struct name { char Stu[30] = { 0 }; num *number...
There are several issues with your code. First, use std::string instead of char[30]. Second, don't allocate memory unless is necessarily. There is no need for num* number. Use a std::vector. You can put your code as follows: struct num { int x; int y; }; struct name { std::string Stu; std::vector<n...
67,076,160
67,076,224
error: static assertion failed: std::thread arguments [...] but the number of arguments is correct
Here is my code: #include <atomic> #include <thread> #include <vector> int num_of_threads = 4; // Simple function for incrementing an atomic int void work(std::atomic<int>& a) { for (int i = 0; i < 100000; i++) { a++; } } void test() { std::atomic<int> a; a = 0; std::vector<std::thread> ...
When creating a thread, its arguments are copied, and that leads to problem for thread-functions taking references as arguments. You need to wrap objects that you want to pass as references, using std::ref (or std::cref for references to constants): threads.emplace_back(work, std::ref(a));
67,076,274
70,027,023
{fmt}: always compile-time check format string in function
I am trying to create a custom error class, whose constructor creates error message by passing arguments to fmt::format(). I would prefer it to always compile-time check the format string against arguments, without me having to explicitly use FMT_STRING() each time I throw. Something like: class Err : public std::excep...
I faced this exact same problem today, but I think that the {fmt} library has improved since, and so here is my solution. The idea here is to have the exact same call in the exception constructor as the fmt::format call: the construction of the fmt::format_string object, using C++20 consteval, will parse and check the ...
67,076,386
67,076,720
Can C++ pattern of making structs to 'correspond' types be emulated in Haskell (template specialization)?
template <typename T> struct Corresponding; template <> struct Corresponding<int> { using CorrespondingT = boost::multiprecison::cpp_int; }; template <typename T> using GetCorresponding = typename Corresponding<T>::CorrespondingT; This can be used as static_assert(std::is_same_v<GetCorresponding<int>, boost::mult...
I'm not fluent in C++, so I'm not 100% sure what your example code is doing, but at a first glance type families and equalities seem similar. {-# LANGUAGE TypeFamilies #-} type family Corresponding a type instance Corresponding Int = Integer foo :: Corresponding Int ~ Integer => () foo = () -- compiles bar :: Corres...
67,076,589
67,076,625
Why C++ allows returning ifstream object?
In C++98, the following code does not compile because the ifstream has no copy constructor: #include <iostream> #include <fstream> using namespace std; ifstream f() { return ifstream("main.cpp"); } int main() { ifstream st= f(); } However using multiple GCC versions with C++11, this compiles without warnings...
C++11 added move constructors. The stream is now moved. The source object here is a temporary in the return expression, which can be moved to the st object in main.
67,076,900
67,079,465
How to read optimally from an array (in memory) having array position from a vector?
I've such a code: const rack::simd::float_4 pos = phase * waveTable.mLength; const rack::simd::int32_4 pos0 = pos; const rack::simd::float_4 frac = pos - (rack::simd::float_4)pos0; rack::simd::float_4 v0; rack::simd::float_4 v1; for (int v = 0; v < 4; v++) { v0[v] = waveTable.mSamples[pos0[v]]; v1[v] = waveTabl...
Your code is not too efficient for multiple reasons. You’re setting individual lanes of SIMD vectors with scalar code. Processors can’t quite do that, but the compiler pretends they can. Unfortunately, these compiler-implemented workarounds are slow, typically they do that with a rountrip to memory and back. Generall...
67,076,911
67,077,036
Multiple Inheritance in C++, choose from which class take the member
Consider the following code: class A { public: virtual void f() { std::cout << "A-F" << std::endl; } virtual void g() { std::cout << "A-G" << std::endl; } }; class B: public A { public: void f() { std::cout << "B-F" << std::endl; } }; class C: public A { public: void g() { std::co...
You can achieve the same if your C only inherits from B, i.e. class C: public B {/*...*/}. If you really want your C to inherit from both, B and A, you have to use virtual inheritance (see the virtual keywords when inheriging from A): #include <iostream> class A { public: virtual void f() { std::cout << "A-F" ...
67,077,003
67,077,230
Why does this c++ program not function correctly?
Right now, I'm learning C++. I have made my first little program, an addition calculator. I write two numbers and it adds them. Can you tell me why my output is 0? #include <iostream> #include <string> using namespace std; int main () { int a; int b; string number1; string number2; number1 = a; ...
Step through your code in order and you'll see the problem: int main () { int a; int b; string number1; string number2; number1 = a; number2 = b; int output; output = a + b; getline (cin, number1); getline (cin, number2); cout << output; } You define four variables, fiddle w...
67,077,384
67,077,668
Does Using Async Always Make C++ Code Faster
Is using async function in c++ is always a good idea? Literally I meant many times we may need to do some simple things like making a function that returns weather a no is prime etc so does it make c++ code faster or make it more slow? //Example Code #include <iostream> #include <future> using namespace std; bool Asyn...
This highly depends on your situation. I will describe a few situations. Situation 1: All tasks are very quick to handle. The sum of all the calculation time is small in comparison with the overhead you will face for creating the different threads. -> You will gain no, very little or even negative speed increase. Situa...
67,077,554
67,168,256
What DLLs and libs do I need so I can use `timeBeginPeriod` or other parts of `timeapi.h`?
Whereas many Windows API functions exist in Windowsapp.lib or in API sets (see this answer to How to declare and link to RoInitialize,RoUninitialize,RoGetActivationFactory and HSTRING Functions in Mingw Gcc), many functions are not listed as included in WindowsApp.lib or in the extension APIs. For example, timeBeginPer...
I figured I'd look into this myself. I wrote a little test program and used the VS compiler to test. Via Start, I launched a VS developer prompt (among other ways of doing that like in the answer to Run cl.exe from cmd ). I wrote up some simple programs to test the various cases. The answer My experimentation showed ...
67,077,862
67,077,956
Why is this concurrent code slower than the other (both C++)?
I have 2 functions, test_1 and test_2 and both should do the same thing at the same speed. But that's not the case with test_1 being significantly slower. If I run some benchmarks, test_1 takes around 15x longer than test_2. Why is that? And how can I rewrite test_1 to do the same as test_2 but with variable number of ...
Your functions are not the same. test_1 has undefined behavior, so anything you get from it is suspect. In the loop for (size_t i = 0; i < 4; i++) { AlignedType a{}; threads.emplace_back(work, std::ref(a.val)); } You pass a.val to the thread by reference, but a is destroyed at the end of each iteration. Tha...
67,078,355
67,078,530
C++: use void as template argument
I have this minimal class to represent an event which client can subscribe to. The event can have an data type associated to it, so when it is triggered by a publisher, an argument of that type would be passed to the client's callback: template<typename Arg, typename Callback = function<void(const Arg&)>> class Event {...
The quickest way of solving this without explicitly specializing for void is to use a parameter pack (added in C++11) for your template argument instead of a single type and using an empty parameter pack instead of void. A parameter pack can homogeneously hold any number of type, including 0 and 1. Then it can be used ...
67,078,539
67,081,160
program crashes while running linked list program
this is the code #include <iostream> using namespace std; struct Node{ int data; Node *next; }; Node *head; `insert function takes a number as argument` void insert(int a) { Node *temp = new Node(); temp -> data= a; temp->next = head; head = temp; } void print(void) ...
Looks like it might be due to an infinite loop like one of the comments says. Try updating the loop in the print function like this: void print() { Node *temp1; temp1 = head; // Here, I switched `head` with `temp1` while (temp1 != nullptr) { std::cout << temp1->data << std::endl; temp1 ...
67,078,636
67,078,974
C++20 Coroutines, await_resume return lvalue, Segmentation fault
Happening I want to store move only data to promise_type, and get it in coroutine. I try return return lvalue from await_resume(). The result is compilation is successful but Segmentation fault appears during execution. How can I improve? Environment OS: WSL2 Ubuntu 20.04 Complier: gcc 10.3 Command: g++ -std=c++20 -f...
In your struct awaitable, you have: bool await_ready() { return true; } To clarify, await_ready is a mechanism used to determine whether the result corresponding to an awaitable is ready or not. If it is ready, then there is really no good reason to suspend the calling coroutine (i.e the one that co_awaits the awaitab...
67,078,686
67,079,395
QML DropShadow performance issue on android app
I stumbled upon this problem some time ago and made this post: Is my QML android application running on software and how can I fix this?. The answers suggested that the app is actually being rendered on GPU and I just need to optimize my code with a profiler but I didn't find any kind of complicated bindings or anythin...
I'm guessing you'll see better results if you turn on the cached property: https://doc.qt.io/qt-5/qml-qtgraphicaleffects-dropshadow.html#cached-prop
67,078,743
67,078,828
Initializing a OpenGL VBO with a struct
Im having problems to add a struct to a OpenGL VBO This is my struct struct Vertex { //vertices std::vector<glm::vec3> vertices; //texture coordinates std::vector<glm::vec3> texCord; } This is how im assigning and initializing the VBO glGenVertexArrays(1, &buffer.VAO); glGenBuffers(1, &buffer.VBO); g...
std::vector stores a pointer to dynamically allocated memory. However, you must pass a consecutive buffer to glBufferData. Create the object's data store with glBufferData, but use glBufferSubData to initialize the buffer: size_t vertexSize = vertex.vertices.size() * sizeof(glm::vec3); size_t texCordSize = vertex.texC...
67,079,233
67,082,220
changing a pointer to method class using method class
I wanted to change the value of a pointer to class method by using a class method, but it doesnt work. This is the code: TestCode class class TestCode { public: TestCode() {}; virtual ~TestCode() {}; void render1() { (rendering code) } void render2() { (rendering code) } void event1(SDL_Event* e, void (TestCo...
Taking into account the answers, i had to pass the pointer by reference. I have altered the event1 method and the tptr1 pointer. The rest is the same. It now works. Like i said, im still learning C++ and SDL. event1 void event1(SDL_Event* e, void (TestCode::*& point)()) { if (e->key.keysym.sym == SDLK_t) { point = ...
67,079,758
67,097,118
How to simulate a video in real time and be able to extract its frames?
I am making a program that identifies a figure in a video. With OpenCV you can extract the frames of a video, as follows (I am working with c++): cv::VideoCapture vidCap(path/video.mp4); cv::Mat frame; while (!endVideo){ successRead = vidCap.read(frame); if (!successRead){ endVideo = true; } /* ...
One way to do this might be to start a separate thread that reads the video file at its normal speed and stuffs each frame in a global variable. The main thread then just grabs that frame when it's ready. So, if we use a video that just displays the time and the frame counter, we can grab a frame here and there as the ...
67,079,799
67,099,490
Use std::vector member variable as list in swig generated python interface
I am using SWIG to create python wrappers for a C++ library. The library has a few public std::vector member variables that I would like to use as lists in python. However, I haven't been able to found a solution that works. Below is a simplified example which illustrates my current solution: example.h #pragma once #i...
Without %naturalvar, this may be acceptable to you: >>> import example as e >>> x=e.MyClass() >>> x.my_data <example.int_vector; proxy of <Swig Object of type 'std::vector< int > *' at 0x0000029A09E95510> > >>> x.my_data.push_back(5) >>> list(x.my_data) [1, 2, 3, 5] If you need a more robust solution, you can use %pyt...
67,080,024
67,080,099
Can you compare an assignment of a variable to NULL?
I'm working with some code that have variable assignment and null checking on the same line. As an example: while((var1 = func1()) != NULL) { doStuff(); } My question is, is the check comparing the value of var1 to NULL, or the process of assigning a variable to NULL? I'm not sure that makes sense, but the code seems t...
https://en.cppreference.com/w/cpp/language/operator_assignment For all built-in types, the assignment operator will return the assigned value. So, it does var1 = func1(); then it checks var1 != NULL for the condition.
67,080,369
67,080,669
How to execute from Makefile? (C++)
is it possible to excute from the makefile? My make file is like this tp2: main.o complexe.o g++ main.o complexe.o -o tp2 main.o: main.cpp g++ -c main.cpp echangiste.o: complexe.cpp complexe.h g++ -c complexe.cpp clean: rm *.o tp2 I want to execute tp2 when it's created directly from...
Assuming you tried something like... tp2: main.o complexe.o g++ main.o complexe.o -o tp2 && ./tp2 then that should work, but only if that rule is run and tp2 was built successfully. If make decides that tp2 is already up to date then the rule will not be run and tp2 won't be executed. The easiest solution wou...
67,080,716
67,080,911
How can I compile ISPC code in Linux and link it with normal cpp file?
I want to compile an ispc program. I am trying to generate the executable for one of their example programs. I have simple.cpp with the below content #include <stdio.h> #include <stdlib.h> // Include the header file that the ispc compiler generates #include "simple_ispc.h" using namespace ispc; int main() { float...
According to the ISPC User's guide you can just use ispc as a command in your terminal: ispc simple.ispc -o simple.o This generates an object file simple.o that you can link to your simple.cpp file with a regular C++ compiler like g++. Edit: To compile to simple_ispc.h: The -h flag can also be used to direct ispc to ...
67,080,870
67,080,974
When do I have to include moc*.cpp in Qt?
I understand the basic concept of why it is better to manually include moc*.cpp instead of leaving moc to do it itself, but I don't quite understand when I have to include it. Let's say I have mainwindow.cpp and mainwindow.hpp, that require the moc to run on them. Here, I know I have to include moc_mainwindow.cpp in ma...
The moc’ed file contains the implementation of the meta object, the signal-slot sugar and few other things. It means that if you compile it more than once you will have duplicated symbols on linking stage. Actually your best option would be to not include the moc’ed file and add it as other normal compilation unit of y...
67,081,148
67,081,248
How do I design a function with a strong exception guarantee?
I have a function which I would like to have the strong exception guarantee: class X { /* Fields and stuff */ void some_function() { vector1.push_back(/*...*/); // May Throw vector2.push_back(/*...*/); // May Throw vector3.push_back(/*...*/); // May Throw vector4.push_back(/*...*/); //...
The solution is to use scope guards. See this answer for an example implementation of them; I'm not going to repeat it here. With scope guards, your code will look like this: vector1.push_back(/*...*/); FINALLY_ON_THROW( vector1.pop_back(); ) vector2.push_back(/*...*/); FINALLY_ON_THROW( vector2.pop_back(); ) vector3.p...
67,081,354
67,082,614
Vector initialisation using ranges vs lambda inline initialisation
I would like to initialise a vector by transforming the other one. I made a test with two ways of inline initialisation a transformed std::vector. One using lambda inline initialisation (with std::transform): std::vector<int> foo(100,42); const auto fooTimesTwo = [&]{ std::vector<int> tmp(foo.size());...
Why does it work so much slower? The problem you're running into is one of the differences between the C++98/C++17 iterator model and the C++20 iterator model. One of the old requirements for X to be a forward iterator was: if X is a mutable iterator, reference is a reference to T; if X is a constant iterator, refer...
67,081,650
67,081,752
Is it possible to use a typedef to especify only a few of the types of a template class?
Suppose that there is a template class defined like this: template <typename DOMAIN, typename COUNTERDOMAIN> class funcType { public: COUNTERDOMAIN calculate(DOMAIN x); } Then the code: typedef funcType<float, float> floatFuncType works nice. But now suppose that I want just specif...
What you want is an alias template. That would look like template <typename COUNTERDOMAIN> using RealFuncType = funcType<float, COUNTERDOMAIN>; and then you would use it like RealFuncType<float> foo; RealFuncType<some_other_type> bar;
67,081,682
67,082,831
Is logical/arithmetic shift fewer bits faster?
Is x>>2 faster than x>>31? In other words, is sar x, 2 faster than sar x, 31? I did some simple test, they seem to have the same speed. I would appreciate any solid evidence.
It would depend on the hardware implementation. For common operations involving a shift by a constant amount (e.g. pointer arithmetic), there could be a faster path (e.g. it might be fused with a related addition operation). For shifting by a variable, a barrel shifter circuitry is used, where any shift amount would ha...
67,081,700
67,081,760
Variadic template qualifiers
I have a templated interface with a variable number of parameters: template <typename... Args> class Base { public: virtual void f(Args...) = 0; }; Then I inherit another class from it: class Derived : public Base<std::string, int, float> { public: void f(std::string, int, float) override {} }; Here I would l...
Something like this? Adjust the condition as needed. template <typename... Args> class Base { public: virtual void f(std::conditional_t<std::is_scalar_v<Args>, Args, const Args&>...) = 0; }; Though I agree with @asynts. If it was my code, I'd pass by const reference unconditionally.
67,081,891
67,082,244
Why creating a thread inside an unique_ptr makes the thread destruct?
I wrote a simple function that flushes to a file in a thread, so it does not block the main thread: void MultiChannelDiskRecordingWav::flush() { size_t amountToWrite = mWriteCursorFrames*mChannelCount; for (size_t i = 0; i < amountToWrite; i++) { tempWriteBuffer[i] = writeBuffer[i]; } auto flu...
On this line: flushThread = std::make_unique<std::thread>(flush); You are creating a new std::unique_ptr<std::thread> and assigning it to an existing std::unique_ptr<std::thread> named flushThread. When flushThread is assigned to, it will destroy any std::thread that it already holds. It is that existing std::thread...
67,081,895
67,082,168
using printf with C++ iterators
I'm not clearly understanding what's happening when I use std::printf with an iterator in this context: #include <string> #include <vector> #include <list> #include <cstdio> int main() { std::string str{"hello, world"}; std::printf("%s\n", str.begin()); // prints "hello, world" std::vector<char> vec(str.begin(...
TL;DR: It's all invalid C++, since std::printf doesn't have a type safe API. Passing references to non-POD objects as std::printf arguments is always invalid: printf has a C API. What's happening in all cases is undefined behavior: you should not be writing code like that. The language spec itself tells you nothing abo...
67,082,158
67,082,257
Suppress UndefinedBehaviorSanitizer warnings from external libraries
I have an UndefinedBehaviorSanitizer build (-fsanitize=undefined), and I am trying to suppress a warning for UB in an external library that is out of my control. The clang/gcc docs mention __attribute__((no_sanitize("undefined"))), but to my surprise it seems that this attribute does not suppress warnings from subrout...
Clang has pragmas to apply attributes in bulk: #pragma clang attribute push (__attribute__((no_sanitize("undefined"))), apply_to=function) // ... #pragma clang attribute pop Wrapping the header in those disables the check in your example: #pragma clang attribute push (__attribute__((no_sanitize("undefined"))), apply_t...
67,082,281
67,082,343
Difference between bitshifting mask vs unsigned int
For a project, I had to find the individual 8-bits of a unsigned int. I first tried bit-shifting the mask to find the numbers, but that didn't work, so I tried bit-shifting the value and it worked. What's the difference between these two? Why didn't the first one work? ExampleFunk(unsigned int value){ for (int i = 0;...
Take the value 0xAABBCCDD as an example. The expression value & (0xFF << (i * 8)) assumes the values: 0xAABBCCDD & 0x000000FF = 0x000000DD 0xAABBCCDD & 0x0000FF00 = 0x0000CC00 0xAABBCCDD & 0x00FF0000 = 0x00BB0000 0xAABBCCDD & 0xFF000000 = 0xAA000000 While the expression (value >> (i * 8)) & 0xFF assumes the values: 0x...
67,082,375
67,082,402
Does returning a std::string from a class allocate memory?
Does returning a std::string (and for that matter, std::vector) from a class allocate memory? If I have this class: class Bla { public: Bla(); const std::string& GetStr() const { return m_Str; } private: std::string m_Str; }; And I have some code l...
For the std::string: #include <string> class Bla { public: Bla() {} const std::string& GetStr() const { return m_Str; } private: std::string m_Str = "Hi"; }; int main() { Bla bla; std::string currentString = bla.GetStr(); //1. will allocate new string const std::string& second...
67,082,641
67,094,063
Alpha–beta pruning in non-binary-tree
Is the classical Alpha–beta pruning code on c++ works with Non-binary-tree(3 or more children for node), because all examples of this code are used with binary trees, and when I run this code on VS, the real answer(on paper) and the result of the code are different.Is it normal? Here is the code from the internet: #inc...
It looks like you have a tree defined in a heap structure. You cannot really use this array structure for representing a tree if the number of children of a node is variable ("3 or more"). It is intended for trees that are complete: Each node has either k children or none, with the exception of one node, which may hav...
67,083,047
67,083,107
Use attribute from derived class while using method from the base class?
I have the following code: #include <map> class vehicle { private: int id = 0; std::map<std::pair<int, char>, int> seats{}; public: void displaySeats(); }; class Bus : public vehicle { private: std::string type = "Bus"; public: std::map<std::...
This is something I've done fairly often as well, the issue is how things are constructed and which functions have access to which variables. Maybe you could do something like: class Vehicle { private: int id = 0; std::map<std::pair<int, char>, int> seats{}; public: // Add a constructor ...
67,083,623
67,083,754
Conditional using statement depending on a template parameter being a tuple or not
In a template class with two template parameters T and U, I'd like to define an alias which is the tuple {T,U} if U is not itself a tuple (T is never a tuple) or the tuple {T,U0,...,Un} if U is the tuple {U0,...,Un}. I tried the following which did not compiled (for non-tuple U): #include <type_traits> #include <tuple>...
Something along these lines perhaps: template<typename T, typename U> class A { template <typename X, typename Y> static std::tuple<X, Y> Helper(Y&&); template <typename X, typename ... Elems> static std::tuple<X, Elems...> Helper(std::tuple<Elems...>&&); using TU = decltype(Helper<T>(std::declval<U>()));...
67,085,861
67,085,919
How do I use 'strlen()' on a C++ string
I'm trying to convert my basic C code to C++ using the C++ syntax instead of C syntax, if that makes sense. However, I have a problem. I don't know how to use strlen() in C++. In preprocessing, I have #include <iostream> #include <string> and using namespace std;. When I try to compile, it gave the following error mess...
There are two common ways to store strings in C++. The old C-style way, in this case you define an array of characters and \0 indicates the end of the string. #include <cstring> char str[500] = "Hello"; // How ever the capacity of str is 500, but the end of the actual string // must be indicated by zero (\0) within th...
67,085,991
67,086,054
C++ queue<string> initializer list with double curly braces
From this question Why can't I construct a queue/stack with brace-enclosed initializer lists? (C++11), we know that it won't work by constructing a queue with single curly braces. Because queue is container adapter which does not have constructor with initializer list. However, why below approach will work? Does double...
If you look at this std::queue constructor reference you will see that there is no overload taking an initializer list. There is however an overload taking the underlying container. So what happens here is that the outer {} pair is for the construction of the std::queue objects, and the inner {} pair is to implicitly c...
67,086,798
67,086,941
How do I add a number to a char that would result in the number being added "ASCIIbetically"?
So right now, if I have EncCode = 3, and MessagetEnc = 'f' the Output is 105. I want the output to be "i". Also, why is the output 105 instead of "i" like what would happen in C? int EncCode; cout << "Encryption code: " << endl; cin >> EncCode; char MessagetEnc; cout << "Message to Encrypt:"; cin >> MessagetEnc; ...
The result of an addition of char and int is an int; the equivalent C would be printf("%d", MessagetEnc + EncCode). Convert to char before printing. cout << static_cast<char>(MessagetEnc + EncCode);
67,087,896
69,821,604
Sending private UDP message in broadcast socket
I have a broadcast channel with people talking on it in UDP and its working however i want to send sometimes private message , but my socket is in broadcast mode ? I have the Ip on the people i want to contact privately. It's very annoying to create a new socket , so i suppose there is a way to juste send the message w...
sendto's parameters tells it which address to send to and you are sending to a broadcast address . If sendto() is used on a connection-mode (SOCK_STREAM, SOCK_SEQPACKET) socket, the arguments dest_addr and addrlen are ignored (and the error EISCONN may be returned when they are not NULL and 0), and the error ENOTCONN ...
67,088,082
67,089,049
Is there any mistake in that Cpp-code, which can lead unfavorable output?
Is there any mistake in that Cpp-code, which can lead unfavorable output ? Actually while submitting its solution...I got 6 wrong test cases, but I am not able to find any error! I'm providing question(commented) for reference, /* You are choreographing a circus show with various animals. For one act, you are given two...
Initial remark: You want to check if there exists an integer n with x1 + n * v1 = x2 + n * v2 In other words: x1 - x2 = n(v2 - v1) Now if v1 != v2 and (x1 - x2) / (v2 - v1) is an integer (or (x1 - x2) % (v2 - v1) == 0), the answer is YES. If v1 == v2 and x1 == x2, the answer is also YES In all other cases, the answer i...
67,088,390
67,088,574
vector out of range when converting to short
I have this code: int main() { std::vector<unsigned char> cVec{ 'a','r','t','u' }; std::vector<unsigned short>sVec; sVec = { reinterpret_cast<unsigned short*>(&cVec[0]), reinterpret_cast<unsigned short*>(&cVec[cVec.size()-1]) }; for (auto i : sVec) std::cout << i << '\n'; return 0; } but w...
you are passing pointers to the first and last character to the std::vector constructor. The pointers should be to the first and one after the last character. As the distance between the two pointers you pass isn't a whole number of shorts the code has undefined behaviour. The following code should fix the problem: #in...
67,088,960
67,092,262
Trying out a problem but code I had written is not giving output for large numbers. why?
I was trying this question. The prime factors of 13195 are 5, 7, 13 and 29.What is the largest prime factor of the number 600851475143 ? And I had written the following code: #include<iostream> #define num 600851475143 using namespace std; int isprime(unsigned long long int n) { unsigned long long int c=0; for(un...
The below code snippets are from c (but should run quite nice with c++ as well): #include <stdio.h> #define uIntPrime unsigned long long int #define uIntPrimeFormat "llu" uIntPrime findSmallestPrimeFactor(uIntPrime num) { uIntPrime limit = num / 2 + 1; for(uIntPrime i=2; i<limit; i++) { if(...
67,089,428
67,089,660
Pointer in function argument seems not working
I'm developing in C++. I have 2 objects : which are the StandaloneAgent and the ConfigManager. I want from the Standalone Agent to reach a char * variable in the ConfigManager with a function . int32_t StandaloneAgent::getConfigFile(char * file){ int32_t code = mConfigMgr->getConfigFile(file); return code; } ...
Arguments to functions are either passed by-value or by-reference. Any variable passed by-value will be local to the function and any changes made to it is local to the function too. This means that when to assign a new value to the pointer (file = mConfigFile) you only change the pointer in the function. The pointer y...
67,089,840
67,093,232
C++ template functions accepting parameters in random order
I am writing a C++ network library and would like the main (template) function to accept parameters in random order, to make it more user friendly, in the same way the CPR library does. The template function will accept up to 10 parameters at the same time, each a different type. Is there a way to instantiate the templ...
If your goal is to match the API design of a given library, best way to learn is to dig into its source code and dissect it. Consider this snippet of code (I'm still using CPR as an example as you mentionned it as a reference): cpr::Session session; session.SetOption(option1); session.SetOption(option2); session.SetOpt...
67,089,954
67,090,000
why the return values of function strcmp() in for(){} are different and increasing?
in this example for(int i = 0; i < 4; i++) { char c = 's'; printf("%d\n", strcmp(&c, "s")); } output : 0, 1, 2, 3 why the return values of function strcmp() in for(){} are different and increasing?
The code snippet has undefined behavior because the function strcmp is designed to compare strings. But the pointer expression &c in this statement printf("%d\n", strcmp(&c, "s")); does not point to a string. It points to a single object of the type char after which the memory can contain anything. So it seems the mem...
67,089,971
67,090,105
Where to put header files in order to make them accessible for all .cpp programs?
There's a "filesystem" library in my laptop. When I compile the code I get an error. I tried putting -lstdc++fs in the compile command, but it didn't work. It should, according to GCC manual. What do I do? I think I'm lost. My GCC version is 6.3.0. edit: <experimental/filesystem> also isn't working. Directory of C:\Mi...
As you use GCC 6 you not only need add -lstdc++fs, but include <experimental/filesystem>: g++ file.cpp -lstdc++fs You also need to remember that you're using experimental library, so you need to use experimental namespace as well: #include <experimental/filesystem> using fs = std::experimental::filesystem; If you do...
67,090,206
67,090,450
C++ Can I cast a pointer from one type to another, then use it as the latter? And is there overhead?
Let's say I have a pointer to a struct. Can I recast this to *char and, assuming I know the size of it including padding, then pass that to some function that could use it as *char (for example write it to a file)? And is doing that free in terms of overhead? (No need to tell me this is a bad idea, my question is if it...
It is generally legal in C++ and free in terms of runtime costs to use reinterpret_cast<char*>(pointer_to_my_value). In place of char you can also place unsigned char or std::byte. As long as you are going only to read this cast data and/or cast it back to original type it is within the bounds of defined behaviour. For...
67,090,484
67,090,590
Get number of 'nested' template arguments of a template type in c++
How can I get the number of 'nested' template arguments of a type in c++? I would like to write a function GetNumberOfTypes<T>() that returns the number of template arguments of T: constexpr int a = GetNumberOfTypes<int>(); //a == 0 constexpr int b = GetNumberOfTypes<std::vector<int>>(); //b == 1 constexpr int c = GetN...
You might (somehow) do it with specialization: template <typename T> struct TemplateArity : std::integral_constant<std::size_t, 0> {}; template <template <typename...> class C, typename ...Ts> struct TemplateArity<C<Ts...>> : std::integral_constant<std::size_t, sizeof...(Ts)> {}; Demo We cannot mix in generic way typ...
67,090,717
67,091,076
Why `std::ostream& operator<<` overriding must be declare in 'global' scope in C++?
Description I'm overriding << operator for std::ostream to ease object display in my code. I use differents namespaces where I define types of object to display. That leads me to a compilation error. I have found a fix. It seems that overriding must be declare in a global scope but I really don't understand why. Can so...
ADL strikes again For resolving operator overloads, C++ uses Argument Dependent Lookup. In short, it will search the namespace of either parameter (in this case namespace std) and the namespace of the call of the operator (aNamespace), going up the hierarchy if no operator overload is found. The namespace std does not ...
67,090,888
67,091,572
Upgrade MFC CListBox control with ON_WM_RBUTTONDOWN so dialog can handle message directly
I have wondered about how limited is the provided set of messages controllers for CListBox control. I am already using ON_LBN_SELCHANGE in the message map of the CDialog containing this control. I also would like to use ON_WM_RBUTTONDOWN, so I have derived a class CMyListBox : public CListBox, so now i can map that mes...
You can set your control to send WM_PARENTNOTIFY messages to the parent dialog box (it doesn't, by default) and add an override of the OnParentNotify() function to your dialog class. The basic procedure would be as outlined below. First, you'll need to remove the WS_EX_NOPARENTNOTIFY style from your list-box control, s...
67,091,344
67,093,812
Extending Rcpp::as for custom classes depending on Rcpp.h
I'm working on an Rcpp sparse matrix class that uses both Rcpp::IntegerVector (row/column pointers) and a templated std::vector<T>. The rationale is that overhead in deep-copying the integer pointer vectors (@i, @p) in extremely large sparse-matrices can be avoided by simply leaving them as pointers to R objects, and c...
It's actually quite simple to create an Rcpp SparseMatrix class! I was overthinking it. #include <rcpp.h> // Rcpp for sparse matrices (spRcpp) namespace Rcpp { class SparseMatrix { public: Rcpp::IntegerVector i, p; Rcpp::NumericVector x; int n_rows, n_cols; // constructor ...
67,091,788
67,092,845
When algorithm is placed inside loop it produces different results, C++
I create the following algorithm in Rcpp and compile it in R. // [[Rcpp::depends(RcppArmadillo)]] #include <RcppArmadilloExtensions/sample.h> // [[Rcpp::export]] arma::colvec Demo(arma::mat n, int K){ arma::colvec N(K); for(int j=0; j<K; ++j){ for(int i=0; i<(K-j); ++i){ N[j] += accu(n.submat(i,0,...
You are incrementing N in place via +=. Your function fails to ensure it is initialized at zero. Rcpp tends to do that by default (as I think it is prudent) -- but this can be suppressed for speed if you know you are doing. A minimally repaired version of your code (with the correct header, and a call to .fill(0)) fol...
67,091,890
67,092,158
How to pass pointer to function that passes argument as referrence in C++
Following is given: void foo(Bar& argument){ ... } Bar* bar = ...; How do I call an equivalent of foo(bar); ?
As mentioned in the comment foo(*bar) works.
67,092,536
67,093,119
Overloading + and += operators in parent and child class in C++
Okay guys, this one has me confused not least because of how little info for this there is online... Okay so lets say I have a parent and a child class as such: class ParentPlot { public: int a; int b; datacontainer Events; friend ParentPlot& operator+(ParentPlot& plot...
1. Fix your operator return types. operator + should return a copy. operator += should return a reference to this. friend ParentPlot operator+(ParentPlot& plotA, const ParentPlot& plotB) ParentPlot& operator+=(const ParentPlot &plotB) friend ChildPlot operator+(ChildPlot& plotA, const ChildPlot& plotB) ChildPlot& opera...
67,092,701
67,092,860
Concept for member function taking a template parameter in C++20
I would like to have a concept for the struct creatorclass { template<typename T> int fct(T val) { return 42; } }; What I would like is a concept that checks for the existence of a function fct without specifying the template parameter. That is want to have template<typename U> concept CREATOR=requires(U v...
As far as I am aware, it is not possible to test for a template member function without evaluating any of the template parameters. That said, if you have an idea of what the classification of inputs are allowed to be -- such as if a function can only be evaluated with integral-values or something like this -- then you ...
67,093,603
67,094,281
No viable overloaded '=' at std::vector
I have this c++ program with the following types: typedef pcl::PointXYZI PointType; typedef pcl::PointCloud<PointType> PointCloudType; typedef std::vector<PointCloudType::Ptr> CloudPtrList; and this in main: CloudPtrList clusterPtr(2); for (int i = 0; i < clusterPtr.size(); ++i) { clusterPtr[i] = b...
As can be seen in the error message ... /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/memory:3737:17: Candidate function not viable: no known conversion from 'typename boost::detail::sp_if_not_array<PointCloud<PointXYZI> >::type' (aka 'shared_ptr<pcl::PointCloud<pcl::...
67,093,839
67,094,170
How to implemet copy constructor in C++
this is the header of a class that I have been designing for an assignment. I have included constructors, a destructors, as well as overloaded operators. Could you give me a hint how to properly define the constructors in a class using c++ 20 most recent features in an efficient way. #ifndef VECTOR_DOUBLE_H #define VEC...
This example definition may help, I tried sticking to C++20 features: #include <cmath> #include "vector_double.h" vector_double::vector_double(int size): m_array{ new double[size] }, m_size{size} {} vector_double::vector_double(std::initializer_list<double> lst): //Constructor that takes an...
67,094,148
67,119,149
Solved:Query Results (to CString) in C++ using mysql.h
Im currently trying C++ and building a databaseconnection with mysql c api from oracle. In first place it works fine. If i query for a col like " select username [...] where id=1" I'll get my result: testuser. But if i try "select * from..." I'll get: 1 //correct ID t // only first letter. Iam looking arround quite a ...
Probleme solved: The resultset is an Char pointer on an pointer. By dereferencing it with * it will only provide the first char if the strong. So without it works fine: Change "CString strTest(*m_mysqlRow[i]);" to "CString strTest(m_mysqlRow[i]);" . and it will work as intended.
67,094,424
67,094,580
Necessity of default constructor for members
I am confused by a compiler error I'm receiving with C++14. It concerns the necessity of a default constructor for member variables. In the code below, class A does not have a default constructor. class B has a member of type A that it move assigns. The compiler complains about the lack of default constructor for A, ev...
Is there some implicit call to the default constructor of A happening in the constructor of B that I'm missing? Yes. From the reference Before the compound statement that forms the function body of the constructor begins executing, initialization of all direct bases, virtual bases, and non-static data members is fin...
67,094,560
67,094,661
Problem joining char* to filesystem::path.filename() or char[260]
I Know similar questions have been asked before but none of them Helped in my case. Basically I want dstPath = %AppData% + "CURRENT EXE NAME" but problem is with different string types and string concantation SIMPLIFIED CODE :- #include <stdio.h> #include <string> #include <filesystem> #include <Shlwapi.h> #include <W...
You cannot assign to arrays. You should use strcpy() to copy C-style strings. strcpy(dstPath, getenv("APPDATA")); strcat(dstPath, p.filename().string().c_str()); Or the concatination can be done in one line via snprintf(): snprintf(dstPath, sizeof(dstPath), "%s%s", getenv("APPDATA"), p.filename().string().c_str()); F...
67,094,588
67,094,806
Who deletes previous nlohmann json object resources when value is replaced?
I have a key and I want to change the value of the key with another json object. json newjs = ...; json tempjs = ...; newjs["key"] = tempjs["key"]; What will happen to the data existed in newjs["key"] previously? Will nlohmann class automatically destroy it or is it a memory leak? OR do I need to manually era...
Internally it's a kept by an "ordered_map: a minimal map-like container that preserves insertion order". The actual standard container used in this ordered_map is a std::vector<std::pair<const Key, T>, Allocator> and the assignment you do is performed via T& operator[](const Key& key) { return emplace(k...
67,094,722
67,096,784
Why some compiler shows unfavorable output for a specific input?
Look at this code, In my VS code or some online compilers it gives favorable output, but when I'm submitting this on HackerRank or this online compiler I'm getting wrong output but only when I provide input as: 1 1 1 100...and I'm not able to spot the Error?..I'm providing question for reference. /*There will be two ...
Considering your inputs: 1 1 1 100, What are you doing in this code is You are pointing on index beyond your second array's size limit i < num2[1], this is why you are getting wrong outputs. Do some changes as, i <= num2[0];
67,095,158
67,095,198
What is the error in this code,In 2d vector how the extra elements gets added?
How again -1,2,-1 gets included in the next pair? The question is: Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. public: vector<vector<int>> threeSum(vector<int>& nums) { vector<int>r1; vec...
You forgot to clear r1 before adding new elemnets. if(nums[i]+nums[j]+nums[k]==0) { r1.clear(); // clear the vector (erase the extra elements) r1.push_back(nums[i]); r1.push_back(nums[j]); r1.push_back(nums[k]); resvec.push_back(r1); } Instead of clearing, you should declare r1 inside the inner if...
67,095,607
67,096,005
I need to make a bag using a Doubly Linked List with (element, frequency) pairs
Just like in the title, I need to make a bag using a Doubly Linked List with (element, frequency) pairs. By analyzing other projects I made, so far i made this: //bag.h #pragma once #include <utility> using namespace std; //DO NOT INCLUDE BAGITERATOR //DO NOT CHANGE THIS PART #define NULL_TELEM -111111; typedef int TEl...
Try this. void add(TElem elem) { node* n = nullptr; n = new node; n->info.first = elem; if (this->tail == nullptr) { //if we don't have an end if (this->head == nullptr) { //if we dont have a start this->head = n; //set the start to n } ...
67,095,841
67,102,791
The program does not show the corresponding letters grates correctly
This program ask for student score then it supposed to give corresponding letter for each grade and average price. The problem is: the code gives me only letter grade for a last grade. Can not figure out how to fix it. Could someone navigate me please? #include <iostream> using namespace std; char *calcGrade(co...
Your calcGrade function is broken in two ways: You calculate the correct letter grade for each student, then you try to store all of them. But you need to store each one as you calculate it. There should not be two for loops in calcGrade. I don't know what you think this does, but the second line overwrites the first...
67,095,993
67,096,696
C++ best way to create constructor and class instance
I'm pretty new to c++ language however I have experience with python and a little bit with java. Since c++ is pretty overwhelming and there is like always few ways to achieve certain behavior I have 2 questions related to oop. What is the best way to create class constructor with parameters? For example let's say we h...
The most C++-ish way to create a struct is struct_name{value1, value2}. And you don't need to declare your own constructor. If you really want to use a constructor, use the one with initializer syntax. Here is the difference. Let's consider a structure with two fields. So it looks like: {one, two}. When you use initi...
67,096,347
67,097,524
MPI Scatter losing values from the final partition
I have an array of numbers that I need to scatter to each node in an MPI program. The setup is that I have an array of numbers from 1 to 100 with all the even numbers except the number 2 removed. Due to the way I removed the even numbers, the number 2 is the last element in the array. So my array contains 51 odd number...
One approach is to use MPI_Scatter and add padding to the array so that its size is evenly divisible among processes. However, whenever a process has to manipulate that array it needs to ignore the padding part. Another approach is to use MPI_ScatterV, and "manually" divide the blocks among the processes. An example of...
67,096,550
67,096,855
Ambiguous name lookup with C++20 using-enum-declaration
Consider following code snippet with C++20 using-enum-declaration: namespace A { enum A {}; }; using namespace A; using enum A; gcc-trunk rejects it with: <source>:4:12: error: reference to 'A' is ambiguous 4 | using enum A; | ^ <source>:1:20: note: candidates are: 'enum A::A' 1 | namespace A...
gcc is wrong here (submitted 100'084). The grammar for using enum A; is from [enum.udecl]: using-enum-declaration:     using elaborated-enum-specifier ; Lookup for such a thing is defined in [basic.lookup.elab]: If the class-key or enum keyword in an elaborated-type-specifier is followed by an identifier that is not...
67,096,670
67,097,707
Connecting button to create and store an object in Qt C++
I am creating a Qt Widget based app and I want to be able to add objects to std::list<>(that store objects of some class) at runtime by using button(QPushButton). Is there any way to pass this list by reference so I can store created objects in it? AFAIK there is no way to use connect(Object1, signal, Object2, slot), b...
Without more context it's difficult to know exactly what you're trying to achieve but... given a variable objects defined as follows... std::list<QObject *> objects; You can connect a button's clicked signal to a lambda that captures objects by reference with... QObject::connect(&button, &QPushButton::clicked, ...
67,096,972
67,097,370
in C++, how to use Macro to reduce duplicate code?
Consider this lines of code: string name = getName(); SomeClass z; if (name == "a") { z.set_name_a("is a"); } if (name == "b") { z.set_name_b("is b"); } if (name == "c") { z.set_name_c("is c"); } ... How do I write a macro function to remove duplicate code? Specifically I am not sure how to change the fun...
I'd recommend you prefer to find a better approach to the problem, such as using a hash table. But since you asked about macros, the usual disclaimers apply (macros are bad, error prone, have poor error messages since the compiler reports on expanded code, have duplicate argument evaluation problems, can bleed into su...
67,097,053
67,097,314
Can concepts restrict the type member variables?
I'm using C++20 & I'm wondering if Concepts is at all possible to solve a situation like this. Let's say I have a function: template <typename F> void doSomething(F f) { f(); } doSomething accepts a callable objects (technically lambdas but shouldn't matter I think) & I want to ensure that no member variables of F h...
You can easily check if a simple struct/aggregate T contains any field with type TType using boost::pfr: #include <boost/pfr.hpp> template <typename TType, typename T> [[nodiscard]] constexpr bool has_any_data_member_of_type() noexcept { return []<std::size_t... Is>(std::index_sequence<Is...>) { return...
67,097,071
67,097,097
const int template does not seem to work inside a struct
I am working with a code which needs a struct template which should contain a constant int variable like this #include <iostream> using namespace std; template <typename T> struct person { T age; }; int main() { struct person <const int> man; man.age=18; cout << man.age; } Unfortunately, the code abo...
If you want T to be a const int, that means that age is const and can't be assigned to like you do with man.age=18; What you need to do is initialize age when you create man like person<const int> man{18}; and now age is 18 and can't be changed. Also notice that I removed struct. Unlike C, in C++ you do not need to...
67,097,553
67,097,807
How to color a region of an image in C++?
I would like to set all the pixels in a region of an image to the same color. I couldn't find how to do that in C++ using Opencv, if anyone can please help. I found this code in Python but it doesn't work for C++: It starts from the x,y coords of the region(bottom right of the image segment) up until the given x+width ...
Define the rectangle. OpenCV calls it a "region of interest" (ROI). Then call the Mat instance with that rectangle... sounds strange but bear with me. Now you have a view into the original Mat. Any changes happen to the same memory, and you see the changes in either object. Now you can use the setTo method to fill the ...
67,097,685
67,098,079
In visual studio 2010, how to inherit preprocessor definitions from parent project?
I have a project "First" with first.cpp #include<iostream> #include "second.h" using namespace std; int main() { #ifdef MY_MACRO1 cout << "MY_MACRO1 in first" << endl; #endif second(); return 0; } and a static library "Second" with second.cpp #include <iostream> #include "second.h" using namespace std; ...
Create a stand-alone property sheet and then have all relevant projects inherit that. Under the View -> Other windows -> Property manager right click on one of the projects and select "Add new property sheet", edit the properties for the sheet then add it to the other projects that need to inherit the relevant properti...
67,097,708
67,099,577
Optional function parameter based value of template parameter
So I understand I could probably solve this problem by simply using a parameter pack, but that solution seems a little ugly to me. What I want to do is something like the following: template<bool test> void Foo(int x, int y, int z, /*if test is set to true*/ int w) { if constexpr(test) { //use w for somethin...
You might decouple interface from implementation, use overloads and enable_if: namespace detail { struct Empty {}; template<typename T> void FooImpl(int x,int y, int z, T w) { constexpr test = std::is_same_v<T, Empty>; if constexpr(test) { //use w for something ...
67,097,726
67,100,025
How to initialize std::array<std::atomic<bool>> — no copy or move ctors
In my class, I want a std::array<std::atomic<bool>>, and I'd like to initialize it via member initialization, in the constructor. For example: struct Foo { Foo() : flags{{ true, true }} { /* no op */ } std::array<std::atomic<bool>, 2> flags; }; Sadly, this does not work, giving: er...
You can use an initializer-list for each item in the initializer list of the std::array. Here is how: struct Foo { Foo() : flags{{ {true}, {true} }} { /* no op */ } std::array<std::atomic<bool>, 2> flags; }; While the syntax is a bit strange, it works well (tested on GCC, Clang, MSV...