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
72,754,258
72,754,312
reinterpret_cast usage to manipulate bytes
I was reading here how to use the byteswap function. I don't understand why bit_cast is actually needed instead of using reinterpret_cast to char*. What I understand is that using this cast we are not violating the strict aliasing rule. I read that the second version below could be wrong because we access to unaligned ...
The primary reason is that reinterpret_cast can not be used in constant expression evaluation, while std::bit_cast can. And std::byteswap is specified to be constexpr. If you added constexpr to the declaration in your implementation, it would be ill-formed, no diagnostic required, because there is no specialization of ...
72,754,339
72,754,358
static variable in variadic template function
I want to use a static variable in a function which accept variadic template to accept variable number of arguments. Since the function gets called recursively I expect the value of i to be incremented for each call. But the static variable is incremented only once rather than for each function call. Here is the progra...
Each specialization of the function gets its own copy of the static variable. Does the compiler create a separate function for each function invocation? Rather, for each used set of template arguments.
72,754,623
72,759,723
How to benchmark fmt::format API on https://quick-bench.com
I am trying to understand and benchmark fmt::format API ( https://fmt.dev/latest/api.html ). I wrote a simple test in compiler explorer i.e, https://godbolt.org/z/fMcf3nczE. #include <benchmark/benchmark.h> #include <fmt/core.h> static void BM_format(benchmark::State& state) { // Perform setup here for (auto _ : ...
Unfortunately, quick-bench does not support external libraries which require separate compilation (as fmt does). As a side note, it does not support the inclusion of header-only libraries via URLs, either. I would have said that in this specific case you could use C++20 std::format instead, if you are not tied to fmt l...
72,754,634
72,756,396
Inheriting singals from child widgets
I created a Custom widget in QT, i use it in my main program but i cant use the signals from a QLineEdit, how can i do it?, this is mi code: search = new Search_browser(ui->widget); connect(search, SIGNAL(returnPressed()), this, SLOT(set_page())); Search_browser has a QLineEdit, that is why im trying to use returnPr...
You aggregate QLineEdit in Search_browser so now it's incapsulated (private), to make it accessable from outside world (from MainWindow) you can do one of two things: add accessor to it and connect to returned value. class Search_browser : public QWidget { ... QLineEdit *getLineEdit() {return lineEdit;} }; connect(sea...
72,754,755
72,755,095
Signed int not being converted into unsigned int
I am reading the book C++ Primer, by Lippman and Lajoie. On page 65 they say: If we use both unsigned and int values in an arithmetic expression, the int value ordinarily is converted to unsigned. If I try out their example, things work as expected, that is: unsigned u = 10; int i = -42; std::cout << u + i << std::endl...
Both unsigned int and int take up 32 bits in the memory, let's consider their bit representations: unsigned int u = 10; 00000000000000000000000000001010 int i = -42; 11111111111111111111111111010110 u + i: 11111111111111111111111111100000 If we treat 11111111111111111111111111100000 as a signed number (int), then it...
72,755,246
72,772,839
ASN.1 REAL binary base 2 encoding mantissa normalization
I am trying to DER encode REAL data in binary 2 base form using C++. I calculate the mantissa and exponent with the following algorithm. sample data = 32.3125 using C++ std::frexp function, extract double mantissa and int exponent. mantissa 0.5048828125 exponent 6 Convert the mantissa to integer by multiplying by 2 an...
Your encoding is correct. Note that the requirements for DER are covered in X.690 11.3, and you have met them (you are using base 2, your mantissa is odd, and F = 0). F != 0 is only ever needed when encoding using base 8 or 16.
72,755,304
72,755,388
Function which copies an array of integers from one array to another using pointers in C++
The purpose of the Copy function in the following code is to copy an array of integers from one array to another using C++ but the output seems wrong. What could be the problem here? #include <iostream> using namespace std; void Copy(int old_array[],int new_array[],int length) { int *ptr1 = old_array; int *ptr...
ptr2 is one past the end of the array when your print loop runs. Try this: void Copy(int old_array[], int new_array[], int length) { int* ptr1 = old_array; int* ptr2 = new_array; int i = 0; for (int i = 0; i < length; i++) { *(ptr2++) = *(ptr1++); } ptr2 = new_array; for (int i =...
72,755,568
72,755,612
Need a better solution to a hackerrank challenge
So I am new to competitive programming and I have been trying to solve this challenge for the past hour or so. I'm pretty sure my solution is overly complicated so can someone give me a better solution please? My code is pretty bad so if you can pls provide me with some feedback. The challenge You are given the day of ...
For a start it would help if the code would actually be correct: int find_answer_for_more_than_7_days(int start,int day){ cout<<day%7 + start - 1; return 0; } start = 7 and day = 6 produces 12. All those special cases in main are unlikely and costing you far more time then simply doing the general math. Just d...
72,755,744
72,756,072
Use of std::uninitialized_copy to an initialized memory
If std::uninitialized_copy is used to an initialized memory, does this use cause a memory leak or an undefined behavior? For example: std::vector<std::string> u = {"1", "2", "3"}; std::vector<std::string> v = {"4", "5", "6"}; // What happens to the original elements in v? std::uninitialized_copy(u.begin(), u.end(), v.b...
Base on specialized.algorithms.general and uninitialized.copy I don't find any formal requirements that the destination range must be uninitialized. As such, we can consider the effect of std::uninitialized_copy which is defined as equivalent to the follow (excluding the implied exception safety boilerplate code) : for...
72,755,784
72,756,073
Visual Studio 2022: MSB8036 since upgrading to VS2022
I've been unable to build C++ projects since upgrading to VS2022. No matter what I do, it cannot programmatically find the Windows SDK files it needs, always claiming MSB8036 (the extremely generic "it can't find the Windows SDK" error). To be absolutely clear, the version of the Windows SDK that it is looking for (10....
@john's comment here provided the answer. I then was able to grab the proper SDKManifest.xml from here, which is basically the same as the version given in the video with the Windows SDK version swapped out.
72,756,420
72,796,737
Winui 3 winrt C++ reference counting
Using WinUI 3, Winrt C++ in the following code: Is myRectangle reference counted? Or is it copied? namespace winrt::MyProject::implementation{ void MyProjectClass::fnc(){ winrt::Microsoft::UI::Xaml::Controls::Canvas myCanvas = CanvasElementFromXAML(); winrt::Microsoft::UI::Xaml::Shapes::Rectangle myRectangle; myCanv...
WinRT is COM-based, so the Canvas instance and the Rectangle instance are both COM-objects. So, Append implementation will call AddRef on myRectangle. In this case, there's no specific MS extension involved.
72,756,435
72,756,568
c++ primer plus Partial Specializations question
In the "Partial Specializations" section of chapter 14 of C++ Primer Plus: Without the partial specialization, the second declaration would use the general template, interpreting T as type char *.With the partial specialization, it uses the specialized template, interpreting T as char. The partial specialization featu...
A partial specialization will expect as many template arguments as the base template mandates ("base" meaning the unspecialized declaration of your class template, NOT the type named Base). A solution to your problem would be to define the base template as: template <typename T1, typename T2 = T1, typename T3 = T2> cla...
72,756,636
72,757,110
Eclipse installation issue
It is possible to install Eclipse for Java and C++ in the same time for same Pc? Thanks ☺️ I’m Java Developer but also I need eclipse even for C++ projects. It is that possible ?
You have options: install Eclipse/Java and Eclipse/C++ in different folders on the same computer Install either Eclipse/Java or Eclipse/C++, then further install the plugins for the missing language The first one is trivial as it is just two downloads. For the second, check out https://stackoverflow.com/a/39283723/42...
72,756,717
72,793,806
How to deal with possible errors that arise from dereferencing a nullptr?
I have a question regarding some guidelines to write better code. Suppose that I have a class like this: class A { private: T *m_data; public: A(T *data) : m_data(data) {} void doSomething() { //accessing m_data } }; Since it's possible to call A constructor passing a nullptr, what is th...
The short answer is always: there is no single correct way, or rule that always applies. For example, suppose your class is the start of a custom iterator definition. Dereferencing default-constructed or end() iterators is usually undefined behaviour, even if they don't represent null values. The non-default constructo...
72,756,950
72,756,988
C++ change base's member variable and print it from derived class
The idea is: I've 2 classes, one named Print with only one method called printName, and other class named Human with variable name. I want printName to print whatever the name variable in the Human class is. Example: class Print { public: char name[255]; // name will be overridden from Human class. void prin...
One of the solutions: Curiously Recurring Template Pattern 1, 2. template <typename T> class Print { public: char name[255]; void print() { std::cout << static_cast<T*>(this)->name << std::endl; } }; class Human : public Print<Human> { public: char name[255]; }; int main() { Human h; h.name = "Som...
72,757,374
72,757,730
Problem creating abstract class with no virtual pure methods C++
I want to create a class that is a subclass of two classes that have a common virtual base class. Furthermore, I want this class to be abstract (not be able to create instances of it, but also not needing to call the ctor of the virtual base class). Sample code: #include <cstdio> class CommonBaseClass { public: vir...
You can use a pure virtual destructor as follows. Even although it is pure virtual, you still need to implement it. You do not need to declare destructors in the derived classes. class TargetClass : //I will never instantiate this class public ClassA, public ClassB { public: TargetClass() : ClassA(), ClassB...
72,757,461
72,757,551
How to run new instance of qt application programmatically
Im trying to clone notepad. Im getting some trouble with the "new window"(ctrl+shift+n) button. is there a way for me to run a new instance of the application programmatically?(that is also not a child of the first instance, meaning if i close the first instance the second instance will continue to live) (I already rea...
I think https://doc.qt.io/qt-6/qprocess.html is what you are looking for. Expecially the startDetached method might do the trick, see: https://doc.qt.io/qt-6/qprocess.html#startDetached-1
72,757,835
72,757,877
Loop compiles but Range does not
OrderProcessor::ProcessRange function in the code below accepts a range as an argument and iterates over it. When I try to call it with a range constructed with std::views::filter it does not compile, but when I copy and paste OrderProcessor::ProcessRange function implementation into the code it compiles: #include <ios...
You just need to drop the const on the range argument to ProcessOrder(). A range may change when you iterate it - and apparently that's true for the filter view. Perhaps the library or the compiler could have guessed otherwise, but they don't. Without the const - it compiles: https://godbolt.org/z/MnEczfTjG Also note t...
72,757,928
72,757,980
I'm reading "C++ Templates: The Complete Guide" and there is something that I don't understand
It says: A function generated from a function template is never equivalent to an ordinary function even though they may have the same type and the same name. This has two important consequences for class members: A constructor generated from a constructor template is never a default copy constructor. Firstly, I don...
A copy constructor is a non-template constructor with a certain signature. A specialization of a constructor template is never (by definition) a copy constructor. I think "consequences" is not really used here to mean a logical implication immediately following from the previous statement. I think it is rather just mea...
72,758,384
72,758,458
Invocability of functors
Why does the standard not consider functors with a ref-qualified call operator to be invocable? #include <concepts> struct f { auto operator()() {} }; struct fr { auto operator()() & {} }; struct fcr { auto operator()() const& {} }; struct frr { auto operator()() && {} }; static_assert(std::cop...
This fails: static_assert(std::invocable<fr>); // fails Because it is testing the validity of the expression std::invoke(std::declval<fr>()), which is trying to invoke an rvalue of type fr. But fr's call operator is &-qualified, which means you can only invoke it on an lvalue. That's why it's being rejected. Why doe...
72,758,545
72,758,571
C++: No match for operator for the same types of operand
I have a vector of a map of int and float std::vector<std::map<int, float>> datad; And I want to iterate over the maps in vector and inside over pairs in map for (std::vector<std::map<int, float>>::iterator currentMap = datad.begin(); currentMap < datad.end(); ++currentMap) { for (std::map<int, float>::iterator it =...
std::map's iterators are bidirectional iterators, not random access iterators. Therefore they do not provide relational comparison operators. You can only equality-compare them. So replace < with !=, which is the standard way of writing iterator loops. Or even better, replace the loop with a range-for loop: for (auto& ...
72,758,653
72,758,765
How to separate a string using separator
I want to separate this string using _ as the separators {[Data1]_[Data2]_[Data3]}_{[Val1]_[Val2]}_{[ID1]_[ID2]_[ID3]} where underscore should not be considered inside the { } brackets. so when we separate the strings we should have three new data items {[Data1]_[Data2]_[Data3]} {[Val1]_[Val2]} {[ID1]_[ID2]_[ID...
A manual solution: iterate through the string and use a variable to check whether it's in the bracket or not: std::vector<std::string> strings; std::string s = "{[Data1]_[Data2]_[Data3]}_{[Val1]_[Val2]}_{[ID1]_[ID2]_[ID3]}"; std::string token = ""; bool inBracket = false; for (char c : s) { if (c == '{') { ...
72,758,843
72,758,967
C++ template size argument from initalizer list without standard library
I'm working on some C++ code for an embedded platform (an ATTiny, though I don't think that matters) which miraculously can compile with C++17. I am trying to use constexpr and template arguments anywhere possible in order to avoid managing array sizes manually while also avoiding memory allocations, while also produc...
This seems like a job for user-defined-deduction guides. You could do something like the following: #include <concepts> #include <cstddef> #include <cstdint> using std::size_t; using std::uint16_t; template<size_t N> class LedPattern { public: template<typename ...D> explicit LedPattern(D...d) : delay_{uint1...
72,759,280
72,759,320
To read from file and store data in map c++
I am trying to read file contents and store it in map data structure, where I am trying to skip comment section not be included in my map. I am unable to keep my map as expected, I am kind off clueless how to go ahead. I have mentioned how my map should look like. Please suggest me what changes I have to add in my code...
This is a mistake while (getline(inputFile, line, '\0')) should be while (getline(inputFile, line)) The first one reads 'lines' terminated by the \0 character, which I seriously doubt is what you want. You want lines terminated by the \n character, that's what the second version does. This illustrates the point that ...
72,759,959
72,762,202
How to convert std::chrono::zoned_time to std::string
What is the most efficient way to convert from std::chrono::zoned_time to std::string? I came up with this simple solution: #include <iostream> #include <sstream> #include <string> #include <chrono> #if __cpp_lib_chrono >= 201907L [[ nodiscard ]] inline auto retrieve_current_local_time( ) { using namespace std::c...
What you have is not bad. You can also use std::format to customize the format of the time stamp. And std::format returns a std::string directly: const auto str = std::format("{}", time); That gives the same format as what you have. const auto str = std::format("{:%FT%TZ}", time); This gives another popular (ISO) f...
72,759,994
72,760,064
Embed Define into a string
I have a preprocessor define that should determine the size of an array. This constant should also be passed to a HLSL shader. For this I need to pass it around as a string. Is there a way to embed preprocessor defines as a string? #include <iostream> #ifndef SIZE #define SIZE 16 #endif int main() { const int arr[S...
You can use a stringifying macro, eg: #define STRINGIFY(x) STRINGIFY2(x) #define STRINGIFY2(x) #x const char* str = STRINGIFY(SIZE); std::cout << str << std::endl; Alternatively, use a runtime format via snprintf() or equivalent, eg: char str[12]; snprintf(str, "%d", SIZE); std::cout << str << std::endl; However, yo...
72,760,201
72,760,312
no suitable user-defined conversion from "lambda []()-><error-type>" to "const std::vector<int, std::allocator<int>>"
I try to implement lambda function:- vector<int> numbers; int value = 0; cout << "Pushing back...\n"; while (value >= 0) { cout << "Enter number: "; cin >> value; if (value >= 0) numbers.push_back(value); } print( [numbers]() -> { cout << "Vect...
The problem is that print accepts a vector<int> but while calling print you're passing a lambda and since there is no implicit conversion from the lambda to the vector, you get the mentioned error. You don't necessarily need to call print as you can just call the lambda itself as shown below. Other way is to make print...
72,760,488
72,762,934
Thread-safety about `std::map<int, std::atomic<T>>` under a special condition
In general, it's not thread-safe to access the same instance of std::map from different threads. But is it could be thread-safe under such a condition: no more element would be added to\remove from the instance of std::map after it has been initialized the type of values of the std::map is std::atomic<T> Here is the ...
Yes, this is safe. Data races are best thought of as unsynchronized conflicting access (potential concurrent reads and writes). std::thread construction imposes an order: the actions which preceded in code are guaranteed to come before the thread starts. So the map is completely populated before the concurrent accesses...
72,760,907
72,760,941
Returning lvalue from function
Why the result of returning lvalue from function is that that object std::vector<int> v in main() function has same memory address as returned object std::vector<int> vec in a get_vec() function, even though these objects exist in a different stack frame ? Why there is not called move constructor ? #include <iostream> ...
vec is either moved (automatically, because you're returning a local variable), or, if the compiler is smart enough, is the same object as v (this is called NRVO). In both cases .data() is going to stay the same. When moved, the new vector takes ownership of the other vector's heap memory. &vec,&v are going to be the s...
72,761,126
72,761,584
Multithreading beginner query (C++)
I am trying to learn multithreading in C++. I am trying to pass elements of a vector as arguments to pthread_create. However, it is not working as expected. #include <iostream> #include <cstdlib> #include <pthread.h> #include <vector> using namespace std; void *count(void *arg) { int threadId = *((int *)arg); c...
int retVal = pthread_create(&thread1, NULL, count, (void *)&threadId[0]); You have no guarantee, whatsoever, that the new execution thread is now running, right this very instant, without any delay. All that pthread_create guarantees you is that the thread function, thread1, will begin executing at some point. It migh...
72,761,210
72,765,027
c++ mac/m1/intel how to get cpu architecture?
I need to find out at runtime which architecture the cpu is running. I've so far used qt : QSysInfo::currentCpuArchitecture() but there is a problem. The returned value will change when ever I run application that was compiled for x86_64 or arm64. So this will not return the hardware architecture that the system is nat...
Starting QProcess does not work, he inherits base application architecture. I found out that apple added a command to figure out if I'm running in "translated" mode, this can then be used as indication if we are on intel or arm. https://developer.apple.com/documentation/apple-silicon/about-the-rosetta-translation-envir...
72,761,386
72,761,460
How to reference a classes attribute inside another class method?
I'm trying to create a little ascii game where I can run around kill enemies etc. However I'm new to C++ and I would like to do something if the players location is at a certain point. Below is a simpler version of the code and a picture of the problem: #include <iostream> using namespace std; struct Game { bool b...
The variable player is local in function main, so it's not visible where you tried to use it in Game::Draw. One solution could be to make player a global variable. You'll need to switch the order of the structs: struct Player { bool bGameOver = false; int x = 0; int y = 0; }; Player player; struct Game {...
72,761,783
72,761,956
Why does it give an error when compiling the project:
I need to display an array of structures, as far as I understand, I need to use a memory shift, having a pointer to the first element of the array. When trying to fix the code, we saw the following error: Invalid types ‘[int]’ for array subscript my code: #include <iostream> #include <string.h> using namespace std; ...
You absolutely don't need to memory shift *(array_of_points + sizeof(point)*number_of_points) = point; C++ is not that complicated, just array_of_points[number_of_points] = point; Because the compiler knows the type involved, Point3D, it's quite capable of working out the memory shift by itself. Also by the rules of ...
72,762,151
72,765,485
How can I iterate over a TGroupBox and check the state of its children?
Using C++ Builder 10.4 Community edition, I have a TGroupBox populated with some TCheckbox and TButton controls. I want to iterate over the TGroupBox to get the state of each TCheckBox. How can I do this? I tried this: auto control = groupBxLB->Controls; for( uint8_t idx = 0; idx < groupBxLB->ChildrenCount; idx++) { ...
The TWinControl::Controls property is not an object of its own, so you can't assign it to a local variable, the way you are trying to. Also, there is no ChildrenCount property in TWinControl. The correct property name is ControlCount instead. The C++ equivalent of Delphi's is operator in this situation is to use dynami...
72,762,364
72,762,607
compile time parameter checking
I'm trying to understand how the Qt5 framework's Signals and Slots mechanism does type checking on function arguments. I've provided a summary of the section of code I'm interested in. The only thing I'm having trouble understanding is the following template specialization. How does the compiler decide to instantiate t...
When it comes to the instantiations in the two last static_asserts, they both match these: template <typename Elem1, typename Elem2> struct Test { enum { value = false }; }; template <typename Arg1, typename Arg2, typename... Tail1, typename... Tail2> struct Test<List<Arg1, Tail1...>, List<Arg2, Tail2...> > { ... }; ...
72,762,781
72,762,847
Create a pointer that points to a member function that takes a struct as an argument
I have main.cpp file where I defined a struct: struct values { string name1; string name2; int key ; } a; A class named Encrypt defined in a header file Encrypt.h and a file Encrypt.cpp where I define my functions... Im trying to create a pointer that points to a function that has ...
The problem is that args is of type void* and a is of type values* so you get the mentioned error. To solve this uou can use static_cast to cast args to values* if you're sure that the cast is allowed: values *a = static_cast<values*>(args); Additionally change a.name1 to a->name1. Demo
72,763,138
72,763,703
Why does this minimal HTTP test server fail half of the time?
I'm trying to write a minimal HTTP server on Windows and see the response in Chrome with http://127.0.0.1/5000. The following code works sometimes ("Hello World"), but the request fails half of the time with ERR_CONNECTION_ABORTED in Chrome (even after I restart the server). Why? Error: #include <winsock2.h> #include ...
You fail to read the client's request before closing the connection. This usually results in the server sending a RST back to the client, which can cause the ERR_CONNECTION_ABORTED when it is processed before the response itself was processed. As observed by another (deleted) answer, this can be "mitigated" by adding s...
72,764,614
72,764,688
Deduction in template functions with few args
I have few instances of one template function. Each of them sequentially executes each of given lambdas, accompanying them with specific messages. When I do that with one lambda, everything works fine, but when I try to add more than one, I get note: candidate template ignored: deduced conflicting types for parameter '...
Even though the two passed lambdas does the same or looks similar, they have completely different types. Hence, you need two different template types there in the doTasks. Easy fix is providing the template parameter for two lambdas template <class T1, class T2> void doTasks(T1 task1, T2 task2) { // ... } otherwise,...
72,764,815
72,764,841
Best way to copy members from vector<Class> to vector<Member_Type>
I have a vector of complicated structs (here std::pair<int, int>). I now want to copy a member (say std::pair::first) into a new vector. Is there a better (more idiomatic) way than std::vector<std::pair<int, int>> list = {{1,2},{2,4},{3,6}}; std::vector<int> x_values; x_values.reserve(list.size()); for( auto const& el...
std::transform is often used for exactly this: #include <algorithm> // transform #include <iterator> // back_inserter // ... std::vector<int> x_values; x_values.reserve(list.size()); std::transform(list.cbegin(), list.cend(), std::back_inserter(x_values), [](const auto& pair) { return pair.first; }...
72,764,871
72,766,440
Examples of constinit declaration not reachable at the point of the initializing declaration
From dcl.constinit: No diagnostic is required if no constinit declaration is reachable at the point of the initializing declaration. What does it mean? I guess an example would be sufficient. Something dynamically initialized is just ill-formed (from the same link), so it's not that.
Suppose you have one translation unit that declares a symbol to be constinit: // a.cc #include <iostream> extern constinit bool has_constinit; int main() { std::cout << std::boolalpha << has_constinit << std::endl; } Now suppose the translation unit that defined the symbol does not declare it constinit: // b.cc ...
72,765,068
72,812,265
Compiling assimp from source does not generate libassimp file
So I compiled the assimp library with cmake using the x64_x86 developer command prompt that was said to be required. (When I tried using the regular console cmake did an error that it could not find 'the cl compiler'). After some time it finally compiled without errors with the following commands: cmake CMakeLists.txt ...
I installed MSYS2, replaced my existing MinGW installation with MSYS, libraries installed flawlessly and everything works now. My mistake was that: I was compiling the library with VS C++ toolkit while I'm compiling my project with MInGW make and g++ even after I compiled assimp the correct way, version 5.2.4 couldn't...
72,765,359
72,778,798
1D FFT MATLAB results are different from FFTW in C++
I have the MATLAB code: Nx = 10; Ny = 10; Lx = 2*pi; ygl = -cos(pi*(0:Ny)/Ny)'; %Gauss-Lobatto chebyshev points x = (0:Nx-1)/Nx*2*pi; %make mesh [X,Y] = meshgrid(x,ygl); A = 2*pi / Lx; u = sin( (2*pi / Lx) * X); uh = fft(u) This gives the following output: 0 6.4656 10.4616 10.4616 6.4656 0.0000 ...
Was able to fix this by taking the FFT of each columns as someone suggested in the comments: { cplx_buffer out = my_fftw_allocate_cplx(nyk, nx); fftw_execute(fftw_plan_many_dft_r2c(1, &in.rows, in.cols, in.a, &in.rows, in.cols, 1, out.a, &in.rows, out.cols, 1, FFTW_ESTIMATE)); std::cout << "DFT of inpu...
72,766,332
72,766,398
c++11: how to produce "spurious failures" upon compare_exchange_weak?
Is there a way that we can write some code to produce a "spurious failures" for the "weak" version of compare_exchange? While the same code should work well for compare_exchange_strong? I wish to see the real difference between the "weak" and "strong" version of 2 apis, any sample for it? Thanks a lot!
You'll need a non-x86 CPU, typically one that uses load-linked / store-conditional like ARM or AArch64 (before ARMv8.1). x86 lock cmpxchg implements CAS_strong, and there's nothing you can do to weaken it and make it possibly fail when the value in memory does match. CAS_weak can compile to a single LL/SC attempt; CAS...
72,766,402
72,766,473
How to check if given year, month, day and time format is valid in C++?
I am working on an application where the log files will be named in the format "YYYYMMDDHHMM_****.gz". The log file contains YYYY (year), MM (month), DD (day), HH (hours) and MM (minutes). My class constructor needs to check if the file name is valid (whether the year, month, day and time are valid or not). I thought b...
You need to check if std::get_time itself fails. The failing operation is the conversion, not the construction of a time_t value from the resulting struct tm. The sample code on cppreference.com gives a very easy to follow example of how to do that: ss >> std::get_time(&t, "%Y-%b-%d %H:%M:%S"); if (ss.fail()) {...
72,766,688
72,771,169
Reading sensors data from the sysfs interface (hwmon) occasionally results in a blocking call (longer execution time for the function than expected)
I have an ARM machine that runs Linux (BusyBox). I need to frequently read the data in this file /sys/class/hwmon/hwmon0/device/in7_input which contains voltage. It's located in the virtual file system sysfs under the /sys/class/hwmon/ directory. The file contains data that looks like this (SSHed to the device). root:~...
The code you wrote in the readVoltage() is non-blocking. You can use the fact, that read() on non-blocking descriptor would return E_AGAIN / E_WOULDBLOCK errno if reading would block and therefore remove lines with select() and setting FD_SET (less code). You can't be sure what is happening between GetClockCount() call...
72,766,788
72,766,815
Overloading << operator for printing stack in c++
#include <iostream> #include <ostream> #include <bits/stdc++.h> using namespace std; void printHelper(ostream& os,stack<int>& s){ if(s.empty()) return ; int val = s.top(); s.pop(); printHelper(s); os << val << " "; s.push(val); } ostream& operator<<(ostream& os,stack<int>& s){ os <...
The problem(error) is that printHelper expects two arguments but you're passing only when when writing: //----------v--->you've passed only 1 printHelper(s); To solve this(the error) just pass the two arguments as shown below: //----------vv--v---------->pass 2 arguments as expected by printHelper printHelper(os, s); ...
72,767,469
72,767,712
debug template for array C++
I want to create debug template for array for printing array. This is my template #define debug(x) cerr << #x <<" = "; print(x); cerr << endl; void print(ll t) {cerr << t;} void print(int t) {cerr << t;} void print(float t) {cerr << t;} void print(string t) {cerr << t;} void print(char t) {cerr << t;} template <class...
A range-based for loop (for(T i : v) internally uses std::begin and std::end to determine the range it hast to iterate over. These methods work for arrays whose size is fixed at compile time, e.g. int arr[10];, for any standard container, like std::vector, std::list, or any class that has a .begin() and .end()-method t...
72,767,708
72,767,787
How can I make a column chart?
I am facing a problem while doing a chart. I would want to output the chart in a same row without changing the code and without making it horizontal. I would wish to use for loop to solve this problem because I can iterate over everything because I have the same elements. The code is displayed below: # include <iostre...
You don't need to undo endl you just need to reorganise your code so that you do things in the correct order in the first place, like this void outputStatistics() { cout<<"Month\tPayment(RM)\tPrincipal(RM)\tInterest(RM)\tBalance(RM)\n"; for(int i = 1; i <=month; i++) { // output one row at a time ...
72,768,801
72,768,843
C-Style Character String
I want to connect two C-style character strings and store the result in a dynamic char array. int main() { char word1[] = "hello"; char word2[] = "haha"; auto ptr = new char[20]; strcpy(ptr,strcat(word1,word2)); cout<<ptr<<endl; return 0; } The compiler says there is a "segmentation fault" at the statement...
Like this strcpy(ptr, word1); strcat(ptr, word2); You need to use ptr for both operations, the copy and the concatenation. In your version strcat(word1,word2) tries to concatenate word2after the end of word1. But there is no accessible memory there, so you get a segmentation fault.
72,769,594
72,769,668
How to invoke python function in c++ without running script
I'm working on embedded python. However I have a trouble in work. I used 'PyImport_ImportModule' function because I wanted to import python module in C++. Example, # foo.py class foo: def test(self): print("foo.test") foo().test() // main.cpp void main() { PyObject* myModule = PyImport_ImportModule...
Importing a module is the same as "running the script" in Python. All statements are run top-to-bottom, functions, classes are created when their definitions are executed, on the fly. If a module should be used both as a standalone script and as imported module, the canonical way how to do this in Python is wrapping in...
72,770,137
72,771,645
Can I limit the size of a C++14 Vector?
As the tile says, is there anyway that I can declare a vector in C++ 14 and limit the max number of entries it can hold?
One possible solution would be to create your own Allocator. std::allocator is stateless, but yours could implement the max_size() member function which should return the value of a member variable that carries the max number of elements. An example that will work from C++11 up until at least C++20: template<class T> s...
72,770,474
72,780,687
(C++) Two classes with some common function. Cleanest way to code
I have two classes that has some common functions and some different functions. Let's say class Red{ public: void funcA(); void funcC(); } class Blue{ public: void funcB(); void funcC(); } Note My actual code contains more functions (both common function and non-common one) and...
Use virtual keyword to archive this. Example: class Color { public: void funcColor() { cout<<"Color::funcColor()\n"; } virtual void funcC() { cout<<"Color::funcC()\n"; } }; class Red : public Color{ public: void funcA() { ...
72,770,927
72,771,041
Having a set of regex and a set of functions, how to link each regex to a specific function and then call that function once you have a match?
// vector of pairs vector<pair<regex, void (*)(string)>> patterns; // store a regex pattern patterns[0].first = pattern; // store a function name patterns[0].second = func1; patterns[1].first = pattern2; patterns[1].second = func2; // take user's input string input; cin >> input; for (int i = 0; i < patterns....
Let us first look at your code: I will show you the problems and how to fix it. And then I will show, how it could be optimized further. I will put comments in your code to show the problems: // vector of pairs // *** Here we have the base for a later problem // *** After this line, you will have an empty vector, that...
72,771,470
72,771,542
cmake error: "cc: error: unrecognized command line option ‘-std=c++20’; did you mean ‘-std=c++2a’?"
I'm attempting to compile a binary from source, but keep running into an error while doing so. $ cmake --build ./\[binary_dir\]/ [ 0%] Building C object [binary_dir]/CMakeFiles/ZIPLIB.dir/extlibs/bzip2/bcompress.c.o cc: error: unrecognized command line option ‘-std=c++20’; did you mean ‘-std=c++2a’? make[2]: *** [[bin...
Presuming you are in a build directory: You can set CMAKE_C_COMPILER when you run the original call to cmake. cmake -DCMAKE_C_COMPILER=/usr/bin/gcc-11 .. cmake --build .
72,772,356
72,772,616
Passing an object by reference (C++)
I want a method that creates a binary tree from an array and returns nothing. So I would have to work by reference but I am having some troubles with the proper syntax to use. I have obviously tried to search before posting this question, I have seen similar posts but no answer were truly helpfull. Here what i have don...
void Node::make_tree(Node* node, int values[], int size); Node pointer cannot be modified inside the function, as you pass it by value (only the copy is modified). You can use a reference, as suggested in comments : void Node::make_tree(Node* &node, int values[], int size); Or you can also use a pointer to a pointer...
72,772,753
72,772,962
organizing my files in C++ , ARGB to RGBA
I'm trying to understand how the hpp, cpp, and main all work together. for this example I'm working on a code that coverts ARGB to RGBA and I'm confused on what to put in each file. This is my code: color.hpp using namespace std; #include <stdio.h> #include <stdio.h> #include <iostream> #ifndef colors_hpp #define color...
Some advice Remove this template <typename T> Move struct Color { ... }; to color.hpp (all of it, you can delete color.cpp, it is not needed). Remove using namespace std; from color.hpp Remove string getHex(); uint32_t fromArgb(); from color.hpp change main to this int main(int argc, char**argv) { Color c; ...
72,773,090
72,774,052
How to properly pass objects across multiple classes in C++
I am mostly self thought with C++ and I have built some large complex codes during my PhD research. One of the issues I have been continuously facing is lack of oversight during development as I am nearly the only one who can code in the entire group. So when I make a "bad" code, there's no one to correct me and make m...
If I understand your concern correctly, you just want to make class C have pointers to A and B, which are the instances that the instance of class C is going to work on. I am going to explain this on example. Consider the following code #include <iostream> class C { int* _num; public: C(int* num) : num(_num) ...
72,773,329
72,777,462
c++17 fast way for trans int to string with prefix '0'
I want to trans an int into string. I known under c++17, a better way is using std::to_string. But now I want to fill the prefix with several '0'. For example, int i = 1, std::to_string(i) is '1', but I want the result is '00001'(total lenght is 5). I know using sprintf or stringstream may achieve that. But which have ...
If you know something about your domain and don't need to check for errors, nothing gets faster than rolling your own. For example if you know that your int is always in the range [0, 99'999], you could just: std::string convert(unsigned i) { std::string r(5, '0'); char* s = r.data() + 4; do { ...
72,773,640
72,953,110
Write in JSON file - Data not inserted in the correct order
I am creating a desktop app using QT C++ that take a text file and convert it to JSON File like this example: { "102": { "NEUTRAL": { "blend": "100" }, "AE": { "blend": "100" } }, "105": { "AE": { "blend": "100" }, "...
I did resolve it using rapidjson library instead of QJsonObject Based on this example #include <rapidjson/document.h> #include <rapidjson/writer.h> #include <rapidjson/stringbuffer.h> #include "rapidjson/filewritestream.h" #include <string> #include "RapidJson/prettywriter.h" using namespace rapidjson; using namespace ...
72,773,647
72,774,212
Converting an unsigned char array to jstring
I'm having issues trying to convert an unsigned char array to jstring. The context is I'm using a shared c library from Java. So I'm implementing a JNI c++ file. The function I use from the library returs a unsigned char* num_carte_transcode And the function I implemented in the JNI C++ file returns a jstring. So I nee...
The string passed to NewStringUTF must be null-terminated. The string you're passing, however, is not null-terminated, and it looks like there's some garbage at the end of the string before the first null. I suggest creating a larger array, and adding a null terminator at the end: JNIEXPORT jstring JNICALL Java_com_exa...
72,773,734
72,773,824
C++11 packaged_task doesn't work as expected: thread quits and no output
I've this code snippet: #include<future> #include<iostream> using namespace std; int main() { cout << "---------" << endl; packaged_task<int(int, int)> task([](int a, int b){ cout << "task thread\n"; return a + b; }); thread tpt(move(task), 3, 4); cout << "after thread creation\n"; future<int> sum =...
You're moving the packaged task into the thread and then trying to get the future object from the moved-from task which no longer has any state. For me this throws an exception: https://godbolt.org/z/Gh534dKac terminate called after throwing an instance of 'std::future_error' what(): std::future_error: No associated ...
72,774,044
72,775,239
C++ type from dtype (how to initialize a cv::Mat from a numpy array)
pybind11 has the following method in numpy.h: /// Return dtype associated with a C++ type. template <typename T> static dtype of() { return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::dtype(); } How do I get the inverse? the C++ type from a variable of type dtype ? EDIT My ...
cv::Mat has a constructor that accepts a void* for the data pointer. Therefore you don't need to convert the dtype into a C++ type. You can simply use: cv::Mat img2(rows, cols, type, (void*)img.data());
72,774,210
72,778,221
sprintf_s problems. It worked on Windows, but not on Xcode
sprintf_s(colorBuffer, 255, "%.2X", getAlpha()); result.append(colorBuffer); The error is: Use of undeclared identifier 'sprintf_s'
sprintf_s is part annex K of the C11 standard, titled "bounds-checking interfaces". Annex K is optional. Annex K hasn't been successful. N1967 Field Experience With Annex K — Bounds Checking Interfaces stated in 1995: Despite more than a decade since the original proposal and nearly ten years since the ratification of...
72,774,285
72,811,024
Abort trap 6 when merging arrays in bottom-up Merge Sort
I was trying to implement Merge Sort (Bottom-up approach) until a mysterious Abort trap occurs: void botup_mergesort(int *arr, int begin, int end) { for (int merge_sz = 1; merge_sz < (end - begin); merge_sz *= 2) { for (int par = begin; par < end; par += merge_sz*2) { const int &sub_...
The following change will fix the error: const int& m = std::min(par + merge_sz, end); The code could be a bit faster if a one time allocation of a full sized second array was done, and if the direction of merge was changed on each pass, instead of doing a copy back after each merge. The code would need to det...
72,774,371
72,778,284
How to compile a Qt program without qtCreator on Windows?
I have read the question Can I use Qt without qmake or Qt Creator? which is basically the same for Linux, and very useful. How to compile a basic program using QtCore (console application, even without GUI) on Windows, without using qmake or qtCreator IDE, but just the Microsoft VC++ compiler cl.exe? For example, let's...
I finally managed to do it 100% from command line, without the qtCreator IDE, but not yet without qmake. Steps to reproduce: Let's assume Microsoft MSVC 2019 is installed. Install qt-opensource-windows-x86-5.14.2.exe. (This is the latest Windows offline installer I could find), double check that you install at least ...
72,774,495
72,775,174
How to traverse a graph with algorihtm
Need to find how many translators need for two persons to be able talking to each other. Given values are A : 1 2 B : 7 8 C : 4 5 D : 5 6 7 E : 6 7 8 F : 8 9 And the translators which we are looking for are as below B > E Can translate directly, answer : 0 A > B Can't translate, answer : -1 C > F Need 2 translators C ...
I think your graph construction is wrong, it's not really a graph at all. You need to do some work to translate the input into a proper graph. In your code you've created a mapping from language (1, 2, 3 etc) to translators (A, B, C etc) but really the problem is asking for a mapping from translators to translators (th...
72,774,506
72,774,642
std::unique_lock and std::shared_lock in same thread - shouldn't work, but does?
Why is it possible to acquire two different locks on a std::shared_mutex? The following code #include <shared_mutex> #include <iostream> int main(int /*argc*/, char * /*argv*/[]) { std::shared_mutex mut; std::unique_lock<std::shared_mutex> ulock{mut}; if(ulock) std::cout << "uniqe_lock is bool true...
Also from cppreference: "If lock_shared is called by a thread that already owns the mutex in any mode (exclusive or shared), the behavior is undefined." You have UB; the toolchain is not required to diagnose this, though it might if you enabled your stdlib's debug mode (_GLIBCXX_DEBUG for libstdc++).
72,774,707
72,776,703
How can I catch a unique constraint violation through QT's QSqlDatabase interface?
The title says it all, really. I have a QT application, using the QSqlDatabase interface, and I need to take a different action on a unique key constraint violation as opposed to any other type of error. Currently the backend database is SQLite, if that matters. However, management is talking about switching to MS SQL ...
You can use a QSqlQuery::lastError method to check an error occured while INSERT or UPDATE query execution. It returns QSqlError, which has a nativeErrorCode method. I'm not sure, if it contains only a numeric value or a full error description. In common, according to documentation SQLite should return 2067 error, howe...
72,775,443
72,775,511
Is there a purpose for using a macro that does nothing over an empty macro in c++?
Learning c++ and reading through a project, I found this. #define EMPTY_MACRO do {} while (0) ... #if ASSERTS_ENABLED #define ASSERTCORE(expr) assert(expr) #else #define ASSERTCORE(expr) EMPTY_MACRO #endif What is the purpose of EMPTY_MACRO? Is it unnecessary or is there a reason for it?
It's there so ASSERTCORE(expr); behaves the same with or without ASSERTS_ENABLED. A plain #define ASSERTCORE(expr) would leave behind a lone ; and that would behave differently in some cases.
72,775,454
72,837,741
How to modernize code that uses deprecated NumPy C API?
The following C or C++ code, intended for use in a Python extension module, defines a function f that returns a NumPy array. #include <Python.h> #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <numpy/arrayobject.h> PyObject* f() { auto* dims = new npy_intp[2]; dims[0] = 3; dims[1] = 4; PyOb...
The code is up to date. There is no need for modernization. The code line #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION is required by bad design. See the discussion on the NumPy issue tracker, https://github.com/numpy/numpy/issues/21865.
72,775,490
72,776,032
C++20: Validate Template Bodies Against Concepts
C++20 introduces concepts, which allows us to specify in the declaration of a template that the template parameters must provide certain capabilities. If a template is instantiated with a type that does not satisfy the constraints, compilation will fail at instantiation instead of while compiling the template's body a...
TL;DR: no. The design for the original C++11 concepts included validation. But when that was abandoned, the new version was designed to be much more narrow in scope. The new design was originally built on constexpr boolean conditions. The eventual requires expression was added to make these boolean checks easier to wri...
72,775,755
72,775,909
C++, fast removal of elements from vector by binary index
There are several posts focused on the fast removal of elements given by indices from a vector. This question represents a slightly modified version of the problem. There is a vector of elements: std::vector <double> numbers{ 100, 200, 300, 400, 500, 600 }; and the corresponding binary index: std::vector<bool> idxs{ 0...
Unfortunately there is no automatism for this. You simply have to implement a custom erase function yourself: auto widx = numbers.begin(); for (auto ridx = numbers.cbegin(), auto bidx = idxs.cbegin(); ridx != numbers.end; ++ridx, ++bidx) { if (*bidx) *widx++ = *ridx; } numbers.erase(widx, numbers.end());
72,775,945
72,776,090
using remove method of std::list in a loop is creating segmentation fault
I am using remove() of std::list to remove elements in a for loop. But it is creating segmentation fault. I am not using iterators. Program is given below. #include <iostream> #include <list> using namespace std; int main() { list <int> li = {1, 2, 3, 4, 5}; for(auto x : li) { if (x == 4) { ...
But here I am not using iterators and I am using remove() which doesn't return any. Can any one please let me know if we can't use remove in a loop or if there is any issue with the code. You are mistaken. Range-based for loops are based on iterators. So after this call: li.remove(x); The current used iterator becom...
72,776,522
72,776,628
Boost rotation matrix no match for operator *
I am trying to rotate a vector based on another orientation vector. Elsewhere in the code, this works fine. But here, it fails and Boost complains about an operator error. // (Assume these vectors are filled with useful values) boost::qvm::vec<double, 3> aspectVec; boost::qvm::vec<double, 3> orientation; // Ro...
The issue was the includes. I noticed they were the only difference in the code between the two files. I swapped out: #include <boost/qvm/mat_operations.hpp> #include <boost/qvm/vec_operations.hpp> For: #include <boost/qvm/all.hpp> And the problem went away. I'm not really sure why, but it did. I don't like including...
72,776,764
72,776,865
Determine data type of items in an STL container in a template method
I'm trying to write a template method to handle items in an STL container. Getting details of the container is easy (and I use a std::enable_if clause to allow this template method to be called only if the container can be iterated over (detects a begin() method.)) I further need to know the data type held by the con...
You could use template template parameters: template <template <class, class...> class CONTAINER, class ITEM, class... REST> std::string doStuff(const CONTAINER<ITEM, REST...>& container) { using CONTAINER_TYPE = ITEM; // or `typename CONTAINER<ITEM, REST...>::value_type` // This requires SFINAE to not match `ITE...
72,777,019
72,777,133
c++ complains about __VA_ARGS__
The following code has been compiled with gcc-5.4.0 with no issues: % gcc -W -Wall a.c ... #include <stdio.h> #include <stdarg.h> static int debug_flag; static void debug(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); } #define DEBUG(...) \ ...
Since C++11 there is support for user-defined literals, which are literals, including string literals, immediately (without whitespace) followed by an identifier. A user-defined literal is considered a single preprocessor token. See https://en.cppreference.com/w/cpp/language/user_literal for details on their purpose. T...
72,777,348
72,777,381
Why C++ template array length deduction need to be like "f(T (&a)[N]"?
Use C++ template to know the length of C-style array, we need this: #include<stdio.h> template<class T,size_t N> size_t length(T (&a)[N]){ return N; } int main() { int fd[2]; printf("%lld\n", length(fd));; return 0; } It works, prints 2. My question is about the syntax. In the declaration of length, why th...
In this function declaration template<class T,size_t N> size_t length(T a[N]){ return N; } the compiler adjusts the parameter having the array type to pointer to the array element type. That is this declaration actually is equivalent to template<class T,size_t N> size_t length(T *a){ return N; } On the other hand, th...
72,777,590
72,777,625
How to use Resources in c++?
I want to put an exe file in my C++ program, but I don't understand how to do it. I am using Visual Studio 2019. I know that it can be done through project resources, but I don't know how to work with it.
Create an .rc file to refer to the desired embedded .exe as an RCDATA resource, eg: MYEXE RCDATA "path\to\file.exe" Add the .rc file to your project. The referred .exe file will then be compiled into your final executable. You can then access the MYEXE resource at runtime using the Win32 FindResource()/LoadResource()/...
72,777,821
72,778,827
Eigen::Map and dimension change 4 to 3
Context: I want to operate rotations and scaling on an existing array, representing a 4x4 matrix, using Eigen. I don't know how to do it without copying data around: Edit: Input matrix is of type array<double,16> The code: Rotation: Eigen::Map <Eigen::Matrix4d> mapped_data( (double *)&input_matrix ); auto rot ...
Eigen's geometry module has a handy Transform class that helps with this stuff. Something like this should work: using Affine3d = Eigen::Transform<double, 3, Eigen::Affine>; double angle_z = ..., sx = ..., sy = ..., sz = ...; Affine3d transform = Eigen::AngleAxisd(angle_z, Eigen::Vector3d::UnitZ()) * Eigen:...
72,778,175
72,778,943
Can I get the memory address on the data from the static JNI field?
Can I get the memory address on the data from the static JNI field? For example, I have 2 situations: First: jclass clazz = ...; jfieldID staticFiled = ...; // static field on java object uintptr_t *staticFiledPtr = ((uint64_t) staticFiled); // get field ptr jboolean *boolPtr = *magic code with static field*; *boolPtr...
Fields in the JVM have no addresses. There are only references to objects (which are not pointers), and then those references are accessed at a certain offset to read or write a field. This operation might involve un-compressing and adding the reference' value to the heap base address to obtain a temporary memory addre...
72,778,474
72,779,009
What are the best sorting algorithms when 'n' is very small?
In the critical path of my program, I need to sort an array (specifically, a C++ std::vector<int64_t>, using the gnu c++ standard libray). I am using the standard library provided sorting algorithm (std::sort), which in this case is introsort. I was curious about how well this algorithm performs, and when doing some r...
Introsort takes your concern into account, and switches to an insertion sort implementation for short sequences. Since your STL already provides it, you should probably use that.
72,778,797
72,778,802
Resolving apparent circular dependency: class A having a method that takes in class B, while class B having a member of type class A
I have two classes that I want to define, Position and TangentVector, partially given as follows: class Position { public: Position(double x, double y, double z); // getters double x(){ return m_x }; double y(){ return m_x }; double z(){ return m_x }; void translate(const TangentVector& ta...
class Position takes only a reference to class TangentVector. Therefore you might pre-declare TangentVector as class TangentVector; before the declaration of class Position: class TangentVector; class Position { public: Position(double x, double y, double z); // getters double x(){ return m_x }; d...
72,779,101
72,779,145
Why do I have to make a 2d array for this
I was solving a question online on strings where we had to perform run-length encoding on a given string, I wrote this function to achieve the answer using namespace std; string runLengthEncoding(string str) { vector <char> encString; int runLength = 1; for(int i = 1; i < str.length(); i++) { if(str[i ...
std::to_string() returns a std::string. That's what it does, if you check your C++ textbook for a description of this C++ library function that's what you will read there. encString.push_back( /* something */ ) Because encString is a std::vector<char>, it logically follows that the only thing can be push_back() into i...
72,779,225
72,795,934
How to use results from mysql built-in functions when inserting via mysql-x-devapi in C++?
I am using mysql-x-devapi and need to insert a row to a table and put UNIX_TIMESTAMP() of the server in a column: sql_client_.getSession().getDefaultSchema() .getTable("event") .insert("title", "time") .values("event title", "UNIX_TIMESTAMP()") .execute(); This code gives me: CDK Error: Incorrect integ...
I used mysqlx::expr("UNIX_TIMESTAMP()"): sql_client_.getSession().getDefaultSchema() .getTable("event") .insert("title", "time") .values("event title", mysqlx::expr("UNIX_TIMESTAMP()")) .execute(); then fixed the compile error by touching: /usr/include/mysql-cppconn-8/mysqlx/devapi/table_crud.h replace...
72,779,255
72,779,290
Getting a specific element from Queue
I have a queue: queue<string> saves. I need to use it's ability to remove elements from the front. Is there a way to get a specific element in the queue like the 5th one? Neither saves.at(4) nor saves[4] works.
The entire point of a queue is you can only see and get the item, if any, waiting at the out end. Anything that allows you to see any other values in the queue is not a queue. Wanting to see inside the queue suggests that you do not want a queue. Try a std::deque instead.
72,779,319
72,779,460
How can you require that a concept parameter is a reference `&` type?
In the following concept implementation struct, String, the operator() method does not take the value Source by reference but still satisfies the concept Consumer. How can I prevent String from being a valid Consumer, specifically by requiring Source source to be a reference &? template <class Type, class Source> conce...
You cannot (reasonably) detect if takes a reference parameter. But you can detect if it can take an rvalue: template <class Type, class Source> concept ConsumerOfRvalue = requires(Type type, Source &&source, std::ranges::iterator_t<Source> position) { type(std::move(source), position); }; If the function takes its...
72,779,418
72,779,509
C++ function resolution matches different function when I adjust their sequence
I've got a test program to see how compiler(g++) match template function: #include<stdio.h> template<class T>void f(T){printf("T\n");} template<class T>void f(T*){printf("T*\n");} template<> void f(int*){printf("int*\n");} int main(int argc,char**) { int *p = &argc; f(p); // int* return 0; } It print...
You have two (overloaded) template functions here, and a third function f(int*) that is specializing one of the template functions. The specialization happens after after the overload resolution. So in both cases you will select f(T*) over f(T). However, in the first case when you have specialized f(T*), you will get...
72,779,432
72,779,469
Advice for getting a pointer to an object from a vector stored inside a class
class Element { class Point { private: double x; double y; public: //getters/setters for x and y }; private: std::string name; std::vector<Point> values; public: void insertValue(unsigned int index, double x, double y); ...
The usual idiom for this is to have two methods, a const one and a non-const one. In this case one returns a const Element *, and the other one returns an Element *, keeping everything const-correct. const Element* elementAt(unsigned int index) const { return &elements.at(index); } ...
72,779,626
72,779,716
Why does std::barrier allocate?
Why does std::barrier allocate memory on the heap while std::latch doesn't? The main difference between them is that std::barrier can be reused while std::latch can't, but I can't find an explanation on why this would make the former allocate memory.
While it is true that a naive barrier could be implemented with a constant amount of storage as part of the std::barrier object, real-world barrier implementations use structures that have > O(1) storage, but better concurrency properties. The naive, constant-storage barrier can suffer from a large number of threads co...
72,781,255
72,781,527
Can you call a constexpr function to assign a constexpr value with a forward declaration?
I found myself in a weird spot, with the error message "expression did not evaluate to a constant": constexpr uint64 createDynamicPipelineStateMask(); static inline constexpr uint64 dynamic_state_mask = createDynamicPipelineStateMask(); struct CullMode { static constexpr inline bool bIsDynamicState = false; ...
I know that it's compiler, and not the linker that needs the full definition of the constexpr function, but the compiler has it right below. The behavior of the program can be understood using expr.const#5 which states: 5. An expression E is a core constant expression unless the evaluation of E, following the rules ...
72,781,450
72,925,857
Recursive nested initializer list taking variant
I want an object obj to be initialized from an initializer_list of pairs. However, the second value of the pair is a variant of bool, int and again the obj. gcc reports trouble finding the right constructors I guess. Can I make this work recursively for the following code? #include <utility> #include <string> #include ...
As Igor noted, without any changes to your type or constructor, your code can compile fine with an explicit type specified for your subobject: obj O = { { "level1_1", true }, { "level1_2", 1 }, { "level2", obj { { "level2_1", 2 }, { "level2_2", true }, } }, }; I believe the problem may ...
72,781,492
72,790,900
C++20 : Memory allocation of literal initialization of const references
I am trying to optimize for speed of execution a piece of code using the factory design pattern. The factory will produce many objects of a class having some members that are constant throughtout the execution of the program, and some members that are not. I always initialize the constant members with literals. My ques...
The easiest way to get what you want is just to make name_ a const char *: class Test { private: const char *const name_; int value_; public: Test(const char *name, int value) : name_(name), value_(value) {} }; int main() { Test test1("A", 1); Test test2("B", 2); Test test3("B", 3); Test test4("A", 4); ...
72,782,114
72,782,532
Get PDF Page size from HDC C++
I want to draw string in 3 location(Top, Center, bottom) of my printing page. I use Gdiplus::RectF and drawstring() to Draw string in the page. for setting string Location I need the Page dimentions. I have to Hook EndPage (Inject DLL) and I have only the HDC. how can I Get the dimentions of printing page? here is my c...
I find The method that is somehow close to the correct answer, it returns dimensions close to correct size, but it's not exact. I get the printable area of the page Width and Height in pixel by GetDeviceCaps(hdc, HORZ|VERT RES) and get Number of pixels per logical inch along the screen Width and Height by GetDeviceCaps...
72,782,588
72,783,673
C++ reinitializing variables in a while loop
I have a settings menu that can make the window fullscreen. Most of the menu elements are dependent on the window size. By default, all the menu elements are in the same position they were in before the window was resized (meaning they are not in the position I intend). I understand the positions needs to be recalculat...
In short: std::make_unique makes new objects, every time it's called. It cannot reuse the memory of the previous object. What would happen if the constructor of the new object throws an exception? It's only in the assignment to the existing unique_ptr that the old object is discarded, and you wouldn't get there if an e...
72,783,071
72,783,562
What does field 'predicate' exactly mean in (find_if) function in cpp?
I'm a beginner in c++. I was learning STL especially vectors & iterators uses..I was trying to use (find_if) function to display even numbers on the screen.I knew that I have to return boolean value to the third field in the function(find_if) ..but it gives me all elements in the vector !!! .but,When I used the functio...
You can use std::find_if, but each call finds only one element (at best). That means you need a loop. The first time, you start at v.begin(). This will return the iterator of the first even element. To find the second even element, you have to start the second find_if search not at v.begin(), but after (+1) the first f...
72,784,373
72,785,068
Weird LTO behavior with -ffast-math
Summary Recently I encountered a weird issue regarding LTO and -ffast-math where I got inconsistent result for my "pow" ( in cmath ) calls depending on whether -flto is used. Environment: $ g++ --version g++ (GCC) 8.3.0 Copyright (C) 2018 Free Software Foundation, Inc. This is free software; see the source for copying ...
man gcc: To use the link-time optimizer, -flto and optimization options should be specified at compile time and during the final link. It is recommended that you compile all the files participating in the same link with the same options and also specify those options at link time. For example: gcc -c -...
72,784,505
72,790,117
Figure out which desktop is active at the moment from the Win service
I have a Win service running under the SYSTEM account. In case the user logs out from the system, the service should detect this and restart particular application on the logon desktop (and stop itself in case than user closing this application manually). The obvious way for me is detect which desktop (Default, ScreenS...
Services run in a different session than users do. Desktops (and other UI resources) belong to the Session they are created in, and cannot be accessed across session boundaries. So the service simply can't directly access a user's desktops at all. To access a given user's desktop, you will have to run a separate proces...
72,784,535
72,784,598
how to use objects of nested classes
I have a class in a header file: dmx.h // dmx.h #ifndef dmx_h #define dmx_h class Dmx { public: Dmx() { } // some functions and variables void channelDisplay() { } class touchSlider; }; #endif and a nested class in another header file: tou...
The problem is that inside the class dmx you already provided a definition for the nested class touchSlider since you used {} and so you're trying to redefine it inside touchSlider.h. To solve this you can provide the declarations for the member functions of touchSlider in the header and then define those member functi...
72,784,867
72,784,981
private and public, how to make it work properly? -> C++
I have been trying to make the string name; private. I left the correct font below without putting the "string name"; in particular. Well, all attempts failed to put the "string name; private. Does anyone know how I could do this correctly. I'm new to C++ and object-oriented programming. #include <iostream> #include <s...
A private parameter is only accesible from the class it is declared in. If you want to be able to get or set the information stored in a private field you have to make what we call (public) getters and setters methods. private: std::string nome; public: std::string get_nome() { return this->nome; } ...
72,785,753
72,786,006
Count maximum consecutive occurrence of a substring in a string, using only basic string operations
int longest_str(std::string str, std::string dna) { int longest_count = 0; int current_count = 0; std::string temp; for (int i = 0; i <= (dna.size() - str.size()); ++i) { if (dna.at(i) == str.at(0)) { for (int j = i; j < i + str.size(); ++j) { temp.push_back(dna.at(j))...
The issue is that you do: i += str.size() but you forget that your loop itself is also incrementing i, so you are actually skipping an index. Second issue is that you might exit the loop before if (current_count >= longest_count) { longest_count = current_count; } is executed, if your last match w...