question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
71,979,469
71,979,876
How to use cmath functions like div in C++?
I am new to C++ and I am not sure how to use some of the cmath functions like div. #include <iostream> #include <cmath> using namespace std; int main() { int n; cin >> n; if (n < 10) { cout << div(n , 2); } return 0; }
The reason cout << div(n , 2) doesn't work is because div doesn't return a number, instead div returns a struct with 2 values in there, quot and rem. So when you use div(10, 3), it will returns a object with .quot == 3 and .rem == 1. To print the result of div, you would need to first store the result, then print each ...
71,979,526
71,979,820
How can I calculate the tens place value of 2^100 in C++?
How can I calculate the tens place value of 2^100 in C++? I tried this; #include <cmath> #include <iostream> using namespace std; int main(){ int answer; answer = (unsigned long long int)pow(2, 100) % 100 / 10; //zero cout << answer << endl; return 0; } But it printed 0 because of overflow. Python pr...
You have a problem with typecasting. As you can see from documentation std::pow return double So first step to solve our problem, try to remove type casting. std::pow(2, 100); // return 1.26765e+30 The next problem we can't use operator % with double type so we need std::fmod So final solution would look like this: in...
71,979,628
71,979,978
How can I output bit pattern of infinity and NaN in C++?(IEEE standard)
I'm reading Computer Systems: A Programmer’s Perspective, then I found the Special Values's definition and corresponding bit patterns. Now, I wanna output their bits using C++. I use their macro to output bits, obviously is incorrect, because macro defined to Integer! #define FP_NAN 0x0100 #define FP_NORMAL 0x0...
I wrote a quick-and-dirty double bit-wise output program a while back. You could modify it to work for float. It has ANSI escape sequences in it, which might not be suitable for your environment. The key part is just using a byte memory pointer and examining the bit state directly, rather than trying to get std::bitse...
71,979,970
73,921,436
Constant evaluation of self-assignment in member initialization
In the following program, constexpr function foo() makes an object of A with the field x=1, then constructs another object on top of it using std::construct_at and default initialization x=x, then the constant evaluated value is printed: #include <memory> #include <iostream> struct A { int x = x; }; constexpr int...
C++20 [basic.life]/1.5 states that the lifetime of an object (in this case, the object a) ends when the storage which the object occupies is released, or is reused by an object that is not nested within o (6.7.2). The standard isn't totally clear about when exactly the memory is considered "reused" (and thus, the old...
71,980,007
71,980,068
Take value out of std::optional
How do you actually take a value out of optional? Meaning take ownership of the value inside the std::optional and replace it with std::nullopt (or swap it with another value)? In Rust for example you could .unwrap your Option or do something like foo.take().unwrap(). I'm trying to do something like that with C++ optio...
operator*/value() returns a reference to the value held by the optional, so you can simply use std::move to move it to a temporary variable std::optional<std::string> opt = "abc"; // "take" the contained value by calling operator* on a rvalue to optional auto taken = *std::move(opt); This will invoke the rvalue refere...
71,980,108
71,980,166
C++ 20 lambda in template: unable to deduce ‘auto*’ from lambda
Given the following simple wrapper struct (inspired by this answer): template <auto* F> struct Wrapper; template <class Ret, class... Args, auto (*F)(Args...) -> Ret> struct Wrapper<F> { auto operator()(Args... args) const { return F(args...); } }; The following works: int this_works(){ return...
Wrapper expects function pointer, but template argument deduction won't consider implicit conversion (from lambda without capture to function pointer). You can convert the lambda to function pointer explicitly: int main(){ return Wrapper<static_cast<int(*)()>([](){return 42;})>()(); } or int main(){ return Wra...
71,980,406
71,981,318
Compile-time efficient n-ary cartesian product of parameter packs with a transformation
In a previous question, solutions were given on how to compute the n-ary cartesian product of parameter packs (see here, here (and here but for tuples)). Basically, we consider the following wrapper: template <class... Types> struct pack {}; template <class... Packs> struct pack_product {/* SOMETHING */} template <cl...
This works with O(1) instantiation depth template<template<typename...> class F, int N, typename...> struct fn_typelist {}; template<typename...> struct typelist {}; template<template<typename...> class F, int N, typename... Ts> typelist<fn_typelist<F, N, Ts>...> layered(typelist<Ts...>); template<template<typename....
71,981,096
71,987,740
Is there a way to start a new thread from dialog and use it in mainwindow in qt?
I have a function that downloads a torrent file. I need to download the torrent in a separate thread from the GUI thread, so I used QtConcurrent::run to start the download in another thread, but I started the download in a dialog and the dialog closes immediatly after the download has started, and (I'm new to qt, so I ...
Dialog gets deleted because it goes out of scope because it's instantiated on stack. Use heap. DownloadDialog* ddl_dial = new DownloadDialog(this); ddl_dial->exec(); Don't forget to delete it at some point to avoid memory leak.
71,981,297
71,981,551
How to run method/function on a separate thread in c++
I am a beginner to c++, so I don't know much here is a function void example(){ for(int i=0; i<5; i++){ // do stuff } } if I call this function, it will wait for it to be finished before continuing int main(){ example(); otherThingsGoHere(); otherThingsGoHere(); otherThingsGoH...
You need to use a std::thread and run the example() function from that new thread. A std::thread can be started when constructed with a function to run. It will run potentially in parallel to the main thread running the otherThingsGoHere. I wrote potentially because it depends on your system and number of cores. If you...
71,981,298
71,981,356
Cmake include header only library with -I option
I have a header only library that is contained in a "headers/" directory in the main project. When compiling from terminal I include it with #include "symbolicc++.h", but I need to pass the option -I "headers/" when compiling with g++. How can I include this in a Cmake project? (And also, in general how can I pass othe...
Adding include directories in CMake is done by using the target_include_directories directive. Use it this way (in your CMakeLists.txt): target_include_directories(${TARGET_NAME} PUBLIC ${SOME_INCLUDE_DIR}) Some more info: target_include_directories
71,981,501
71,985,008
Why #define variable in library is overridden from #define in calling application?
I am trying to a make plugin system which will have a header file for all plugins to include. In that header the version of the plugin system is defined in a #define like so: PluginHeader.hpp: #define PLUGIN_SYSTEM_VERSION "00.001" class PluginSystem { public: string GetSystemVersion(){return PLUGIN_SYSTEM_VERSION...
It is neither expected nor unexpected behaviour. Your program has undefined behaviour, so any outcome (whether it seems "right" or not) is possible. Your member function PluginSystem::GetSystemVersion() is defined (implemented) within its class definition, so is implicitly inline. The problem is, by having different...
71,981,976
71,982,014
What are the differences between "T a", "T a()" and "T a=T()" where T is a class?
Let T a C++ class. Is there any difference in behaviour between the following three instructions? T a; T a(); T a = T(); Does the fact that T provides an explicit definition for a constructor that takes no parameter change anything with respect to the question? Follow-up question: what about if T provides a definition...
T a; performs default initialization. T a = T(); performs value initialization. T a(); does not declare a variable named a. It actually declares a function named a, which takes no arguments and whose return type is T. The difference between default initialization and value initialization is discussed here.
71,982,220
71,990,718
Boost.Log: register attributes manually
In my code using Boost.Log I register a formatter for my log output register_simple_formatter_factory<LogLevel, char>("Severity"); This worked as expected for some time but now I tried to build on a different platform and are getting a linker error undefined reference to `void boost::log::v2s_mt_posix::register_format...
My guess is that this is because the installed library from the package repository was build with BOOST_LOG_WITHOUT_DEFAULT_FACTORIES defined. No, this is not the reason for the linking error. Disabling default factories does not remove factory registration APIs. But how do I do this? What specifically do I have to ...
71,982,437
71,982,547
Why does this code give no output on online C++ compilers?
I was experimenting with a statement in C++ using online compilers. When I try to run this specific code cout << num[i] + " " + num[i]; The online compilers give no output. I can change the + symbol to << but I want to know the reason that the code does not give any output on these online compilers. Online compilers t...
C++ is not like JavaScript or many higher-level languages, as in you may not delimit you data with +'s or ,'s. As shown in Lewis' answer, each item you wish to have printed must be separated by an insertion delimiter (<<). As for extracting, you may use the extraction delimiter (>>). In your case, you are doing mathema...
71,982,681
71,982,724
How could I fix the undefined identifier error in the bool functions of my program?
I was doing an assignment for my class but I cannot see how to fix the undefined variable error for the N under grid[][N]. I was wondering if anyone here would mind showing me in the right direction? This program determines the locations of peaks in an elevation grid of data #include <iostream> //Required for cin, cou...
As other users pointed out, your N is defined in the main() scope, not in global. But the definition of a isPeak() function is in global scope. Thus the compiler can not see the N you are requiring him to see. In order to solve the problem you can just define N in global scope (outside the main) #include <iostream> //R...
71,983,287
71,983,394
Specialize template function to return vector
Let's say I have a reader class over a file: class Reader { public: template <class T> T Read(); }; Its only function is the Read function that reads any arithmetic type (static_assert(std::is_arithmetic_v<T>)) from a file. Now I want to create a specialization of that function, which reads a vector from the f...
You can't partially specialize functions. You can overload them though, but the way of doing it is not obvious, since your function doesn't take any parameters. First, you need a way to check if a type is a std::vector<??>: template <typename T> struct IsVector : std::false_type {}; template <typename ...P> struct IsVe...
71,983,747
71,986,596
Correct input of a phone number with an input mask
Asked the last question, regarding the mask and how to put the cursor at the end of the typed text, but did not receive an answer. Trying to figure it out on my own, I realized that the question was asked very superficially. So. I tried to delve into the logic, looked at examples on different sites. ui->lineEdit_newCli...
You are calling text() method, according to Qt doc: When an input mask is set, the text() method returns a modified copy of the line edit content where all the blank characters have been removed. The unmodified content can be read using displayText(). So all you should do is finding symbol _ from template and setting...
71,983,947
72,088,887
Best HID device communication libary C++
I want to send bytes to a HID device. I've allready tried libhid but I can't get it to work. Does anyone know a libary or a easy way to send bytes via. HID in C++. Any help is appreciated.
Check hidapi lib. Also will be usefull for you same question on SO.
71,984,025
71,984,865
Yet another C++ pointer to array question
I haven't written C++ for over 25 years and evidently I've forgotten a lot, and the compilers are now far more strict than they used to be. Consequently, I'm struggling and failing to create a dynamically allocated array of pointers to arrays of 8 unsigned char. I believe I need a single variable that's a pointer. I ex...
I believe you want to get to know ** double pointer and how to use them. // explanation of what double pointer is. int **arr1; //double pointer: is a pointer to point to pointer // example int* p = new int(1); arr1 = &p; // points to pointer int*, note the "&" affront which returns the memory address...
71,984,101
71,984,165
member function pointers to virtual functions
How is the information about ptr to a virtual member function vs. non virtual function encoded within a function pointer. Clearly this is compiler dependent, but I would like to understand techniques used to encode this information. #include <cassert> struct X { virtual void f() { } void f1() { ...
A non-virtual class method is, basically, an ordinary function, so a pointer to a non-virtual class method is functionally equivalent to an ordinary function pointer, the function's address. Every non-static class method, whether virtual or not, receives an internal pointer. You know it as "this". This is, typically, a...
71,984,127
71,984,331
Is overloading on universal references now much safer with concepts in c++ 20
In the book "Effective Modern C++" by Scott Meyers the advice is given (item 26/27) to "Avoid overloading on universal references". His rationale for this is that in almost all calls to an overloaded function that includes a universal reference, the compiler resolves to the universal reference even though that is often...
I would say no. I mean, concepts help, because the syntax is nicer than what we had before, but it's still the same problem. Here's a real-life example: std::any is constructible from any type that is copy constructible. So there you might start with: struct any { template <class T> requires std::copy_const...
71,984,263
71,984,319
0 bytes in 1 blocks are definitely lost in loss record 1 of 1
I'm learning C/C++ as a newcomer from java in school and since it is weekend, I can't get help from there. I got an error like this: ==18== 0 bytes in 1 blocks are definitely lost in loss record 1 of 1 ==18== at 0x483C583: operator new[](unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-...
Even if you new 0 bytes, you still have to delete it. With every allocation, there's a bit of additional overhead beyond the number of bytes you asked for. (e.g. entry in the heap, the pointer itself, etc...). Side note: new items[0] does not return nullptr. And even if it did, delete [] nullptr is perfectly OK and sa...
71,984,693
71,984,700
Intermittent issue getting input
Can someone explain to me what's wrong with this code? It works sometimes, i.e. if I input 5, 5, 5, -1 on the terminal, it'll return 15. But other times, it returns 0. #include <iostream> #include <vector> using namespace std; int main() { int input; vector<int> input_vector; cout << "Enter -1 when done"...
You use a range-based notation for (auto i : input_vector) which gives for i the actual values stored in the array. But then you use it as input_vector[i]. This is wrong: i is the value of the element, not the index. So replace input_vector[i] by i. for (auto i : input_vector) { cout << "i: " << i << endl; sum ...
71,985,273
71,986,567
Template and anonymous namespace Issue
So I am updating some C++11 code to use gcc-11, and have run into a issue... Namely, it appears that in gcc-11 the constructor symbol, for a class, which is explicitly instantiated, does not exist if the constructor uses a type from a template class, defined in an anonymous namespace. A simplified example that produces...
Anonymous namespaces generally should not be used in header files. There are very few exceptions to this, and your use case is not one. You can use a namespace detail to suggest to people that the code inside is not meant for them to use. GCC 11 is doing nothing wrong here, your code is simply not portable.
71,985,285
71,985,344
Can static_cast be used in C source code compiled by C compiler?
I saw C-library with code that compiled by GCC 11 that do static_cast from C code and it perfectly fine for GCC. But when I tried to compile this library in VisualStudio (MSVC) I got error: (this library can be compiled by older VS2019(pre-2021 update)) fatal error C1189: #error: STL1003: Unexpected compiler, expected ...
static_cast is part of the C++ language, and more importantly it is not part of the C language, so attempts to use static_cast<> should cause a C compiler to emit compile-time errors. If you've seen it successfully used in "C source code" anyway... one likely explanation is that the "C source" code was being compiled a...
71,985,447
72,020,762
C++ performance optimization for linear combination of large matrices?
I have a large tensor of floating point data with the dimensions 35k(rows) x 45(cols) x 150(slices) which I have stored in an armadillo cube container. I need to linearly combine all the 150 slices together in under 35 ms (a must for my application). The linear combination floating point weights are also stored in an a...
As @hbrerkere suggested in the comment section, by using the -O3 flag and making the following changes, the performance improved by almost 65%. The code now runs at 45 ms as opposed to the initial 70 ms. int lastStep = (slices / 4 - 1) * 4; int i = 0; while (i <= lastStep) { result += tensor.slice(i) * w_id(i) + te...
71,985,523
71,985,536
Why is std::string not trivially destructible?
I'm a c++ noob and I've been reading about trivial destructibility. From this article on trivial destructibility, Trivially destructible types include scalar types, trivially copy constructible classes and arrays of such types. A trivially destructible class is a class (defined with class, struct or union) that: uses...
A std::string typically contains a pointer to dynamically allocated character data, so it needs an explicit destructor to deallocate that memory. So, if nothing else, it must either fail this criterion: uses the implicitly defined destructor or have a base class that fails it, in which case it fails this criterion: ...
71,985,595
71,985,649
How to set executable to Win32 in release mode
I've read on CMake's documentation that when calling add_executable, you can set the executable type to be Win32 by doing add_executable(target WIN32 source.cpp). I also know that you should use CMake generator expressions to check for build configurations like so: target_compile_definitions(target PUBLIC $<$<CONFIG:...
I am not really sure it makes sense given a WIN32 executable and a non-WIN32 executable do not have the same entry point, so the code would need to change as well. Still, here is how you would do it on CMake side: add_executable(target source.cpp) set_target_properties(target PROPERTIES WIN32_EXECUTABLE $<CONFIG:Releas...
71,985,957
71,986,021
Can we declare constructor before member variables?
Can the constructer declared before the member variable alter its value? I thought only the code below works, struct test { int a; test(int t): a(t) {} }; but I found the code below also works. struct test { test(int t): a(t) {} int a; }; Usually, in function, we cannot use the variable that is not ...
Actually in C++ there's an exception that there's no need for forward declaration of functions and variable of a class/struct. You can see my such examples on the internet like this: class foo { public: foo(int x) : my_var(x) {} private: int my_var; }; The above is 100% valid. You can also call a function of a...
71,986,185
71,986,217
How to use an object created inside a try block, outside of it?
Say I created an object inside a try block because I wanted to catch the exceptions thrown from it's constructor, how will I be able to use the object outside of that block? //Inputs given to t5 can throw an exception from the constructor. try { Time t5(23, 59, 59); } catch (invalid_argument& e) { ...
Depends on what kind of a default constructor Time has. If its constructor just zeroes three numbers, then your solution is ok. If its default constructor is expensive (or doesn't exist at all), you can put it into std::optional: std::optional<Time> t5; try { t5.emplace(23, 59, 59); } // ...
71,986,332
71,986,349
Why do we use dynamic allocation in a linked list?
In a linked list class, the code below is declaring Node<T> *newNode: void LinkedList<T>::push_front(const T& val) { Node<T> *newNode = new Node<T>(val); newNode->next = head; head = newNode; if(newNode->next == NULL) tail = newNode; } Why do we use dynamic allocation? Can't we just write Node<T> newNo...
A local variables such as Node<T> newNode(val); would be destroyed when exiting the function (or rather, when exiting the scope (aka braces, more or less)) that it was created in. But for a linked list, you want the nodes to live longer; as long as you want them to.
71,986,415
71,989,304
Does C++20 require of the implementations the use of IANA Time Zone Database?
C++20 <chrono> library comes with local time and time zone support. The interface of this library is compatible with that of IANA Time Zone Database, but the question is, does C++ Standard require that the implementation actually uses IANA Time Zone Database with all its historical data? The online C++ reference claims...
The Library Working Group of the C++ Standards Committee wrestled with those words for quite a bit, trying to get them right. The intent is that the std::lib supplies the IANA Time Zone Database. And perhaps even more importantly, all three major std::lib vendors are on-board with that intent. Not shown in the online...
71,986,909
71,988,721
Load ECDSA private key with Crypto++
I'm trying to load an EC key given as a byte array using Crypto++. Here is the key: -----BEGIN EC PRIVATE KEY----- MHcCAQEEIPQLO9zyl40X3lh1wbSR6S88aCsUvJr9R5n2pA3DbD9+oAoGCCqGSM49 AwEHoUQDQgAEs+nDydkW5F07yZPb/c05TSjzRJXCvD8Ni76ppfWJFOEOdM/WuHU6 zBMcdIzoY+LuqdZ8LgVlMBsnx8NwNvvFAA== -----END EC PRIVATE KEY----- And here...
Your private key has the SEC1 format, but only the PKCS#8 format is supported (see here and here), so the key has to be converted, e.g. with OpenSSL: openssl pkcs8 -topk8 -nocrypt -in <path to input-sec1-pem> -out <path to output-pkcs8-pem> This results in (PEM encoded): -----BEGIN PRIVATE KEY----- MIGHAgEAMBMGByqGSM4...
71,986,924
71,987,054
Calling child's overridden method from parent class
I want to practice C++ by coding a simple mobile phone application with an interchangeable system. I created a System base class and also created MyOS class which extends the System class. In the Phone class, I have a variable of System class because I think like in Java, you can assign it with child class. (eg. System...
If you're coming from java, you need to remember that every non-primitive variable or field in java is implicitly a pointer, so to make equivalent C++ code, you need to make all interclass references into pointers. In addition, every method in java is implicitly virtual, so if you want to override them, you need an exp...
71,987,426
71,999,440
Is member initializer list considered part of the body of a constructor or it it considered part of the declarator
I am learning about member initializer lists in C++. So consider the following example: struct Person { public: Person(int pAge): age(pAge) // ^^^^^^^^^ is this member initializer formally part of the constructor body? { } private: int age = 0; }; My firs...
As per [dcl.fct.def.general], which tells us the grammar of a function definition, a ctor-initializer is part of the function-body: function-definition: [...] function-body function-body: ctor-initializer_opt compound-statement The compound-statement, as per [stmt.block], is, in this context, what OP refers...
71,987,443
71,987,603
c++ : How does std::sort a vector of equal elements based on weak ordering principle
I am trying to understand how weak ordering works by reading this article : https://medium.com/@shiansu/strict-weak-ordering-and-the-c-stl-f7dcfa4d4e07 The main take away from it is : Then for strict weak ordering we must have For all x: x < x is never true, everything should be equal to itself If x < y then y < x cann...
The code is good. When the values x1 and x2 are compared, rule 2 is satisfied: The rule says "IF x < y, THEN something else". Since the IF part is false (x1 is not less than x2), the entire statement is true. That is how implications ("IF ... THEN ...") work. It is a basic rule of mathematical logic: when the precondit...
71,987,638
74,103,854
With clang and libstdc++ on Linux, is it currently feasible to use any standard library types in a module interface?
So far it seems to me that including almost any libstdc++ header in a C++ module interface causes compile errors on clang 14.0.0 and the libstdc++ that comes bundled with GCC 11.2.0. I wonder if I am doing something wrong or if this is just not something that is supported yet. (I see that the Clang modules support is "...
Ok, this is something that sort of worked for a large project. Note that this was half a year ago, so the world may have moved on. I ended up creating a single header, "sys.hh", that #includes pretty much all the system headers used in the project. What seems to be important is that nothing directly or indirectly #incl...
71,987,840
71,994,381
Smart pointers cast c++17 apple clang
I'm trying to use arrays in smart pointers, but when I cast smart_ptr to weak_ptr using Apple clang I get an error (I use -std=c++17). error: cannot initialize a member subobject of type 'std::weak_ptr<int []>::element_type *' (aka 'int (*)[]') with an lvalue of type 'std::shared_ptr<int []>::element_type *const' (aka ...
This seems to be a bug, where weak_ptr<T>::element_type should be defined as remove_extend_t<T>, but it is currently defined as T. On the other side, share_ptr<T>::element_type is correctly defined as remove_extend_t<T>. This inconsistent caused the underlying type of shared_ptr<T[]> is T*, where the underlying type of...
71,988,033
71,988,083
Sorting vector of objects by object's variable
I have a vector of objects. Each of these objects has 2 fields (the values of which can be repeated), e.g: //myClass name = myClass(x,y) myClass obj1 = myClass(2,5); myClass obj2 = myClass(2,4); myClass obj3 = myClass(1,5); myClass obj4 = myClass(3,2); std::vector<myClass> myVector; myVector.push_back(obj1); myVect...
You can try something like that: for (int i = 0; i < myVector.size(); i++) { for (int j = 0; j < myVector.size() - 1; j++) { if (myVector[j].x < myVector[j + 1].x) { std::swap(myVector[j], myVector[j + 1]); } else if (myVector[j].x == m...
71,988,147
71,988,251
How to loop this program if the user input 2 or more character?
#include<iostream> #include<string> int main(){ char find; char find; int times = 0; string message; cout <<"Enter a message a message: "; getline(cin, message); cout <<"Enter a character to be found: "; cin >> find; for(int i = 0; i<message.length(); i++){ if(message[...
Try below code : #include<iostream> #include<string> using namespace std; int main() { string find; int times = 0; string message; cout << "Enter a message a message: "; getline(cin, message); cout << "Enter the character to be found: "; cin >> find; while (find.length() > 1) { ...
71,988,229
71,988,900
in Android Ndk 'malloc.h' file not found
i want use malloc lib when i create a new .c file and .h file .android studio tell me 'malloc.h' file not found. I use CMake to compile. is my CMakeLists.txt. I am a ndk rookie. cmake_minimum_required(VERSION 3.4.1) add_library( native-lib SHARED native-lib.cpp) find_library( log-lib...
I know. I need to add a .c file to add_library . add_library( # Sets the name of the library. native-lib # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). native-lib.cpp stackblur.c)
71,989,024
71,989,126
Can't compile a Crow sample - boost/optional.hpp: No such file or directory
I'd like to compile and test Crow C++ microframework in Debian Linux 11: Download the latest crow.deb, currently crow-v1.0+1.deb. Install it: $ sudo dpkg -i crow-v1.0+1.deb Selecting previously unselected package crow. (Reading database ... 587955 files and directories currently installed.) Preparing to unpack crow-v...
You need to install Boost, for Debian that would be apt install libboost-dev.
71,989,160
71,989,211
How to use remove_if on an std::list of structs when you want to compare to a member variable of the struct
I have an std::list of structs and I would like to remove items from the list based on if a certain member variable matches a particular value. My struct and list: struct Foo { uint64_t PID; uintptr_t addr; }; std::list<Foo> FooList; Code to remove entry: uintptr_t Bar; FooList.remove_if(???) // Remove when "Foo....
list::remove_if takes a function object as its argument. You can feed with an inline lambda function like this: FooList.remove_if([Bar] (auto &element) { return element.addr == Bar; }); Edit: be advised that if Bar is a local variable declared outside if the lambda, you need to capture it via copy (Bar) or referen...
71,989,237
71,989,363
Deleting an item somewhere in a vector of structs
I have a vector that is filled with structs. The struct looks something like this: struct entry{ int something int something2; int LRU; // least recently used }; What I want to do is to first find the struct in the vector that has the lowest LRU. And tried doing this by: least = vector[0].LRU; for (entry ...
One way could be to make sure that the element with the lowest LRU is last in vector using std::nth_element. You can then just resize() vector to get rid of the last element. Example: if(not vector.empty()) { std::nth_element(vector.begin(), std::prev(vector.end()), vector.end(), [](auto&& lhs, auto&& rhs) ...
71,989,520
71,989,967
Creating server-socket connection without waiting for user input
My goal is to create a user-server connection. Most importantly I'm not willing to use threads. For now, I want it to work as a simple chat. I believe The issue is that It goes from one user to another in a loop waiting for their getline input, so technically only one user can send a message at a time. What I wish is t...
The answer to your question is "yes," but with a big proviso: a properly designed server shouldn't care what the client is doing. You might want to look into select() or, if you anticipate a large user community, poll(). You don't want a multi-user server to depend on/wait for a single client.
71,989,544
71,990,238
Arduino communication via COM Port isnt working
I want my Arduino to light up the LED if he reads "on" in the Serial Port. At Serial.print(serialData); it prints out what he reads but at if (serialData == "on") it wont work. int led1 = 9; int led2 = 6; String serialData; void setup() { pinMode(led1, OUTPUT); pinMode(led2, OUTPUT); Serial.begin(9600); S...
There are two issues in your code: The timeout is set to 10ms. In 10ms, you can at best enter a single character. readString() will return after a single character and the read string will likely be "o", "n", "f". When you hit the RETURN key, a carriage return and a line feed character are also transmitted ("\r\n"). ...
71,989,806
71,995,801
How to open an HTML file in QtextBrowser
I have a ready-made HTML file, if it is opened through a browser, then a normal web page is displayed. How can this HTML file be opened via the QTextBrowser widget so that structured information is also displayed in it as a web page? I've tried something like this: QFile file("/home/alex/data.html"); if(!file.open(QIOD...
There are dedicated classes to display full webpages: https://doc.qt.io/qt-5/qtwebengine-index.html https://doc.qt.io/qt-5/qtwebengine-webenginewidgets-simplebrowser-example.html In your case, QTextBrowser can "only" display rich text following HTML tags.
71,990,309
71,990,577
Why is this implementation of deleting an element from heap wrong?
Here is my implementation of deleting an element from Min Heap if the position of the element to be deleted is known: void MinHeap::deleteKey(int i) { if(heap_size>0 && i<heap_size && i>=0) { if(heap_size==1) heap_size--; else { harr[i] = harr[heap_size-1]; ...
Consider the following min heap: 0 / \ 4 1 / \ / \ 5 6 2 3 If you were to extract the node 5, with your current algorithm it would simply replace it with 3: 0 / \ 4 1 / \ / 3 6 2 And since it has no children, nothing else is done. But this is not a min heap an...
71,990,579
71,990,880
correct usage of reference in a class
Here is my usage: void fun_out(int& mkol){ mkol = 3; } class refTest{ public: int pol_as; refTest(int& poul): pol_as(poul){} void fun1(){ fun_out(pol_as); } }; int main(){ int asl = 46; refTest testcase(asl); // testcase.pol_as = 46 testcase.fun1(); // testcase.pol...
I need to change asl to the value in fun_out Currently you're storing a copy of asl into the data member pol_as. This means that when you call fun_out from inside fun1 it will only effect that copy. So to achieve the desired effect you can either make the data member pol_as as an lvalue reference to int or you can di...
71,990,814
71,990,909
How to invoke a templated static class method having tuple input in a constexpr way
How can a static constexpr class::method (int i1, int i2, int i3) be invoked, having input data available as tuple<int, int, int> in a constexpr way. The default approach is using std::apply to apply each tuple element as argument to a function. A minimal example to visualize, what I try to achieve looks like: struct a...
Working test_functor: template <typename T> struct test_functor { constexpr void operator()(auto... args) const { T::template test<c>(args...); } }; The problems: Your constructor was misnamed, and ultimately unnecessary – without a constructor your type is an aggregate and can be constexpr-constructe...
71,991,237
72,015,327
Map QWidget center position to QGraphicsScene coordinates?
I have a QGraphicsItem with an embedded QWidget, this QWidget have a QPushButton in it. I'm trying to map the center of the QPushButton to the QGraphicsScene coordinates, so for example, I can add a Circle to the center of the QPushButton. With the help from another post I was able to find the center of the QPushButton...
Solved. This was caused by two things: 1: QRectF getButtonRect() was returning layout->itemAt(0)->geometry(), (index 0 being the first and only widget in the layout) but button->frameGeometry() seems to be a more accurate visual representation of the button's geometry. 2: When adding the widget to the graphic item usin...
71,991,758
72,336,920
C++ filesystem lib not importing
I'm working on a small project with CMake and I'm trying to use the filesystem library to generate asset directories but when trying to use namespace fs = std::filesystem visual studio marks it with a red underline and it doesn't build correctly. I can't find any reason why this shouldn't work. The code I'm using is: #...
The problem is that I was not using C++ Standard >= 17 By using target_compile_features(MyTarget PRIVATE cxx_std_17) in my CMakeLists.txt suggested it fixed the issue of the <filesystem> header being empty
71,991,780
72,011,242
ld.lld: error: could not open 'libLIBCMTD.a': No such file or directory
I recently installed vspkg and tried to build my c++ application with libcurl using command vcpkg.exe install curl:x64-windows-static After i tried to compile it, i got an error on linking stage ld.lld: error: could not open 'libLIBCMTD.a': No such file or directory ld.lld: error: could not open 'libOLDNAMES.a': No suc...
mingw32-make looks like you are using mingw. Consider using the correct vcpkg triplet, e.g. x64-mingw-static.cmake. x64-windows-static will use an installed VS toolchain. Be aware that you also need to set -DVCPKG_TARGET_TRIPLET=x64-mingw-static and -DVCPKG_HOST_TRIPLET=x64-mingw-static in your cmake call. Also make ...
71,991,901
71,992,858
error: ISO C++ forbids converting a string constant to ‘char*’
I'm trying to run the following code, taken from "Object Oriented Programming with C++" by Balagurusamy (8th edition): #include <iostream> #include <cstring> using namespace std; class String { char *name; int length; public: String() { length = 0; name = new char[length+1]; } String(char *s) { length = strlen(s); ...
As the comments indicate, you need to use const char*, not char*. It looks like the book is badly out of date. In C++, a string literal is of type const char[N], where N is the number of characters in the literal plus one for the terminating '\0'. I was able to make your code compile and run by making the following cha...
71,991,995
71,992,253
Cleanly exit Boost thread member of class
I have a class that has a boost::thread member variable. I have a private member function that is run in that thread (see code below). class Human { public: Human() : m_thinkThread(&Human::think, this) { } ~Human() { m_thinkThread.interrupt(); m_thinkThread.join(); } pr...
Do I need the interrupt and join calls and therefore the custom destructor? Or will the default destructor take care of exiting cleanly? If the default destructor is all I need, then what does it do "under the hood" to ensure the thread is exited cleanly? Yes. There's std::jthread in more recent standard versions, wh...
71,992,255
71,992,306
C++ returns 0xC0000005 status
I am new to C++. In the code below, I am probably doing something wrong, because in the terminal I get Process returned -1073741819 (0xC0000005) execution time : 1.533 s main.cpp #include <iostream> #include "foo.h" int main() { Baz* quuz; quuz->quux(); return 0; } foo.h #include <vector> class Bar {...
Baz* quuz; quuz->quux(); Calling a function on an uninizialized pointer is no bueno. void Baz::quux() { qux[0].boolean_val = true; } Follows uninitiliazed this pointer to access qux. Undefined behavior invoked. You're lucky to get a crash. 0xC0000005 is accessed memory that is not mapped.
71,992,295
71,992,355
Does a C++ STL Map move a value's location around after creation?
I have read some hints here and there that after inserting an object into a c++ stl map, then as long as one doesn't delete it, its location in memory never changes. But nobody ever mentioned any literature or sources to back it up, so I don't know how reliable such hints are. Can anyone answer this definately/reliably...
Does a C++ STL Map move a value's location around after creation? No. Can anyone answer this definately/reliably? You can rely on it. Could it be implementation-dependent? It couldn't be dependent on implementation. Is there a guarantee anywhere? Yes, it is guaranteed in the C++ standard: [container.rev.reqmts...
71,992,392
71,998,018
Undetectable NaN when using quiet_NaN() and -Ofast
I am writing a classic nanmean function with OpenCV. I try to emulate MatLab's nanmean by default behaviour (i.e. nanmean reduce on the first dimension). I generate a matrix of random size which can be CV_32F or CV_64F with up to 4 channels. I fill it with random values following a uniform law. Then I assign some value...
You mention in the comments that you were using -Ofast, and this was causing the issue. To understand why this is, we start by looking at the GCC documentation for options that control optimizations. Here it lists the following options that are turned on by -Ofast: It turns on -ffast-math, -fallow-store-data-races and...
71,992,422
71,992,524
Pass by reference to a function accepting a universal reference
I am trying to use an API which sets a value of a variable based on an HTTP call. The function in which I can set the variable which will be set upon an HTTP Call is of type T&&. I would like to access this variable on a different thread. I tried to simplify the problem and represent it in the following code, as two th...
Such notation: template<typename T> void WriteCycle(T&& i) Doesn't really mean an rvalue reference, it means a universal reference, which could be an lvalue reference or rvalue reference depending on what kind of data you pass. In your case it turns into just an lvalue reference, so it has nothing to do with move sema...
71,994,048
71,994,272
Is direct-initialization equivalent to direct-list-initialization?
I have the following example: struct S{ int x, y; } S s1{1}; // direct-initialization or direct-list-initialization ? S s2{1, 2}; // direct-initialization or direct-list-initialization ? S s3(1); // direct-initialization or direct-list-initialization ? S s4(1, 2); // direct-initialization or direct-list-initi...
From direct initialization's documentation: T object ( arg ); T object ( arg1, arg2, ... ); (1) T object { arg }; (2) (since C++11) T ( other ) T ( arg1, arg2, ... ) (3) Direct initialization is performed in the following situations: initialization with a nonempty parenthesized list of expressions or braced-i...
71,994,108
71,994,361
Why string shown up in Shared Library file like .so file in Linux?
May I know why the .so file in linux will show up the string value from my cpp code? Even with fvisibility=hidden set in gcc make. for example, i set "Hello World" and it will show up. I tried google but found nothing related.. Thanks.
-fvisibility=hidden only affects the linker visibility, i.e. whether symbols are visible when a linker tries to link against your file. It does not specify any active obfuscation. Your strings are still placed inside a data section and need to be loaded into the memory space of the process when your library is loaded, ...
71,994,237
71,994,424
Passing 2D arrays as argument to a function and get another 2D array
I'm writing a code which calculates the inverse matrix given a matrix, the thing is, I need that to be included in other code that makes statistical fits, so I need something like a function that receives the size of the matrix (matrix is square matrix) and the matrix itself and returns his inverse, I found something a...
In your second function, you have float *I = 0. Later on, you try to write to this array but you have not allocated it. The way you're indexing your matrices is the flattening approach so you must write float *I = new float[n*n]. There are different approaches, of course, like using dynamic 2D arrays, 2D vectors, etc. ...
71,994,464
71,994,534
I need to choose random function in C++ project
I am making a C++ game-project and in the game I need to choose random bonuses (functions). (below is the example of the code) void triple_balls(){ /* CODE */ } void longer_paddle(){ /* CODE */ } void shorter_paddle(){ /* CODE */ } void bonus_activator(){ //Here I must choose one of the 3 functions a...
You can use std::function, to store you functions in a container. Then create an array of std::function of size 3. #include <functional> #include <iostream> void triple_balls() { /* YOUR CODE */ } void longer_paddle() { /* YOUR CODE */ } void shorter_paddle() { /* YOUR CODE */ } void bonus_activator(){ std::fun...
71,994,867
71,995,031
C++ std::string::at()
I want to print the first letter of a string. #include <iostream> #include <string> using namespace std; int main() { string str = "다람쥐 헌 쳇바퀴 돌고파."; cout << str.at(0) << endl; } I want '다' to be printed like java, but '?' is printed. How can I fix it?
That text you have in str -- how is it encoded? Unfortunately, you need to know that to get the first "character". The std::string class only deals with bytes. How bytes turn into characters is a rather large topic. The magic word you are probably looking for is UTF-8. See here for more infomation: How do I properly us...
71,994,899
71,995,520
How to append to a std::fstream after you got to the end (std::fstream::eof() is true)
I open a file like this (Because it's part of an exercise and it may require overwriting the file): #include <fstream> //std::fstream. std::fstream file("file.txt", std::ios::in | std::ios::out); And let's say I have read a file until the end (To get to the end of the file). std::string tmp_buff; while(std:...
First, there is no need to state std::ios::in and std::ios::out when using a fstream because they are there the default value in the constructor. (it is actually std::ios_base::in/out to be more exact. std::ios (std::basic_ios<char>) inherits from std::ios_base) So std::fstream file(filename) works the same. The proble...
71,994,929
71,996,544
what is the time complexity and space complexity of this solution? Question- Top K Frequent Elements (Leetcode-Medium)
vector<int> topKFrequent(vector<int>& nums, int k) { if(k==nums.size()) return nums; map<int,int> mp; for(int i=0;i<nums.size();i++) mp[nums[i]]++; multimap<int,int> m; for(auto& it:mp){ m.insert({it.second,it.first}); } vector<int> ans; for (auto itr = m.crbegin...
In my opinion you have not the optimal solution. You use a std::map instead of a std::unordered_map. That will have a higher complexity in most cases. std::maphas logarithmic complexity, std::unordered_map has on average constant-time complexity. The std::multimap is not needed at all. It will add unneccessary space an...
71,995,309
72,010,801
qml does not accept keyboard event until i switch windows
I am developing some kind of a video player in QML. I want to control it by Keyboard events but the problem is that the qml doesn't seem to accept any keyboard event until I switch the window and comeback to the app window. I tried with "focus: true" "enabled : true" and "FocusScope: Item" but nothing worked for me
I solved this problem by tracing the focus. The problem was during the frame/page switches I lost the focus. Hence I enabled it on each frame by forceActiveFocus.
71,995,672
71,996,403
Strange freezing cases of Qt GUI event loop on Windows
I try to ask here if somebody has encountered such a problem. From time to time, I have a situation: I launch my Qt app on Windows (in debug mode, but I am not sure if it matters) via cmd.exe and then I work with it and then I stop working with it for some time. Then I return it to be focused and very rarely I experien...
Here is the answer to my question: https://stackoverflow.com/a/33883532/4781940 I really have that Select Command Prompt title when the freeze happens.
71,995,707
72,031,746
How to use reflection of Protobuf to modify a Map
I'm working with Protobuf3 in my C++14 project. There have been some functions, which returns the google::protobuf::Message*s as a rpc request, what I need to do is to set their fields. So I need to use the reflection of Protobuf3. Here is a proto file: syntax="proto3"; package srv.user; option cc_generic_services = t...
If you dig deep into the source code, you would find out the map in proto3 is implemented on the RepeatedField: // Whether the message is an automatically generated map entry type for the // maps field. // // For maps fields: // map<KeyType, ValueType> map_field = 1; // The parsed descriptor looks like:...
71,996,018
71,996,030
Can I access a non-type template class argument from outside? How?
Please check the following code: #include <iostream> template <int Size> class Test { public: // Will not compile, if Size is not a type! // error: 'Size' does not name a type using MySize = Size; double array[Size]; }; using MyTestArray = Test<3>; int main() { MyTestArray testArray; std::...
You can define a constexpr static variable with the value of the template parameter inside the class, for example template <int Size> class Test { public: constexpr static auto MySize = Size; double array[Size]; }; Then you access like this using MyTestArray = Test<3>; auto size = MyTestArray::MySize;
71,996,519
71,996,625
Refactoring : delegate friendship in sub-functions
I refactor a code where a class has a friend function doing a lot of stuff. class Foo { friend void do_something(Foo& foo); }; void do_something(Foo& foo) { // More than 2000 lines of ugly code } I would like to split the content of do_something in several small functions. Something looking like this : void do_so...
Instead of having do_something as function calling other sub-functions, I would suggest you to create an analogous class DoSomehting. Then you could declare this class as a friend with friend class DoSomehting;. So these sub-functions could be its private methods. The method to call -- could be a public method named e....
71,996,867
71,996,937
iterator to a vector of vector of int
I have an error in the following code where I want to print the first element in each sub-vector: vector<vector<int>> logs{{0, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; for (auto beg = logs.begin(); beg != logs.end(); beg++) { cout << *beg[0] << endl; } the error is from cout << *beg[0]...: Indirection requires...
The problem(cause of the mentioned error) is that due to operator precedence, the expression *beg[0] is grouped as(or equivalent to): *(beg[0]) which can't work because beg is an iterator and has no [] operator. This is because the operator [] has higher precedence than operator *. To solve this replace cout << *beg[0...
71,997,062
71,998,751
C++ Windows function "LockResource()" returns half the data in the resource
I am trying to read an embedded resource from a dll, it contains an encrypted file. Reading it from LockResource() , only returns half the data. The funny thing is that I checked SizeOfResource() and the size of the resource is what it is supposed to be. So I tried to access the file without it being an embedded resour...
strlen is assuming the parameter is a zero terminated string. It counts the chars until it gets to the zero termination. In your case it seems like the resource is binary. In this case it may contain bytes with the value 0, which strlen treats as the end of the string. Therefore what strlen returns is irrelevant. You c...
71,997,200
71,998,137
Why does Apple Clang make a call to compare for a unique hash in an unordered map?
I was trying to improve my understanding of the implementation of unordered_map and was surprised by this behavior. Consider this minimal example below. #include <iostream> #include <unordered_map> using namespace std; template<> struct std::hash<int*> { size_t operator()(int* arr) const { cout << "cu...
There are basically two cases where the comparator does not need to be applied: The first one is when the target bucket is empty (then, there is nothing to compare with). A simple demo code that works with both libstdc++ and libc++ is as follows: struct Hash { size_t operator()(int a) const { return a; } }; struct...
71,997,445
71,997,488
Why we must overloading += and -= beside just overloading + and - operator?
In c++, why we must overloading +=, -=, +, - operator beside just overloading + and - operator? Here is an example: In C++, when I create a Point class, I will do: class Point { public: int x, y; public: Point(int X, int Y) : x(X), y(Y) {} //Assignment operator void operator=(Point a) { x = a.x; y = a.y...
The typical operator+= is more efficient than a = a + b, and cannot be implemented in terms of operator+. It can be the other way around though: struct foo { int value = 42; foo& operator+=(const foo& other) { this.value += other.value; return *this; } foo operator+(const foo& other) c...
71,997,744
71,998,139
How can I propagate const when returning a std::vector<int*> from a const method?
Lets show it in an example where we have a Data class with primary data, some kind of index that points to the primary data, and we also need to expose a const version the index. class Data { public: const std::vector<int>& getPrimaryData() const { return this->primaryData; } const std::vector<int*>& getIndex() con...
You're asking for std::experimental::propagate_const. But since it is an experimental feature, there is no guarantee that any specific toolchain is shipped with an implementation. You may consider implementing your own. There is an MIT licensed implementation, however. After including the header: using namespace xpr=st...
71,997,768
72,159,778
Mesh getting cut off
I'm using DirectX 11. I'm trying to draw a Cube mesh to the screen but the bottom half is getting cut off. If I move the camera up/down the bottom half is still cut off, which leads me to think that it's not a viewport/rasterizer issue, but I'm not sure. The pictures are of the cube looking down and then looking up. Yo...
I've seen similar issues caused by: Transposed matrices (are you using row major or column major matrices? Do you need a #pragma pack_matrix? It looks like you've finnicked with transposing quite a bit - avoid doing that, as you will make mistakes that are difficult to reason about) Otherwise messed up matrix multipl...
71,998,383
72,070,391
CLBlast library not working on Mingw-w64 with Nvidia GPUs
I am trying to run the example samples/sgemm.cpp from the CLBlast repo on Windows 10 with a Nvidia graphics card. I have obtained the cl.hpp from the link. The makefile is simply as follows: a.exe: sgemm.cpp g++ sgemm.cpp -lopencl -clblast -O0 -g -DCL_TARGET_OPENCL_VERSION=300 I have the Nvidia CUDA toolkit v11.6 ...
To answer this, this was not a problem with gdb, a.exe or the CUDA toolkit but rather with the installed library which is build with Visual Studio. The resulting binary seems to be incompatible with g++. Therefore, installing the library from source using g++ fixed this.
71,998,428
71,998,590
how to write the result of sqlite3_exec not in stdout
I need to execute sql command "select" and return some data from the result of it. I'm trying to do it with sqlite3_exec, but it's only writting in stdout. What I need to do to write the data in array or something like this? static int callback(void *NotUsed, int argc, char **argv, char **azColName){ int i; fo...
Let's look at the fourth parameter of sqlite3_exec(). This is a pointer that is passed to the callback function. Give sqlite3_exec() a pointer to your data structure and store the results to that pointer in the callback. You can for example use a vector: std::vector<std::pair<std::string, std::string>> vec; rc = sqlite...
71,998,434
71,998,911
can not open include file cpr/cprver.h using CPR library in CPP application
Hello i work with CPR library in cpp application for http request to my api but after i add additional include directory, i am getting error like 'can not open include file cpr/cprver.h' As i check there is no file with the name cprver.h in cpr folder. What i did: Download CPR library from https://github.com/whoshuu/c...
I think simply downloading cpr library from Github is not enough, you should build and link cpr against your binary. According to the documentation, there are several ways to use cpr: Cmake If you already have a CMake project you need to integrate C++ Requests with, the primary way is to use fetch_content. Add the fol...
71,998,455
72,002,774
Cast AlignedBox double to AlignedBox int
I'm trying to use Eigen AlignedBox. Specifically, I'm trying to cast a box of double into an int one, by using AlignedBox::cast AlignedBox<double, 2> aabbox2d = AlignedBox<double, 2>(Vector2d(0.52342, 2.12315), Vector2d(3.87346, 4.72525)); aabbox2d.cast<AlignedBox<int, 2>>(); auto minx = aabbox2d.min().x(); Anyway, wh...
Consulting the documentation for AlignedBox::cast shows that the template argument to cast is defined as template<typename NewScalarType> and the return value is *this with scalar type casted to NewScalarType. Thus the cast function does not modify the existing instance of the box, but returns a new one. To make your e...
71,998,722
71,999,005
How can I get the faceIdlist from a vtkPolyhedron object in python?
I'm a learner of vtk, I want to use vtkpolyhedron object to describe an irregular polyhedron, then write it into .vtu file. It has an error when I write it into unstructured grid. I use a cube as example, here is my code # create a cube polyhedron polyhedron = vtkPolyhedron() for i in range(8): polyhedron.GetPointI...
You should call Initialize after SetFaces (at least before further access to the cell) See this similar example In found from this doc Edit As GetFaces does not seem to work as expected in python I advise to create your data following the pattern of this other example: create a vtkPoints, add it to the vtkUnstructured...
71,998,729
72,039,433
Save a captured image using QCameraImageCapture::capture() in PNG Format
this is literally my first question in a forum. So I'm a Qt newbie and I'm stuck at this little detail. I'm creating this application that takes pictures and saves them, but the issue is that it saves then in a "JPEG" format and i need them in "PNG" or "GIF" or "tiff" and i I've tried a lot of stuff but nothing worked,...
For anyone that might encounter this problem in the future, here's the solution i've found : _image_capture->setCaptureDestination(QCameraImageCapture::CaptureToBuffer); QObject::connect(_image_capture.data(), &QCameraImageCapture::imageCaptured, [=] (int id, QImage img) { fileName = "image.png"; ...
71,998,853
72,076,306
create shared library with main to call undefined function and provide function body in other project
I need to create a shared library using cmake, and I must call function run() in a library function. But the project which uses this library should provide the body of this function. The real cases use systemC which force library to implement main function. To avoid further complexity, I try to simplify the case like t...
As mentioned in the comments, weak symbols worked fine in this case. MyInterface.h void run(); and then have an implementation for run function with weak symbol: InterfaceWeakImplementation.h void __attribute__((weak)) run(){ // pass } and have the actual implementation in caller project InterfaceStrongImplementa...
71,998,977
71,999,084
std::chrono and missing (?) support for negative leap seconds
C++20 added time zone support to std::chrono, and this includes leap seconds. However, it appears as if only leap second insertion was supported, not leap second removal, that is, negative leap seconds. (Admittedly, since 1972 there only have been positive leap seconds; but it seems that in the last few years the drift...
[time.zone.leap.members]/2 actually does specify negative leap seconds. Returns: +1s to indicate a positive leap second or -1s to indicate a negative leap second. [Note 1: All leap seconds inserted up through 2019 were positive leap seconds. — end note] When the standard speaks of insertion of a leap second, that lea...
71,999,513
71,999,540
use the 'typename' keyword to treat nontype "pcl::PointCloud<PointT>::Ptr [with PointT=T]" as a type in a dependent contextC/C++(2675)
I wrote two functions. PointCloud<PointXYZ>::Ptr rotateCloud(PointCloud<PointXYZ>::Ptr src); PointCloud<PointXYZRGB>::Ptr rotateCloud(PointCloud<PointXYZRGB>::Ptr src); In these two functions, I write completely same code without inside <>. <PointXYZ> or <PointXYZRGB>. I want to write a single function.I heard there i...
Since ::Ptr is a dependent type you need typename on the argument and return type template <typename T> typename PointCloud<T>::Ptr rotateCloud(typename PointCloud<T>::Ptr src);
72,000,110
72,001,677
How to automatically make a calculation in a cell in the same row using the data of another cell that is changed in QtableWidget?
Basically I have a table widget. 2 columns in that table contain Diameters and Area repsectively. I basically want when I enter the diameter the area get calculated in the corresponding cell. And if I enter the area, the diameter is similarly calculated. I made the connect function that sends a signal when a cell is ch...
I just defined my tableWidget when constructing my form (not at the CalculateArea function) as below and it worked: QTableWidget* tableWidget = new QTableWidget(); tableWidget->setRowCount(1); tableWidget->setColumnCount(2); QTableWidgetItem* item = new QTableWidgetItem("1.0"); QTableWidgetItem* item2 = new QTableWidge...
72,000,286
72,000,457
custom type_index order without boost
I have the following map : std::map<std::type_index, std::set<Status *>> statuses; It store sets of the different subclasses of Status there, thanks to their std::type_index. However I want to have control about the order of the objects in this map (for instance, I have two classes Burn and Stun that inherit from Stat...
You can wrap the type_index into a custom type with a comparator that yields the desired order. The example from cppreference modified using std::map rather than std::unordered_map and with a custom comparator: #include <iostream> #include <typeinfo> #include <typeindex> #include <map> #include <string> #include <memor...
72,000,618
72,003,582
Not receiving an Appropriate Result, USACO Bronze 2015 Fence Problem
I was attempting the Fencing Problem of USACO 2015 Bronze. http://www.usaco.org/index.php?page=viewproblem2&cpid=567 This problem basically asks you to find the total length of the fence painted given that two individuals (a cow and farmer) paint fences between a given interval on the number line (the fence is the numb...
1. length might not be initialized Like @AlanBirtles pointed out in the comments, length would not be initialized in case b <= d which would lead to undefined behaviour. This could be fixed by moving the assignment of length outside the else statement: godbolt example #include <iostream> #include <string> using namespa...
72,000,637
72,000,871
How can I connect a QML signal to a C++ slot within the QML file
according to this, I can connect qml signal and c++ slot in qml file without QObject::connect in c++ file. But all I got is an error Expected token ':' in Window { signal sizeChange(int y, int width, int height) visible: true width: 1920 height: 1080 sizeChange.connect(cefWindow.resizeCEFWindow) ...
There's a couple different ways you could do it. You could put your code in a function as @Amfasis mentioned: Window { Component.onCompleted: { sizeChange.connect(cefWindow.resizeCEFWindow) } } Or you could just directly call your C++ slot from a signal handler, like this: onSizeChange: { cefWindow...
72,000,848
72,001,352
How to safely get the new filename from SHNotify event (SHCNE_RENAMEITEM)
I've hooked into the Windows shell, and am receiving notification events nicely to my hidden CWnd. When I receive the SHCNE_RENAMEITEM event, the SHGetPathFromIDList() function returns me the old file name, but not the new file name of the rename. I've successfully hacked a pointer and discovered the new name, but this...
You are on the right track, but your syntax is just over-complicated. SHChangeNotification_Lock() will give you a pointer to an array of PIDLs, you don't need fancy type-casts to access the elements of that array. Also, you need to call SHChangeNotification_Unlock() before exiting your callback function. Try something...
72,001,238
72,001,796
binding multiple texture in OpenGL does not work correctly
I am tired of binding multiple textures I have something weird when I have 2 textures or more, it's over each other This problem happens when using GPU: NVIDIA GeForce RTX 3070 Laptop GPU/PCIe/SSE2 and openGL Version 4.6 like this: but when using GPU: AMD Radeon(TM) Graphics it pretty good Like this main.cpp shade...
I'd say this has something to do with the int-to-float conversion. It seems that the NVIDIA GPU adds a little bit of random noise when it interpolates IndexMaterial, while the AMD GPU does not. Try using flat shading for IndexMaterial. This will cause the GPU to use the value from one vertex, instead of interpolating b...
72,001,662
72,001,823
C++ declare zoned_time for 1 PM today east coast time
I'm looking for how to declare a time for a configurable number of minutes before 1 pm east coast time on the day of running the program. I've found ways to get a fixed time of the timezone such as: chrono::zoned_time onePmEastCoastTime ("New York/New York", chrono::sys_days{ 2022y / chrono::April/ 15d } + 13h ); How ...
It sounds like you want to specify the time in terms of local time as opposed to UTC. The key to this is in the use of local_days vs sys_days. sys_days is a count of days in UTC. local_days is a count of days in some local time that can be subsequently paired with a timezone. Maybe you are looking for: chrono::minutes...
72,002,028
72,002,106
How is it that we're allowed to create a const std::vector without any initializer unlike normal const objects
I am learning about std::vector in C++. I learnt that a const std::vector<int> means that we cannot change the individual elements within that vector and also cannot append/push_back more elements into it i.e., we only have read-access to the elements, which is expected from an entity that is a const. But i find a diff...
As we can see that for a const built in type(like int), we must provide an initializer. That is incorrect. You must ensure that a const object is initialized. If you do not provide an initializer for an object, that object will undergo the process of default initialization: To default-initialize an object of type T ...
72,002,196
72,002,738
Get Disjunctive Support for itemset?
Disjunctive Support : let an itemset I formed by any non-empty subset from C Supp(I) is the number of transactions containing at least one item of I for example i have : vector < vector <int> > transactions = {{1, 2}, {2, 3, 7}, {4,6}, ...
You wrote that: Supp(I) is the number of transactions containing at least one item of I But your implementation looks like you are trying to count transactions containing all the items of I. Anyway if you still need implementation for the defintion you supplied, you can try this: #include <iostream> #include <vector>...
72,002,459
72,002,864
Mixing cl, clang-cl and clang in the same project
Context I am developing a cross-platform project that depends on a highly performance sensitive open-source library. This library supports a number of different compilers, but the most performant version is compiled via clang, due to inline assembly which isn't supported by the MSVC compiler (cl). This has highlighted ...
Specifically, can a static library (.a) compiled with clang be consumed by the MSVC toolchain? (ie. symbol definitions are not dllexport/imported). Yes. I have a fairly large Windows (MFC-based) project in which I use the native MSVC compiler to build all components that actually use any MFC (or other WinAPI) code, b...
72,002,717
72,002,817
Using std::thread outside main source file in c++
I'm trying to use thread but it doesn't work outside main source file. For example it doesn't work void Game::foo() { std::cout << "Why are you not working properly"; } void Game::threadStart() { std::thread th(foo); //here is something wrong } But this works(it is in main source file) void foo() { std::c...
In your Game class example, you are trying to use a class member function as the thread function. This will work, but member functions have the hidden 'this' argument. So you need something like: void Game::threadStart() { std::thread th(&Game::foo, this); }
72,002,992
72,025,161
How to link spacy-cpp lib with CMake
I'm working on a project atm where I want to use the lib spacy-cpp. It's a header-only wrapper for the lib spaCy which is a Python lib. Now the problem is that I'm not able to properly link the lib when using CMake but it works if I use a makefile. Here's an example how a working makefile looks like: CXX = g++ -g -std=...
We now found the solution to my problem, maybe in the future someone else has the same problem so I wanted to post it here. This worked for me: project(untitled) set(CMAKE_CXX_STANDARD 14) find_library(SPACY_LIB spacy) include_directories(/usr/include/python3.8) add_executable(untitled main.cpp) target_link_libraries...
72,003,202
72,007,952
Can not connect a Surface eglCreatePbufferFromClientBuffer
VGint num_config; EGLint value; EGLBoolean ret; m_BackLayerBuffer = vgCreateImage(SGA_DIS_FMT_RGB565, LCD_WIDTH, LCD_HEIGHT, VG_IMAGE_QUALITY_NONANTIALIASED); vgClearImage(m_BackLayerBuffer, 0, 0, LCD_WIDTH, LCD_HEIGHT); m_Context = eglGetCurrentContext(); m_Display = eglGetCurrent...
I know that, this hardware can not supoort muti context. After I delete m_OffScreenContext = eglCreateContext(m_Display, m_Config, EGL_NO_CONTEXT, NULL); the return value is EGL_SUCCESS
72,003,284
72,003,442
GL_CULL_FACE hides one triangle from the front
I have run into a problem using C++ and OpenGL (GLFW and GLAD). When I use GL_CULL_FACE, it only hides one triangle and it hides it from the front of my cubes. If I use GL_FRONT or GL_BACK, the same thing happens but it only shows the opposite triangles. These are my vertices and indices that I'm currently using: stat...
Your mesh definition lacks consistency. Taking your 'top' face as an example, one of your triangles is defined in clockwise (CW) order, the other is counter-clockwise (CCW): You should fix that. Stick to CCW throughout: Adding to that, some of your face vertices are numbered in a C order, some are in Z order. This is...