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,293,209
67,293,369
Can std::call_once be reset?
I wrote a function a while ago, based on Unreal Engine 4's blueprint implementation, that invokes a callable exactly once until it is reset: template<typename Callable> void DoOnce(Callable&& f, bool reset = false, bool start_closed = false) noexcept { static bool once = start_closed; if(!once) { once =...
The standard isn't kidding when they call it "once_flag". It's a flag that only gets set once. You can of course call the function multiple times, with different once-flag objects. But to do this properly, you need to hand each thread that might attempt to call it the new once-flag object. It can't just be a global or ...
67,293,228
67,293,324
why wont my for loop execute when using strings
I am writing a program in C++ that formats phone numbers into international format. I used visual studios to compile my code and it indicates I do not have any errors, yet the for loop on line 21 keeps getting skipped and I cannot for the life of me figure out why. Any ideas? #include <iostream> #include <string> using...
your condition seems wrong. this condition: for (i = 0; i > numOfDigits || count > 10; i++) should be for (i = 0; i < numOfDigits || count < 10; i++) because the conditions inside the for loop should be the conditions for the loop to keep going, so with your condition above, the code block inside will never be reache...
67,294,277
67,294,368
How to make custom operators in C++
I'm trying to make a class to write logs. And I want to replace std::cout to my own class. like below: LogWriter lw; lw << "LOG: TEST" << lw.endl; I made print function, but [lw.endl] command doesn't work. <logwriter.h> namespace logwriter { class LogWriter { public: LogWriter(); ~LogWriter();...
In your code (as it is standard) operator<< is overloaded for a function pointer. LogWriter& LogWriter::operator<<(LogWriter& (*pf)(LogWriter& lw)) {...} lw.endl is not a function pointer, (neither is lw.endl()) in this line: lw << "LOG: TEST" << lw.endl; As a matter of fact endl, at most, is a member functio...
67,294,399
67,294,567
convert from struct tm to std::time_t and convert back date will be changed
i try to convert from struct tm, to std::time_t with the following sample code : void test_time_t() { tm time; time.tm_year = 2004-1900; time.tm_mon = 11; time.tm_mday = 5; time.tm_hour = 12; time.tm_min = 2; char buff[25]; strftime(buff, 20, "%Y %b %d %H:%M",&time); printf("%s\n",bu...
You need to initialize your time: tm time{}; // zero-initialized "I just forget that tm is a C struct." That's common. You can however inherit std::tm and use your own type in the code instead. struct tm_ext : std::tm { tm_ext() : std::tm{} {}; // zero initialize on default construction }; You can now use tm_e...
67,294,863
67,294,927
What is the difference between these three object initialization
What are the differences with these 3 object initialization and when we are calling an object, what is literally happening? #include <iostream> class SampleClass { public: int a; SampleClass (int x) { a = x; } }; int main() { //are there any differences with these 3 object initialization?...
This initialization reference contains all the information you might need. From that reference we can get the following information: SampleClass obj = 5; // Copy initialization SampleClass obj1 = SampleClass(10); // Copy initialization SampleClass obj2(15); // Direct initialization Copy initialization Direct...
67,294,977
67,393,681
GRPC CreateChannel() error Could not get default pem root certs
I am using grpc 1.35.0 on Windows 10 and following sample code here to create a grpc channel for client to use. But I have a provide a root cert to create the channel, otherwise it complains below error. Then I write my client in a python version and I can create the channel without giving root cert. So, is this a grp...
Turns out it's grpc document issue, grpc-core C++ for windows does not support default root cert and need specify one by user. Please refer to here.
67,295,299
67,295,423
About #include mechanism in c++
Recently I run into some strange code, this is definitely a bad practice but kinda interesting. For example, I have three files: something.h class Something { void func(); } something.cpp void Something::func() { #define STRANGE() //do something #include strange.h return; } strange.h S...
Per C++ standard ([cpp.include]/3): A preprocessing directive of the form # include " q-char-sequence " new-line causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-...
67,297,509
67,297,588
Overloading != operator does not work if second argument is a rvalue
I am currently trying to understand operator overloading in C++.I tried overloading operator '!=' in the following code: #include <iostream> using namespace std; class MyClass{ int a=0;int b=0; public: MyClass() = default; MyClass(int x,int y){a = x;b=y;} MyClass(const MyClass& ob){a = ob.a;b = ob.b...
The compiler tells you. For instance GCC says: $ g++ -std=c++17 source.cpp && ./a.out source.cpp: In function ‘int main()’: source.cpp:24:12: error: expected primary-expression before ‘{’ token 24 | if(ob!={211,121}){ | ^ source.cpp:24:12: error: expected ‘)’ before ‘{’ token 24 | if(ob!=...
67,297,677
67,319,808
Core latency testing ARMv8.1
There is an interesting article about ARM8.1 Graviton 2 offering of AWS. This article has tests for CPU coherency where I am trying to repeat. There is C++ code repo in GitHub named core-latency using Nonius Micro-benchmarking. I managed to replicate the first test without atomic instructions using the command below to...
After doing some more experiments, I found the problem. In the code snippet below are the steps: making a comparison first (if state equals Ping) calling the class method set to do an atomic store operation. Code snippet from core-latency: if (state == Ping) sync.set(Pong); ... void set(State new_state) { state....
67,297,793
67,297,848
Checking null pointer && pointer->member value in the same if statement
This is a pretty basic question, but I could not find a clear answer: is it allowed to check that a pointer is not null and (&&) to also check one of its members value in the same if statement? Rephrased: is the right part of the condition in the example below even evaluated if f is null? I know this works in VS curren...
...is it allowed to check that a pointer is not null and (&&) to also check one of its members value in the same if statement? It's perfectly valid, it is not UB, the expression is evaluated from left to right, if the left part of the expression evaluates to false the right part is not evaluated. This is usually call...
67,297,878
67,299,165
How to remove a specific compiler warning in CMake
CMake seems to append some default compiler flags such as -Wall, -Wextra and so on when generating a Makefile project. One of those default flags is -Wsign-conversion and I would like to remove it from the list. Adding the suppression flag -Wno-sign-conversion like so target_compile_options(myTarget PRIVATE "-Wno-sign-...
If you don't want to query for the compiler ID/name and/or version (which quickly becomes a mess) you can use CheckCCompilerFlag (or CheckCXXCompilerFlag). The trick here is to not check for the warning disable flag, but for the warning itself. For example: include(CheckCCompilerFlag) check_c_compiler_flag(-Wsign-conve...
67,298,139
67,298,493
How to forward declare a class template?
I'm trying to implement the specification pattern.In that, I have a specification abstract class and an overloaded && operator which returns AndSpecification, which is actually derived from Specification class.Now I have the problem of circular dependency b/w AndSpecification and Specification.Specification is a class ...
You need forward declaration, and move definition of your method which need both class definition after those classes: // Specification.h #pragma once template <class T> class AndSpecification; template <class T> class Specification { public: Specification() {} virtual ~Specification() {} virtual bool...
67,298,358
67,313,733
error: no matching function for call to 'uWS::TemplatedApp<false>::ws<main()::UserData>(const char [3], <brace-enclosed initializer list>)'
I'm ussing uwebsockets to create ws server. main.cpp: int main() { struct UserData { }; uWS::App().ws<UserData>("/*", { /* Just a few of the available handlers */ .open = [](auto *ws) { /* MQTT syntax */ ws->subscribe("sensors/+/house"); }, .message = [](auto *ws, st...
It is because the compiler cannot convert 'brace-enclosed initializer list' to T&&. It can be solved by declaring the struct and converting it to Rvalue reference. struct UserData { }; uWS::TemplatedApp<false>::WebSocketBehavior<UserData> wsb = { /* Just a few of the available handlers */ .open = [](au...
67,298,395
67,301,301
Initializing very large C++ std::bitset at compile time
I want to store a static constant bitset of 216 bits, with a specific sequence of 1s and 0s that never changes. I thought of using an initializer string as proposed by this post : std::bitset<1<<16> myBitset("101100101000110 ... "); // the ellipsis are replaced by the actual 65536-character sequence But the compiler (...
You didn't really split the literal. It gets concatenated for compilation anyways. You are getting limited by the compiler. I don't think there's a way to increase this limit in MSVC. You can split it into two literals, initialize two bitsets, shift 1st part and OR with the other. Something like: #include <iostream> #i...
67,298,585
67,300,355
const class can extend lifetime of const member ref of temporary?
struct A { // something ~A() { std::cout << "A destruct!\n"; } }; class refWrapper { public: refWrapper(const A& a) : a_(a) {} ~refWrapper() { std::cout << "refWrapper destruct!\n"; } private: const A& a_; }; void func(const refWrapper& ref = A()) { // why ~A after ~refWrapper // Rather than aft...
With default arguments, the call func(); is equivalent to func(A()); // so func(refWrapper(A())); So, temporary A is created first (destroyed at end of full expression) temporary refWrapper is created second (bound to parameter reference) temporary refWrapper destroyed. temporary A destroyed. Notice that there is a...
67,298,880
67,299,193
When I delete a pointer and I don't have anything to assign on it immediately, should I use NULL or nullptr?
To rephrase the title, say I have deleted pointer *ptr and I want to assign something new to it later on only when I know that it is open, should I assign it with NULL or nullptr? And if perhaps neither is good, what would be a better way to go? From what I researched, NULL can be both an int and pointer type which cou...
You should not use NULL in C++ at all. If you need a null pointer value, then use nullptr. what is the purpose of NULL? It is a remnant inherited from the C standard library. It has no purpose in C++ other than to make some C code valid C++ without changes - which used to be an important part of the design of the C++...
67,298,924
67,300,138
Qt: use array of pointers to member functions for buttons' events
I have 6 buttons' clicked events that I would like to connect with 6 member functions using array of pointers. I can do it like this: QObject::connect(button_1, SIGNAL(clicked()), this, SLOT(Button1_Function())); QObject::connect(button_2, SIGNAL(clicked()), this, SLOT(Button2_Function())); ... But I would like to use...
The SLOT macro just wraps its argument in double quotes (after prepending "1" to show that it's a slot). Then the argument (in your case, "1(this->*(p_incr_buttons[i]))") gets looked up at run-time in a table of slots. But there is no slot called (this->*(p_incr_buttons[i])), hence the error message. But using the sign...
67,298,980
67,299,248
Defining a variable that is either an existing value or a new one in C++
Can I make the code below work without copying the object b? #include <iostream> using namespace std; class A{ public: A() = default; A(const A& a) { cout << "copy ctor\n"; } A(A&& a) { cout << "move ctor\n"; } A& operator=(const A& a) { cout << "c...
The overall type of your conditional operator is not a reference type, because the 'false' branch is not a reference. Thus, even in the 'true' branch, the b object has to be copied, in order to match the type of the Gen() call. The assignment makes a reference to that copied object. In your case, you can avoid this cop...
67,299,584
67,300,002
How to in-place-construct an optional aggregate?
How to in-place construct an optional aggregate? It seems I can only construct an optional single thing, and not an optional aggregate of things. #include <optional> #include <iostream> struct Unmovable { Unmovable(const Unmovable&) = delete; Unmovable(Unmovable&&) = delete; Unmovable& operator=(const Unmo...
If you can use C++20, then what you want is std::optional<Things>{std::in_place, "jadda", "neida"}; as seen in this live example. The reason you need C++20 is that the std::in_place_t constructor uses the form of T(std::forward<Args>(args)...) to initialize the object, but () only works for classes that have a const...
67,299,876
67,299,941
Why can't I access and use a member type aliases from an object?
Is it impossible to access a type alias (or typedef) of a templated class, from an object of that class? For example, why isn't the following possible: template <typename TKey, typename TData> class MyClass { public: using key_t = TKey; using data_t = TData; TKey key; TData data; MyClass(TKey _key, ...
You got the syntax wrong. Change it to: int main() { MyClass<int, float> mc{1, 1.0f}; using DataType = typename MyClass<int,float>::data_t; MyClass<int,float>::data_t newData = 2.0f; return 0; } If you want to get the aliases from mc directly, you can using DataType = decltype(mc)::data_t;. You can act...
67,299,914
67,301,011
How should I split up Rust modules so that they match corresponding C++ namespaces?
I'm trying to write a code generation tool that generates Rust wrapper functions for C++ code similar to bindgen. I'm facing a problem mapping C++ namespaces to Rust modules. I have a frontend that spits out a number of C++ functions defined in (potentially) different namespaces and I want to create matching Rust wrap...
All you need to be able to reexport a function definition is for it to be (1) visible to the reexporting module and (2) marked pub. In particular, its containing module does not need to be marked pub. That means you can do this: mod bindings_impl { pub fn func1() { /* ... */ } pub fn func2() { /* ... */ } } ...
67,300,258
67,302,431
C++ Splitt string and remove specific part of string
I want to save only dates in a vector and remove time. How can I do it in the best way? string text = "16.04.2021 02:00"; char space_char = ' '; std::vector<std::string> tokens; std::string token; std::istringstream tokenStream(text); while (std::getline(tokenStream, token, space_char)) { tokens.push_back(token); ...
I am not entirely sure if I got your problem right, but as Galik commented: if all your strings have this exact format, the easiest solution probably would be tokens.push_back(text.substr(0, 10)); If this is not the case but you can at least say that the string does not contain any additional spaces I would suggest: t...
67,300,293
67,303,716
Can I initialize a `constexpr static` member outside the class?
I'm working with a variable-width communications format. The structs to handle it look something like this: struct Header { int msgType = -1, len; Header() { len = sizeof(*this); } }; struct A : public Header { int x; char y; A() { msgType = 1; len = sizeof(*this); } }; // Further structs B, C, ... declare...
constexpr goes on the initializing declaration of a variable, so just put it outside the class: struct Header { int msgType = -1, len; static const std::size_t MAX_SIZE; Header() { len = sizeof(*this); } }; // ... declaration of subclasses ... inline constexpr std::size_t Header::MAX_SIZE = std::max({ sizeof(...
67,300,592
67,307,862
Read a list of parameters from a LuaRef using LuaBridge
[RESOLVED] I'm building a game engine that uses LuaBridge in order to read components for entities. In my engine, an entity file looks like this, where "Components" is a list of the components that my entity has and the rest of parameters are used to setup the values for each individual component: -- myEntity.lua Comp...
Found the problem, I wasn't reading the table properly. Instead of LuaRef myTable = getGlobal(state, tableName.c_str()); I was using the following LuaRef myTable = getGlobal(state, tableName.c_str()).getMetatable();
67,300,594
67,302,586
New control button doesn't have the correct Windows ID
I have a Window form application in C++. I added a new button and linked it to a function called ChangeTitle. But when I run the application and I press the button, it doesn't call the function. I checked and I noticed that when I click the button and check the Window ID of the button (wmId), which I set it to be 110 (...
I solved it. The problem was that I created the button control with hMenu set to 1. I changed it to #define IDM_CHANGE_TITLE 110 and now it works. Here is the fixed code: CreateWindowW(L"button", L"Change Title", WS_VISIBLE | WS_CHILD, 20, 50, 95, 25, hWnd, (HMENU)IDM_CHANGE_TITLE, NULL, NULL);
67,300,663
67,300,741
What the easiest way to convert part of a vector to string?
I want to convert part of a vector to a string, I found this std::string myString(Buffer.begin(), Buffer.end()); (Buffer is the vector) But here I converted the whole vector. What the easiest way if I want to skip first 5 chars of the vector and convert the rest? Like ''.join(Buffer[5::]) if it was python.
Just add your offset to begin. Since a vector has random access iterators, you can just use std::string myString(Buffer.begin() + 5, Buffer.end()); If you are not sure about what type of iterators your container is using, you can use std::next like std::string myString(std::next(Buffer.begin(), 5), Buffer.end()); wh...
67,300,703
67,301,114
How do I use the pthreads in a ROS C++ Node
I am trying to use pthread library inside the ros Node, I am including it as #include <pthread>. When I run catkin_make I get the error below. I created a simple thread as std::thread m1(move, 1); thread: No such file or directory #include <pthread> ^~~~~~~~~ The signature of the move function is void move(...
pthread is a C library available on some platforms and if you want to use the pthread_* functions you need to #include <pthread.h>. Since C++11 there is an abstraction layer on top of the native threading libraries which is available if you instead #include <thread>. You can then use std::thread - but you will still ne...
67,300,925
67,301,027
do free template functions need to be static and inlined?
Given this code // In header file template<typename T> inline static void my_func(T var) { std::cout << var << std::endl; } // Used in many cpp files: void some_function() { my_func(1); my_func("test"); } I just "upgraded" my free function to a template. It was static and inlined before. But now its a te...
All function templates are inline by default, so that keyword isn't needed. The static keyword was likely unnecessary before you converted my_func to be a template, and likely still is. Marking a free function static gives its name internal linkage, but since it's declared in a header that doesn't accomplish much here...
67,301,424
67,301,646
How to make a servo push a button with Arduino?
I'm trying to replicate the toy "uselsess box" with Arduino but in a different version. I have a button, a led and a servo motor. When I click the button the led lights up and after 2 seconds I want the servo motor to rotate and push that button again to turn off the led. The problem is that when I press the button th...
did you try this? bool check = true; void loop() { if (digitalRead(button) == HIGH && check) { check = false; if (ledState == 0) { ledState = 1; digitalWrite(led, HIGH); delay(2000); Servo1.write(0); delay(1000); Servo1.write(100); delay(1000); } else { ledState = 0...
67,301,475
67,317,076
Parse an ONNX model using C++. Extract layers, input and output shape from an onnx model using c++
I'm trying to extract data like input layers, output layers and their shapes from an onnx model. I know there is python interface to do this. I want to do something similar to this code but in c++. I have also pasted the code from the link. I have tried it in python and it has worked for me. I want to know if there are...
ONNX format is essentially a protobuf, so it can be opened in any language protoc compiler supports. In case of C++ Take onnx proto file (onnx repo) Compile it with protoc --cpp_out=. onnx.proto3 command. It will generate onnx.proto3.pb.cc and onnx.proto3.pb.h files Link protobuf library (maybe protobuf-lite), generat...
67,301,619
67,301,945
Why are time_of_day and hh_mm_ss two different types in C++20?
The C++20 standard defines 2 types that store a time during the day: chrono::hh_mm_ss and chrono::time_of_day. Both seem to store a duration since midnight, but because of DST-effects, callers should only use the hours, minutes, seconds and subseconds elements. www.cppreference.com gives exactly the same description fo...
https://en.cppreference.com/w/ is great, but not perfect. Ok, maybe it is. Where else can you get this kind of speed for fixes?! (note the second comment below this answer). :-) Howard Hinnant's GitHub library originally had just time_of_day. And that was part of the proposal for C++20. During the standardization p...
67,301,812
67,307,755
Drawing buffer to D3D9 texture
I'm trying to draw CEF buffer (returned on OnPaint) to D3D9 texture of the game, and game randomly premanently freezes. I figured out that code provided below is the reason of the game freeze, but still can't understand. What did I miss? // To create texture I use this code LPDIRECT3DTEXTURE9 tWebPNG; D3DXCreateTexture...
As discussed above, the paint event (and override method) are both called on the CefBrowser UI thread, and locking the same texture multiple times before it gets released will deadlock your entire D3D context. The fix is to separate the paint event handler (which is responsible for saving the rendered Chrome image to a...
67,302,026
67,302,450
array insertion l-value,r-values
This is just out of curiosity, while i was practicing array inserting for fun. The question is in the below code why a[i]=a[i+1] giving me some garbage value but setting it to a[i+1]=a[i] solves the problem. Logically they do the same , but I just wanted to know weather it has something to do with l-value and r-value r...
"Logically they do the same" No - the first version fills the affected part of the array with the same number (the last one in the array). The second shuffles numbers upwards to leave room for value. Do the loop manually with pen and paper and you'll see that the first version copies the same value down until pos. Yo...
67,302,215
67,302,326
Change values of struct with overloaded operator []
I'm trying to make a custom vector data structure. It will always contain 4 float values. I want to make it accessible via its attributes names, but also through operator [ ], so it could be also accessed with index like e.g. array. It should be editable through operator [ ], like vector or array. I've done so far this...
Having individual members and then using a switch statement is pretty much the way to do this. You don't need the vector though and can write the class like struct vec4 { float x = 0; float y = 0; float z = 0; float w = 0; vec4() = default; vec4(float x, float y, float z, float w) : x(x), y(y)...
67,302,688
67,303,214
How to use threading in cpp to enable parallel execution of two methods from two differents classes?
So, I've been trying to use std::thread object to enable execution of another class method during method execution of another class. Pseudocode is shown below. class A (init_A_args ){ A::method1(args_method1) { method1 functionality; return; } A::callback_method2(args_method2) { method2 functionality; ...
You can provide std::thread object with a callable object (something that can be invoked) and the thread object will run the callable object. If you don't want the thread to block execution you should detach the thread, so it becomes a daemon thread, meaning it runs in the background not blocking the main thread of exe...
67,303,146
67,433,711
'fatal error: 'wchar.h' file not found' error with the new macos 11.3 update
I'm totally new to c++ (just started learning from scratch yersterday). Today I had this macos update to 11.3 and now when I run my c++ code in clion I get this error, ====================[ Build | untitled | Debug ]================================ /Applications/CLion.app/Contents/bin/cmake/mac/bin/cmake --build /Users...
"We suppose that Tools | CMake | Reset Cache and Reload project should help in this case." (https://intellij-support.jetbrains.com/hc/en-us/community/posts/360000919219-Clion-can-t-compile-because-of-wchar-h-not-found-after-updated-Mojave-in-mac-) That worked for me
67,303,258
67,303,378
Why does break statement terminate program?
I have a break statement to exit the loop in: while (cin >> text){ if (text == "break"){ break; }; cout << text << endl; words.push_back(text); } The problem is that program just stops afterward with Exit code: 0 (normal program termination). Here is my full progra...
You've written sort(indices_sorted.end(),indices_sorted.begin()); which violates a pre-condition of std::sort, which is that the second iterator must be reachable from the first by incrementing it. This won't be the case in your code unless indices_sorted is empty (i.e. begin is equal to end), and so you're invoking u...
67,304,069
67,308,168
C++ does not recognize string as keyword
I tried the following code: #include <iostream> using namespace std; int main() { char string[4]='xyz'; return 0; } Since string is a keyword the compiler should give error but it runs fine. Can anyone explain why it compiles successfully.
string is not a keyword. It's the name of a type declared in the standard library. When you give it a name, you're doing something called shadowing. This is more clear in the following example: { int x = 0; { int x = 5; std::cout << x << std::endl; } std::cout << x << std::endl...
67,304,070
67,317,201
LibTorch C++: Converting Tensor back to Image, Result is 3x3 Grid?
I am working on some code that takes a matrix object (assume this behaves as cv::Mat), converts to tensor, does a forward pass through my model, and converts back to my matrix object. However I have one issue persisting. That is, my resulting matrix is a 3x3 grid of the result. I tested my conversion codes (Matrix to T...
I have found the solution to my problem. Citing yugo's answer to this question: Convert pytorch tensor to opencv mat and vice versa in C++ You need to make sure to reshape the data: tensor_image_cpy = tensor_image.reshape({ width * height * depth }); Hope this helps others who run into this issue.
67,304,253
67,305,203
How can I copy a part of 4D array from Host memory to Device memory?
I have flattened 4-D array in Host array. And I want to copy a part(red region) of the 4-D array like below image. I don't know how to copy the not serialized array. The reason I copy a part of array is because the original array size is over 10GB and I only need 10% of it. So at first, I tried it with for loop. But i...
For copying a subset of an array, cuda provides cudaMemcpy2D (can copy a single 2D section of a multidimensional array) and cudaMemcpy3D (can copy a single 3D section of a multidimensional array). You can find lots of questions here on the cuda tag to discover how to use those. There are two problems with those approa...
67,305,412
67,305,472
Create an instance of an object C++
I have recently picked up C++ but I am having problems in some areas as I am used to Java and I am not sure if I am going about things the right way. I have a text file which lines are structured like this C;101;1;1;4;10; H;102;9;0;1;8;2 C;103;9;9;2;5; C;104;0;9;3;8; ; being the delimeter C is used to check if its a C...
The compiler should have generated a warning, "Expression with possibly no effect" (or similar), for every line in your constructor. Read the warnings - they're useful. Bug(string type, int id, pair <int, int> position, int direction, int size, bool alive) { this->type = type; this->id = id; ...
67,305,551
67,309,056
How do I use ctypes.create_string_buffer to pass it as a char * argument for a C function?
I have a C/C++ dll with a function: int get_camera_info(char * description, char * serial_number, char * manufacturer) This function takes the arguments and modifies them, so that you could print them. I'm trying to use this DLL from Python by using ctypes. I guess I would need to use ctypes.create_string_buffer to cr...
Here's the basics. Although not strictly required in this case, setting .argtypes and .restype correctly helps ctypes marshal parameters correctly and detect incorrectly passed parameters. Similar to passing arrays to C functions, create_string_buffer returns an c_char_Array_array_size object, but it is marshaled as a...
67,305,823
67,314,683
specializing operator new and operator delete of some class
In order to selectively trace the allocations of particular types, I have created the following construct: struct my_alloc { static void* operator new(size_t sz) { /*...*/ ; return calloc(1,sz); } static void operator delete(void *ptr) { /*...*/ ; return free(ptr); } }; and whenever I wanted to follow the inte...
You might inherit from Empty class: struct Empty{}; using A_alloced = A<my_alloc>; using A_non_alloced = A<Empty>; allocator might be a wrong name, especially as you wanted to subsitutes with std::allocator.
67,306,289
67,306,522
How to access type's index in the template type parameter pack?
I would like to access type's index when expanding a type parameter pack into an std::tuple<...>. For example, given a type pack of <int, double, float> I would like to build an std::tuple<...> that looks as follows: std::tuple<std::array<int,0>, std::array<double,1>, std::array<float, 2>> // ^ ^ ...
You are on the right track of nesting to have two packs. What you need now is a std::integer_sequence that lets you create the desired pack instead of hardcoding it via Baz<0,1,2> bar;. The basic idea is to define a function template that takes a std::integer_sequence<size_t,I...> parametrized on a pack and call that w...
67,306,334
67,307,209
time complexity of priority_queue in C++
I have been trying to figure out the time complexity of a priority_queue. This post here states that the complexity of this container depends on the underlying container. My question is for a priority_queue declared as such using mypair = std::pair<int, int>; std::priority_queue<std::pair<int, mypair>, std::vec...
Heap insertion and extraction have the worst case complexity relative to the height of the tree, thus O(log N), plus the complexity of the underlying data structure. In case of a vector, push_back has an amortized complexity O(1), and pop_back O(1). Therefore it can be said that the total time complexity of push and po...
67,306,337
67,306,498
"a coroutine's promise must declare either 'return_value' or 'return_void'" Error Visual Studio 2019 C++ 20
VS2019 latest c++ compiler. Error is :"a coroutine's promise must declare either 'return_value' or 'return_void'" Example pulled from David Mazièreshttps://www.scs.stanford.edu/~dm/blog/c++-coroutines.html blog that works under a different compiler,GCC 10.2. I can't get the source code to compile in VS2019. #include <c...
Both compilers are correct. Flowing off the end of a coroutine when the promise type doesn't have return_void is undefined behaviour: [stmt.return.coroutine]/3: If p.return_­void() is a valid expression, flowing off the end of a coroutine is equivalent to a co_­return with no operand; otherwise flowing off the end of...
67,306,747
67,306,808
Why can a struct implicitly convert to match a function's parameter type, but not if it's an assignment operator with the default one deleted?
example: struct c{ void operator=(bool){} operator bool(){ return false; } c&operator=(const c&)=delete; }; void f(bool){} int main(){ c a,b; f(b); //works fine a=b; //g++ -std=c++17 says: error: use of deleted function ‘c& c::operator=(const c&)’ } Why does the f(b) call convert...
Overload resolution works by finding the best match, and then checking the accessibility of the function. If you cannot access that function, because its protected/private or deleted, then you get an error. With f(b); the only valid option is operator bool() so the code works. With a=b The compiler finds c&operato...
67,306,864
67,307,948
how i could solve this problem with ifstream
when I run this code its only work with visual studio, in online compiler always tell me "cant opening file" #include <iostream> #include<fstream> #include<string> #include<iomanip> using namespace std; ifstream input("C:/Users/ACER/Desktop/words.txt"); if (!input.is_open()) { cout ...
An online compiler probably cannot open file on your computer using C++ code since that's not how the web works. It would have to route through some Javascript system, which is possible to create, however it seems the creators did not implement that when setting up their compiler. You might try using file://C:/Users/AC...
67,306,891
67,322,826
Algorithm behind score calculation in FAST corner detector
How is the score for a detected corner is calculated in the FAST corner detector? I read the original paper "Machine Learning for High Speed Corner detection" but in the score calculation portion nothing is explicitly mentioned as to which N contiguous pixels they are referring at. Is it the N contiguous pixels that sa...
The docs online confused me too: The score function is defined as: “The sum of the absolute difference between the pixels in the contiguous arc and the centre pixel” I'm pretty sure OpenCV doesn't calculate score like that. If you patiently read the source code you mentioned, you will find that the function cornerSco...
67,307,134
67,307,308
How to make it show the actual value of the array, not the pointer value ( actually don't really know what means "-8589934604")
// i really cant figure out what is wrong in this code, and i cant get the initial array values of zero. #include <iostream> int* create() { int arr[5] = { 0,0,0,0,0 }; return arr; } void disp(int arr[]) { for (int j = 0; j < 5; j++) { std::cout << arr[j]; } std::c...
Your code fails to run for me. I got the warning "address of local variable ‘arr’ returned". When you are using array references like this, you should use dynamic arrays to avoid these kinds of errors. I changed arr accordingly and it works. int* create() { int * arr = new int[5] {0,0,0,0,0}; return arr; } How...
67,307,418
67,307,597
Why does a preprocessor directive affect my C++ vector?
I have a class with a block of members that are wrapped in a preprocessor directive: class MyClass { ... #ifdef MyConditionalCompilation MyObject myObject; std::string myString; uint _myInt; #endif ... } The class also has a member vector std::vector<int> myVector. The conundrum is as follows: When I place the ...
Is your class defined in a header, perhaps? In this case make sure every file that #includes it has MyConditionalCompilation set with the same value as its implementation, because in C and C++ each .cpp/.cc file is compiled as a single, standalone translation unit. Given that you are conditionally adding fields to MyCl...
67,307,437
67,315,804
converting json++ implementation to use rapidJSON: handling mixture of string and wstring
I'm converting some code that originally used the json++ library to now use rapidJSON. The code serializes and de-serializes various objects using json files. In json++, it looks something like this: serialize: string normal = "normal"; wstring wide = L"wide"; JSON::Object json; json["normal"] = normal; json["wi...
I think you need to use conversion here, I have go through the doc and src of RapidJSON, and confirmed that we can't mix GenericValue with Value. We can use the wstring_convert, see this answer as the reference. Or with boost.
67,307,554
67,310,331
Instantiation of friend function defined inside a template
This is a follow up of this question. The original case was something else, but in the course of me writing a poor answer and OP clarifying, it turned out that we probably need the help of a language-lawyer to understand what is going on. In Thinking in C++ - Practical Programming Vol 2 one can find the following examp...
[temp.inst]/2 The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the definitions, default arguments, or noexcept-specifiers of the class ... friends... [temp.inst]/4 ... A function whose declaration was instantiated from a friend function def...
67,307,961
67,308,072
How to access a structure array from 2 different files?
How would I go about doing something like this? header.h struct myStruct; extern myStruct array[]; main.cpp #include "header.h" struct myStruct{ int a = 0; }; myStruct array[5]; array[0].a = 1; file2.cpp #include "header.h" std::cout << array[0].a;
Well, first of all you should put struct declarations in the header files. Second, you can't put assignments to arrays or std::cout statements just loose in files. I'm assuming you did this for short code and not because you didn't know it needed to be in a function, but I'm pointing it out just in case. Third, struct ...
67,308,346
67,308,445
Overriding a virtual function of a nested class
Let's say I have the following class: class Base { public: class Nested { virtual void display() { std::cout << "Not overridden" << std::endl; } }; Nested N; }; And I have another class named Derived that inherits from the class Base. Is it possible to override the display() met...
Nested class (from cppreference): The name of the nested class exists in the scope of the enclosing class, and name lookup from a member function of a nested class visits the scope of the enclosing class after examining the scope of the nested class. Like any member of its enclosing class, the nested class has access ...
67,308,498
67,317,475
Include libqtforandroid.so or libqtforandroidGL.so in package?
I try to run the QT C++ usb debugger on an Android smartphone, altough there is a compilation error (on the screenshot #1). The downloaded version of QTCreator is 4.14.2 with Qt 6.0.3 MinGw 64-bit.
Ok, it's solved, you just need to delete the existing ".user" file from the project directory and choose your Android kit when you open up the project again.
67,308,570
67,308,671
Extract type of input parameter in templated function taking a function as parameter
I have this function: template<typename T, int (*F)(T&)> void DoStuff(T& s) { auto an = make_any<T>(s); cout << _GetDataFromAny<MyStruct, F>(an); } Which needs to be called like this: DoStuff<MyStruct, Fun>(s); This works fine, however I don't like having to specify the first type, since it is part of the sign...
Disclaimer: This answer went through a series of edits and corrections, many thanks goes to Jarod42 for his patience and help, and cigien for fruitful discussion. It is a bit longer than necessary, but I felt it is worth to keep a bit of the history. It is: the most simple / the one I would prefer / some explanation of...
67,308,689
67,308,719
Segmentation fault when returning a nullptr in my strpbrk function
I need help returning a nullptr in my strpbrk implementation. Is there a way to return a nullptr without triggering a Segmentation fault? Here's my code: #include <iostream> const char *STRPBRK(const char *haystack, const char *char_list) { // TODO for(unsigned int i = 0; i < haystack[i] != '\0';i++){ for(unsigned ...
Check the return value in caller and avoid passing nullptr to std::cout. #include <iostream> const char *STRPBRK(const char *haystack, const char *char_list) { // TODO for(unsigned int i = 0; i < haystack[i] != '\0';i++){ for(unsigned int j = 0; j < char_list[j] != '\0';j++){ if(haystack[i] == char_list[j])...
67,308,839
67,309,068
The opposite of bitwise AND
I don't like so many nested ifs, which is why I want the opposite of that condition if (section_header[i].Characteristics & IMAGE_SCN_MEM_WRITE). What would it be? I tried with if (section_header[i].Characteristics & ~IMAGE_SCN_MEM_WRITE) continue, but it's not the correct one. for (WORD i = 0; i < nt_headers->FileHead...
If you are certain that your mask will only have one bit set, then you can test whether that bit is cleared (i.e. not set) in value by doing if (~value & MASK) // bit is clear However, I do not recommend this. While logically correct, it is a lot less idiomatic than the other suggested options if (!(value & MASK))...
67,309,504
67,309,620
Is seek_ptr unique per file?
Sorry but I didn't find clear answer to my question, I know that each file has its own seek_ptr, let's suppose the main process opened connection to file_A then before doing anything called fork() Then forked process reads 2 chars, which is correct? will seek_ptr be equal to 2 for both files? seek_ptr be equal to 2 f...
In Unix, (pid, fd) acts as a pointer into the kernel's table of open file descriptions. When a process is forked, the child process will have a different PID, call it pid2. So (pid2, fd) is a different key from (pid, fd). However, these two pointers actually point to the same open file description: fork does not fork t...
67,309,582
67,309,660
How do you find the last non-zero number in an array?
I am currently writing a console program in C++ for interpreting Chip-8 code, and I need to address the stack, requiring me to find the last non-zero entry in the stack array.
Assuming your stack is something like std::array<int> you can do: auto rit = std::find_if(std::crbegin(my_stack), std::crend(my_stack), [](int v) { return v; }); auto idx = std::distance(std::cbegin(my_stack), rit.base()) - 1; Here is a live example.
67,309,871
67,315,288
When adding a vertex to a weighted undirected graph, which weight stays?
I'm doing an adjacency list implementation of a graph class in C++ (but that's kinda irrelevant). I have a weighted directionless graph and I am writing the addVertex method. I have basically everything down, but I'm not sure what I should do when I add a vertex in between two others that were already there and had the...
I guess it depends on what you want to achieve. Usually, an adjacency list is a nested list whereby each row i indicates the i-th node's neighbourhood. To be precise, each entry in the i-th node's neighbourhood represents an outgoing connection from node i to j. The adjacency list does not comprise edge or arc weights....
67,309,934
67,310,149
Warnings when using Boost Serialization with -Wall -Wextra
I'm trying to use Boost.serialize. It appears to work fine, but I'm getting warnings when I turn on -Wextra and -Wall warnings with g++ (Version 10.2.0). It ran fine, and compiled fine when I switch off the warnings. However I'd like to be able to get rid of them properly. I've been trying for hours but cannot find a s...
It's easy to fix, just remove the unused argument's name, or comment out its name. struct minimal { minimal()=default; minimal(int in) : x {in} {} template <typename Archive> void serialize(Archive & ar, unsigned /*vers*/){ ar & x; } int x; }; With C++17 ...
67,310,128
67,310,165
Assigning an object to C++ array
I'm examining the following code in C++: #include <iostream> using namespace std; class Person{ public: int age; Person(int age){ this->age = age; } }; int main() { Person a = Person(2); Person temp[] = {a}; temp[0].age = 5; cout << temp[0].age; return 0; } So my guess i...
Person temp[] = {a}; is not assignment, but initialization (aggregate initialization): Each direct public base, (since C++17) array element, or non-static class member, in order of array subscript/appearance in the class definition, is copy-initialized from the corresponding clause of the initializer list. So temp is...
67,310,950
67,311,098
Creating an object inside a class throws an error in c++
I am attempting to connect to Sql Server with c++ using sqlapi++. I have gotten my code to work properly in my main function and when I am not instantiating an object within a class, but when I try to move my code over to a separate class I get errors. The errors I'm getting are: Expected a type specifier and syntax...
Initializing cmd in a constructor is an easy way to understand class initialization. Something like this: class DbConnection { SAConnection con; SACommand cmd; // this is just a declaration int age; int id; public: // this is the constructor DbConnection() : con() , cmd(&con) ...
67,311,180
67,311,302
How to only draw the rectangle when choosing from the menu?
I am writing a program that draws a rectangle with the mouse when and only when the user selects it in the menu, if the user does not select it will not draw. Up to now, I have successfully drawn the rectangle with the mouse, now how can I create a menu so that the user can choose to draw the rectangle? This is my prog...
Add a variable that indicates which shape has to be drawn: int shape = 0; Set the variable in menu: void menu(int choice) { switch (choice) { case 1: shape = 1 break; } glutPostRedisplay(); } Draw the scene dependent on shape: void display() { glClear(GL_COLOR_BUFFER_BIT); ...
67,311,569
67,311,956
What does "-flax-vector-conversions" exactly mean for ARM compiler?
I am tring to write a xxx.toolchain.cmake from arm-linux-gnueabihf gcc/g++ compiler. What confused me is, whether should I use -flax-vector-conversions compilation flag or not. I read the doc/man page of the compiler, and it tells: -flax-vector-conversions Allow implicit conversions between vectors with differing numb...
GCC offers vector extensions that are meant to provide a way to access SIMD instructions in a machine-independent way (as opposed to intrinsics). This involves special vector types defined with __attribute__((vector_size(n))) to help the compiler understand the packed multiple-element data types that SIMD instructions...
67,311,618
67,311,871
copying static array to dynamic array c++
So I was playing around with some basics in c++ when I noticed this: int * ptr = new int[3], arr[3] = { 11,13,15 }; for (int i = 0; i < 3; i++) ptr[i] = arr[i]; cout << ptr[0] << ' ' << ptr[1] << ' ' << ptr[2] << endl; this code will perfectly insert and print out the values: 11 13 15. Whereas when I writ...
As @Ch3esteR points out in the comment. The problem is that you are reallocating your array on each iteration, and thereby zeroing (or in your case, catching some random values on the heap). I would say that the bigger solution might be to use standard containers for handling memory. Here is a solution for fixing your ...
67,311,712
67,311,787
Writing/reading strings as binary into random accessed file
Simple question: I want to write strings of fixed length into a binary file (that is, as binary), as illustrated in the following snippet. The writing "looks" fine, but reading from the file doesn't work (compiles and runs without crashed, but doesn't give the expected result). #include <iostream> #include <fstream> #i...
This uses the constructor that takes an std::initializer_list: std::string s2 {5, '\0'}; ... and creates a string with 2 characters with the values 5 and 0 (or whatever \0 is). It should be std::string s2 (5, '\0'); Example: #include <iostream> #include <fstream> #include <string> #include <vector> int main() { {...
67,313,382
67,313,984
Reverse of a number using recursion with return and without return
Why does the following code prints 0 in the main function without the return statement on the recursive function call: #include <iostream> using namespace std; int reverse(int num, int rev = 0) { if(num == 0) return rev; reverse(num / 10, rev * 10 + (num % 10)); } int main() { cout << reverse(123);...
Let's visualize execution of this code. #include <iostream> using namespace std; int reverse(int num, int rev = 0) { if(num == 0) return rev; reverse(num / 10, rev * 10 + (num % 10)); } int main() { cout << reverse(123); return 0; } reverse(123, 0) ⟶ reverse(12, 3) ⟶ reverse(1, 32) ⟶ reverse(0...
67,313,732
67,313,966
Memory leak after moving a std::string with placement new
I have a structure that contains a string and that structure is used in a vector. When the vector grows, all of the elements are moved to the new allocation. Unfortunately, this move also results in std::string leaking memory. Here are a few minimum reproducible cases. This first example will illustrate where a memory ...
Moving from an object does not imply that the destructor does not need to be called. Any constructed object needs to be destructed: { std::string s; std::move(s); } // s’ destructor is run here! The same is true for the object in your code that you constructed explicitly via placement-new (at the address move)...
67,313,767
67,314,033
Casting object pointer to double void pointer (pointer to pointer to void)
I have a class method in a library (can't change it) which takes a double void pointer as one of its arguments. The declaration is as follows: bool Queue::pop(void **packet, int &size, unsigned short &sn) In my application code, I want to pass this function a pointer to another kind of object, in this case a GstBuffer...
For all intents and purposes a void pointer can hold addresses of any object (data type), i.e. it can point to any object, and can be typecasted to any object, your code is valid, I would just use a more idiomatic cast: Q->pop(reinterpret_cast<void**>(&buf), size, sn); §7.3.12 Pointer conversions [conv.ptr] A prvalu...
67,314,335
67,314,389
Does std::list variable in the class need initialization?
I have recently read something like this. I konw it is not so complex. But as a beginner, I just don't know why it works, so here is the description. #include <list> #include <iostream> using namespace std; template <typename T> class A { public: list<T *> testlist; A(); ~A(); void m_append(T* one); ...
Data member testlist is not mentioned in the member initializer list of constructor of A, and doesn't have default member initializer (since C++11), then it would be default initialized via the default constructor of std::list. when a base class or a non-static data member is not mentioned in a constructor initialize...
67,315,201
67,318,172
Creating a timeout method in a gtkmm app causes "void value not ignored as it ought to be" error
I have just gotten started with gtkmm and I am trying to update a label at a predefined interval by letting a timeout method call my Update() method. However, when writing the following line in the constructor of my MainWindow class: Glib::signal_timeout().connect(sigc::mem_fun(*this, &MainWindow::Update), 1000); I ge...
As Scheff mentioned in the comments, I forgot that MainWindow::Update needs to return a value of type bool, as that is expected by signal_timeout. Changing the Update method to the following, fixed the issue: bool MainWindow::Update() { std::cout << "Update" << std::endl; return true; }
67,315,255
67,315,304
Another set of parentheses after a function call [C++]
I've met this as an example in a book (rewritten in a more generic form), however, the problem which I'm curious about is not explained. It works, I've tested it. Q.: What does this another set of parentheses after the function call mean? How is this pattern/syntaxis called to read more about it? #include <iostream> ...
This is just some funny code to illustrate a point I guess. [](int const n) { return n*2; } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This code defines an anonymous function (lambda). It is transformed by the compiler to a construct similar to this one: struct { operator()(int const n) { return n*2; } }; Now compose() takes...
67,315,322
67,315,411
c++ template meta programming: how do you define the type trait "is_xxxxx_v" alias for my custom trait?
So I have been looking through this: https://akrzemi1.wordpress.com/2017/12/02/your-own-type-predicate/ It shows that you can take a custom trait (or predicate) is_thing<T>::type and alias that to is_thing_t<T> - e.g.: template <bool Cond> using enable_if_t = typename enable_if<Cond>::type; Now I want to do the same t...
You have two problems in your definition of is_really_bob_v: You are declaring it as template <bool T> while the template needs a type. You are trying to use a type alias to alias a boolean value. It should be template <typename T> // ^^^^^^^^ not bool inline constexpr bool is_really_bob_v = is_really_bob<T>::...
67,315,842
67,316,612
Is it possible to deduce template template parameter parameter (no typo :-) )
I have a class which implements data types for a huge project. I simplify it here to (actually it is a subclass passing typeID and subTypeID to iots parent class constructor): template<typename T,uint32_t typeID, uint32_t subTypeID> class TDataType { private: T _value; }; Note that using something similar to var...
It's certainly possible, the right syntax is simply: template<typename T1, uint32_t TYP1, uint32_t STYP1, typename T2, uint32_t TYP2, uint32_t STYP2> void convert(TDataType<T1, TYP1, STYP1> from, TDataType<T2, TYP2, STYP2> &to) { to = static_cast<T2>(from.value()); // assuming TDataType has a ctor TDataTyp...
67,315,910
67,315,937
Why am I able to use the names in the std namespace even though I'm "using namespace std;"?
Isn't there already a max function in the algorithm header file? And by using namespace std;, I'm importing the function to the global namespace (which takes to arguments, and in this case both would be integers, so it shouldn't be an overload). So why isn't there any naming conflict? #include <iostream> #include <algo...
So why isn't there any naming conflict? You're declaring a non-template max, and std::max is a set of overloaded function templates, so they're all overloaded. And the non-template version declared in the global namespace is selected in overload resolution here. F1 is determined to be a better function than F2 if im...
67,316,033
67,317,219
C++ binary files I/O, data lost when writing
I am learning C++ with the "Programming: Principles and Practice Using C++" book from Bjarne Stroustrup. I am currently studying chapter 11 and I found an example on how to read and write binary files of integers (section 11.3.2). I played around with the example and used a .txt file (input.txt) with a sentence which I...
When you attempt to do a partial read, the read will attempt to go beyond the end of the file and the eof flag will be set for the stream. This makes its use in the loop condition false so the loop ends. You need to check gcount of the stream after the loop to see if any bytes was actually read into the variable x. But...
67,316,038
67,316,846
MFC menus Open tabs dynamic menu
I am working with a MFC application, and would like to remove the dynamic entry that appears under "Arrange Icons". I am not sure how this is added to the application, or how could I switch that off?
The list of open windows is added to the "Window" menu by the MFC framework, in the application's main window handler for the WM_INITMENUPOPUP command. (Actually, the framework adds the items to all menus that already contain any command with an ID between AFX_IDM_WINDOW_FIRST and AFX_IDM_WINDOW_LAST – which includes t...
67,316,221
67,317,242
Passing smart pointer to function through non smart pointer argument
Consider the following function: void example(void **ptr){ std::cout << *ptr << "\n"; // pointer value std::cout << ptr << "\n"; // pointer address std::cout << **reinterpret_cast<int**>(ptr); // value } The function signature cannot be changed. Is the following code va...
It is not valid and has undefined behaviour. (If it appears to work, it's because your particular implementation happens to store the unique_ptr's underlying pointer as its first member in this particular situation. It is still 100% pure crystal-clear undefined behaviour, though.) If you can't change the function, you ...
67,316,311
67,321,976
Compiler fails due to recursion in MSVS2017
I am using compile time features of boost::hana::string for generating xaml markup strings for a GUI. I am using VS2017 configured as C++17 language, but there is some moment where strings are too long that I received the next message from compiler: fatal error C1202: recursive type or function dependency context too ...
The compiler is giving up because you are creating a template with too many parameters. The representation of a Hana string is hana::string<'<', '?', 'x', 'm',...> where each character is a non-type template parameter. This is generated by some tricks inside the BOOST_HANA_STRING macro. I suggest looking at the followi...
67,316,426
67,363,225
LogonUser() fails for Azure AD user when username is in UPN format even when password is correct
This is my code to check if the password entered by user is correct. My user is an AzureAD user logged in to a windows 10 Azure AD joined machine. if (LogonUser(upn., NULL, pwd, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &token) != 0) LogonUser fails with error 1326 . Invalid username or password. But the same...
Thank You Joseph Willcoxson setting the domain field to "AzureAD" fixed the issue. Hope microsoft updates the document soon.
67,316,473
67,316,570
Conversion Error when passing arguments to lambda comparator
I have a sorted vector of structures and I am trying to find the index of element that has the queried value in its member attribute. For this I am trying to use lower_bound, but I am having problems with the comparator lambda function. Here is a simplified version of my code: #include <iostream> #include <vector> #inc...
The comparator of std::lower_bound is supposed to take the object dereferenced from the iterator, i.e. the element as the 1st parameter, the value to be compared as the 2nd parameter. The type Type1 must be such that an object of type ForwardIt can be dereferenced and then implicitly converted to Type1. The type Type2...
67,316,885
67,317,514
Filter a graph by dynamic conditions / constraints
I am researching for a graph structure which can plan bidirectional for robots. But not only bidirectional, so it can go from A to B and B to A, also taking the orientation into account. So in some scenarios the robot is only allowed to move backwards oriented along the edge. See this example: Starting at 4, I can go ...
I would say that you need to split your graph into two, one with all the forward links and one with all the backward links. These two graphs can then be joined at the nodes where turning is possible, with a zero cost link. From your sample graph: Forward links 1F - 2F 2F - 4F 4F - 3F Backwards links 1B - 2B 2B - 3B...
67,317,240
67,317,610
Why can I omit the template parameter specification in some cases?
I have a question as I cannot explain why something works where I probably have made a mistake. Maybe somebody kind can help me to improve my C++ culture by explaining to me why this is so. For better transparency I simplifiy the code quite a bit. I have a template virtual class that is like this: template<class No...
Within the definition of a template class (more formally, the "current instantiation"), there is something called an injected-class-name, which is simply the name of the template sans arguments. For example: template<class T> struct Foo { Foo* ptr; // refers to Foo<T> }; When you derive from a templated class, the...
67,317,324
67,319,006
Enumeration values versus static constants in metaprogramming
I'm reading C++ Templates: The Complete Guide, chapter 23. Metaprogramming. At the end, it describes the difference in using enumeration values versus static constants in metaprogramming. Consider the following two implementations of calculating Nth power of 3: Enumeration implementation: // primary template to compute...
(enum implementation) because we should have temporary materialization there (prvalue -> xvalue conversion) and since temporary objects also have the address they do, but the temporary xvalue only exists for the duration of the function call. It's identical to passing the function an integer literal. So, an addressab...
67,317,355
67,323,079
C++ accepting command line argument with "-" symbol
I am new to c++ and trying to read command line arguments specified as below. ./helloworld -i input_file -o outputfile -s flag3 -t flag4 I tried hardcoding the flags by index as below int main(int argc, char *argv[]) { // argv[1] corresponds to -i // argv[2] corresponds to input_file // argv[3] corresponds to -o /...
Oh my gosh. Okay, you can do this manually, and I'll show you some code. But please look at getopt(). It already helps you out quite a bit, but it takes a little to get used to. But here's how you could code it manually: int index = 1; while (index < argc) { string cmnd = argv[index++]; if (cmnd == "-i") { ...
67,317,472
67,317,962
Write a program that gives the longest period of days when the temperature was always above K degrees
Multiple Selection My code works fine with the Test 1 inputs but with the Test 2 is stops at the first acceptable indexes and does not continue evaluating other elements and if I remove the break I'm getting off results Possible Solution I would like an assistance making the code to continue evaluating other elements e...
You only need one loop and no recursion, but you need more bookkeeping. Consider the following example execution for your second case. v - where you're looking ^ - the start of the current "at least K" range v 22 36 31 29 25 36 30 36 36 27 max: 0 v 22 36 31 29 25 36 30 36 36 27 ...
67,317,602
67,317,726
How to check if a type is instantiated from a certain variadic template class in a template function?
Let's say I have: template <typename...> class Foo { }; Then I define another function: template <typename... T> void Bar(const T&... arguments) { } How do I check if all Ts passed to Bar are all instantiated from Foo? Like: Foo<int> a; Foo<int, int> b; Bar(a, b); // OK int c; Bar(a, b, c); // ill-formed I want a wa...
You can create a trait to test for instantiations of Foo, and then fold it across all your parameters. template <typename> struct is_foo : std::false_type {}; template <typename... Ts> struct is_foo<Foo<Ts...>> : std::true_type {}; template <typename T> constexpr bool is_foo_v = is_foo<T>::value; template <typename....
67,317,689
67,433,512
Asp.Net Core Dependency Injection doesn't work, if it is started from unmanaged/native
First i try to explain the story. I wanted to extend an C++/MFC application with REST-APIs, and decided to use for this purpose Asp.Net-Core 5 in a library by bridging it to unmanaged code with C++/CLI library. (having a separete ASP application is doubled expenditure, and needed to be rewritten all the logic in C#. in...
The problem has been solved. Assembly resolving event with Assembly.LoadFrom() causes my ASP-assembly to be loaded (or mapped) twice. Loading it in different assembly-load-context means that, doubled Types, static variables and so on. In that regard my registered IServerImpl service searched in the controller with anot...
67,317,793
67,318,351
How to use write access using iterators and armadillo sparse matrices?
I have to replace some columns in a sparse matrix with columns from another sparse matrix that has the same nonzero elements, just different values, based on a condition. I am struggling with write access using iterators in Armadillo. The docs say that using sp_mat::col_iterator provides read/write access, however, whe...
Looking at the (generally excellent) Armadillo documentation, I think you are up a against a design issue. Quoting Caveats: to modify the non-zero elements in a safer manner, use .transform() or .for_each() instead of iterators; writing a zero value into a sparse matrix through an iterator will invalidate all curren...
67,318,103
67,318,201
Dereferencing Pointer to Node in Binary Tree
#include <bits/stdc++.h> using namespace std; struct Node { int key; struct Node *left; struct Node *right; Node(int k){ key=k; left=right=NULL; } }; int main() { Node *root=new Node(1); root->left=new Node(2); root->right=new Node(3); cout<<*root<<endl; } Why does this code throw an e...
You must either overload the ostream operator for struct: std::ostream& operator<<(std::ostream& os, const Node& node) { if (os.good()) { os << node.key << std::endl; // print pointer here if needed // ... } } or just write: cout << root->key << endl; *root just dereferences the po...
67,319,466
67,400,338
XML schema type information using libxml2
To begin with, the application I'm working on uses libxml2 to parse XML and to validate this XML against a schema, and I cannot use another XML-parsing library. The schema contains type information for elements in the XML, and I'm trying to get this type information but am not succeeding. Example schema: <xsd:schema xm...
The libxml2 API simply doesn't support inspection of schemas, only validation.
67,319,502
67,320,370
Templated constexpr variable
I want to confirm that this code is legal (or not legal?) C++17. #include <iostream> template<int N> inline constexpr float MyConst; template<> inline constexpr float MyConst<1> = 1.1f; template<> inline constexpr float MyConst<2> = 2.2f; int main () { std::cout << MyConst<1> << '\n'; return 0; } I don't g...
A constexpr variable must be immediately initialised. Hence the template for MyConst needs an initialiser/definition. GCC is going against spec by not requiring a definiton at first occurance. If you use a non-specialised form of the variable e.g. MyConst<3> you will get a similar error from GCC: <source>: In instan...
67,319,675
67,319,912
How to extract substring by using start and end delimiters in C++
I have a string from command line input, like this: string input = cmd_line.get_arg("-i"); // Filepath for offline mode This looks like a file as below: input = "../../dataPosition180.csv" I want to extract out the 180 and store as an int. In python, I would just do: data = int(input.split('Position')[-1].split('.csv...
Here's a (somewhat verbose) solution: #include <string> #include <iostream> using namespace std; int main() { string input = "../../dataPosition180.csv"; // We add 8 because we want the position after "Position", which has length 8. int start = input.rfind("Position") + 8; int end = input.find(".csv"); int ...
67,319,773
67,319,783
C++ Class that has multiple names
class Color { int r; int g; int b; }; I've created a class like above, and I would like to be able to use the same class using 'Colour' as an alternative of this class like below. Colour c; Would there be a way to create this simply?
You might create alias: using Colour = Color;
67,320,070
67,320,224
How to read text file with multiple delimiter?
I have a source code which reads the text file and stores into the vector which is a tuple type: #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <tuple> #include <algorithm> typedef std::vector<std::tuple<int, int, double>> VectorTuple; VectorTuple Readfile(std::string filename) {...
You can read and discard the | with: std::stringstream ss(line); int a, b; double c; char s; if (ss >> a >> s >> b >> s >> c) { data.push_back(std::tuple<int, int, double>(a, b, c)); }
67,320,261
67,320,299
Is there a wait function in C++?
I have been working on a program, and it makes use of the sleep() function. I want it to be cross platform for macOS, Linux, and Windows but having three branches is tedious to work with and is terrible to do. What can I do to make it cross platform? And what functions that make the program wait for a few seconds work?...
Since C++11, you might use std::this_thread::sleep_for using namespace std::chrono_literals; std::this_thread::sleep_for(250ms);
67,320,417
67,321,486
build c++ project using Make from two source directories in Linux
I have a c++ project in Linux in which source files are in 2 directories as shown below. Currently, the Makefile only compiles the files in the source/ directory, but not those in "/" directory. I've tried many hacks to no avail. How do you instruct Makefile to compile the source files in "/" directory after compiling ...
Well, first you search only for files in the SRCDIR directory: SRC = $(wildcard $(SRCDIR)/*$(EXT)) but not for files in the current directory. So of course make won't try to compile source files in the current directory. If you want to build files in the current directory you need to add them to SRC. Then you write ...