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,042,839
72,042,950
nested list struct c++
I have a nested list: struct CHANNEL { char channel_id[200]; char name_Channel[200]; }; struct Line { CHANNEL* chan; PROGRAM* prog; HOST* host; DATE_TIME* date; struct Line* next; }; but when I create a Line variable and try to work with it char number[200]; Line* p; p = (struct Line*)malloc(sizeof(*p)); ...
This line: p = (struct Line*)malloc(sizeof(*p)); Allocates memory for an object of struct Line. It does not initialize the object. One of the uninitialized data members of this object is CHANNEL* chan. Therefore when you try to access p->chan->channel_id, p->chan is uninitialized and you cannot use it to access the CH...
72,043,955
72,044,938
Address of a constexpr in a template parameter
Can someone solve the mystery of why do I get linking errors if I take the address of a variable that should go in a template parameter only if I make the variable const, constexpr or static, but not oherwise? The piece(s) of code below are part of a larger project, but I extracted the exact same structure: CMakeLists....
The additional specifiers (e.g const, constexpr) makes the template parameter have internal linkage, which subsequently makes testBlaa(int) have internal linkage. It works if you do extern const P p{} right? Maybe Why does the following method get internal linkage? is similar?
72,043,966
72,044,153
Why can an anonymous temporary exception be bound to a reference at a catch site?
Consider #include <iostream> struct Foo{}; int main(){ try { throw Foo(); } catch (Foo& e){ std::cout << "Caught"; } } The output is Caught, but why? I would have thought that the catch should have been const Foo&. What am I forgetting?
I would have thought that the catch should have been const Foo&. It doesn't need to be. I suspect that you are expecting that there would be a problem with binding of an lvalue reference to non-const. [except.handle] The variable declared by the exception-declaration, of type cv T or cv T&, is initialized from the e...
72,044,055
72,044,295
2d array average and total c++
it has to appear like this: #include <iostream> using namespace std; int main() { float allsales[3] [2] = {{1200.33, 2350.75}, {3677.80, 2456.05}, {750.67, 1345.99}}; float totalsales = 0, ave = 0, sum = 0; for (int row = 0; row < 3; row++) { cout << "Ave sale for store "<< row ...
How would you do it by hand? I would start sum with an initial value of zero for each row, add to it each element in that row, and then compute the average at the end of the row. (Don't forget that you can declare variables in other places than first thing in a function.) And I would also probably first sum the row, an...
72,044,415
72,045,748
How can I read a specific value c++ using a text file to store in data structure
How do i seperate my text file values to store in a vector I have a file.txt with values such as DOB,NAME,Arrival,Depature 12/04/2021,Dennis,12:30:20,14:30:40 10/03/2001,Sam,14:20:30,- I want to store these values in a vector I have figured out how to store all of them in the vector but now i am creating another vecto...
#include<vector> #include<string> #include<fstream> using namespace std; void split(const string& s, vector<string>& tokens, char delim = ' ') { tokens.clear(); auto string_find_first_not = [s, delim](size_t pos = 0) -> size_t { for (size_t i = pos; i < s.size(); i++) { if (s[i] != delim) re...
72,044,765
72,044,927
wanna know the difference of these two almost same answers
I'm doing a leetcode problem which you can check it here:https://leetcode.com/problems/binary-tree-preorder-traversal here's my first time answer which is a wrong answer: class Solution { public: TreeNode* preorderTraversal(TreeNode* root, vector<int> &res){ if(root) res.push_back(root->val); else return nu...
Preorder traversal requires to visit all the nodes in the tree. In your 1st version you have these lines: if(root->left) return preorderTraversal(root->left,res); if(root->right) return preorderTraversal(root->right,res); If root->left is not null the return statement will be executed, and will cause the function's ex...
72,044,851
72,044,930
What is this curly brace cpp syntax?
Alas, it's hard to google for symbols like braces. I came across this code: #include <functional> #include <iostream> template <typename A, typename B, typename C = std::less<>> bool fun(A a, B b, C cmp = C{}) { return cmp(a, b); } int main() { std::cout << std::boolalpha << fun(1, 2) << ' ' /...
it create an instance of std::less<int> then pass 5,5.6 as the parameter to it's bool operator()(const int&, const int&) it's roughly the same as auto temp = std::less<int>{}; std::cout << temp(5, 5.6);
72,044,972
72,045,828
How to override a method of a base class which is an input of a function?
I am trying to override a method in a code I am using to learn about this but I didn't succeed, what am I missing? Here some code to reproduce my issue: my_class.h #ifndef MY_CLASS_H #define MY_CLASS_H class Base { public: Base(); virtual ~Base(); virtual double evaluate(double x); }; do...
In short, you need to change call_evaluate to receive the first argument by reference. double call_evaluate(Base& funct, double x); For the reason why your program behaves like it does, see below. Your coding style suggests you come from a Java-like background. You must make yourself aware of a very important point ab...
72,045,055
72,045,239
why the const in c++ conversion operator is meaningless?
In "C++ Primer", exercise 14.47, there is a question: Explain the difference between these two conversion operators: struct Integral { operator const int(); operator int() const; } I don't know why the the answer I found on GitHub says that the first const is meaningless, because for one conversion operator ...
it will be ignored by compiler. This is because of expr#6 which states: If a prvalue initially has the type cv T, where T is a cv-unqualified non-class, non-array type, the type of the expression is adjusted to T prior to any further analysis. This means that in your particular example, const int will be adjusted t...
72,045,119
72,045,187
If two digits are the same 0s then make 0 condition in C++ and Root
In my code, legends are running within a loop, and I am trying to show a graph with 0-10% 10-20% and so on. The problem is when I write this code legend->AddEntry(gr[i], Form("%d0-%d0 %%",i+0,i+1), "lep"); It shows 00-10% 10-20% etc So how to not show 00, but 0 in the first line?
A small adaptation of the shown statement should be enough; use: legend->AddEntry(gr[i], Form("%d-%d %%", i*10 , (i+1)*10), "lep"); Explanation: Form("%d0-%d0 %%",i+0,i+1) seems to be some kind of string formatting, and i your loop variable which runs from 0 to 9, right? The shown Form statement just appends "0" hard-...
72,045,325
72,045,668
libcurl to put stream of data instead of file
We are using libcurl C API in order to send a file over SFTP. This works fine using a code like this : .... fd = fopen(local_file_full_path.c_str(), "rb"); if (!fd) { cout << "Error opening local file: " << local_file_full_path << endl; return -1; } curl_easy_setopt(curl_easy_handle, CURLOPT_UPLOAD, 1L); curl_e...
You already have 1/2 of the solution - CURLOPT_READDATA . You just need to pair it with a custom callback in CURLOPT_READFUNCTION, then you can pass a pointer to your existing data in CURLOPT_READDATA and have your callback copy that data into libcurl's buffer when it needs the data. This callback function gets called...
72,046,562
72,047,359
Alternatives for storing a class member as a raw pointer
In the code example shown below - in Container class, it owns (and is responsible fore destroying) two objects c, d, which are subclasses of an abstract class B. Container object can create new ObjectDisplay that takes a kind of B in its constructor. I can pass the abstract type B as a pointer into ObjectDisplay and st...
If B wasn't an abstract class, I could pass it in ObjectDisplay as a reference No, if B is an abstract class, you can still pass it by reference. B& object can be bound to an instance of B's subclass. It behaves almost the same as pointers. As quoted in cppref: That is to say, if a derived class is handled using poi...
72,047,016
72,047,767
How to set enum val of fixed size to its max possible value?
This is probably simple but I'm not getting it right. I have a "bitmask" enum which has a value all that indicates that all bits are set. However, I can't get it to flip all bits using ~0. The following error appears: <source>:11:16: error: enumerator value '-1' is outside the range of underlying type 'uint_fast8_t' {a...
By default, 0x0 is of type int. So if you try to flip all the bits you'll get -1 which can't be assigned to the type your enumeration was defined to. Even if you use a suffix for that literal value, like u for example. To indicate that the literal value is of unsigned type. As in ~0x0u. You'd get the maximum of the uns...
72,047,595
72,047,812
Make dynamically allocated object type string
I need to make dynamically allocated object type of string to store sentences and after that sentences should be sorted in alphabetical order using std::sort. This would be correct solution using char array: #include <cstring> #include <iostream> #include <new> #include <string> #include <algorithm> int main() { std:...
It looks like you think std::string "corresponds to" char, but it corresponds to char*. You want std::string* sentence = nullptr;. (A lot of the point of this exercise is to notice how much easier it gets when you don't need to allocate the strings yourself.) int main() { try { std::cout << "How many sentences: "...
72,047,718
72,047,818
Assigning to std::array element in std::vector of arrays fails
Today, I'm working on understanding some new-to-me features, particularly std::array and std::vector. Individually, these seem to behave as expected, but I'm very puzzled by the behavior illustrated below: This version works: printf("Using pointer:\n"); std::vector<std::array<int, 1>*> vap; vap.push_back(new std::array...
You are working on a copy of the array, you need a reference to the array in the vector int main() { vector<array<int, 1>> v; array<int, 1> a = { 99 }; v.push_back(a); cout << v[0][0]; auto& ar = v[0]; ar[0] = 42; cout << v[0][0]; } gives 99 42
72,048,000
72,048,086
Class "name" has no member class "name of the member"
I`m new to OOP. Here is the code: #include <cstdint> #include <string> #include <iostream> namespace name { class Class { private: struct u { std::string l{}; struct u* next{}; }; public: Class(std::string s) : u::l(s) ...
this struct u { std::string l{}; struct u* next{}; }; does not do what you seem to think it does, it is just defining the type 'u', it does not say that 'Class' contains an instance of 'u'. Plus you have to have a constructor in order to use that initialization syntax namespace name { c...
72,048,009
72,048,219
size and alignment of int bitfields
A struct with bitfields, even when "packed", seems to treat a bitfield's size (and alignment, too?) based on the specified int type. Could someone point to a C++ rule that defines that behavior? I tried with a dozen of compilers and architectures (thank you, Compiler Explorer!) and the result was consistent across all....
Could someone point to a C++ rule that defines that behavior? Nothing about #pragma pack(push, 1) is specified by the standard (other than #pragma being specified as a pre-processor directive with implementation defined meaning). It is a language extension. This is what the standard specifies regarding bit fields: [...
72,048,397
72,048,480
c++ function template restrict parameter type
Given the class class foo { public: void func(std::string s){}; void func(int i){}; void func2(std::string s){}; void func2(int i){}; }; I'd like to get rid of the multiple function overloads by just using template functions. However, the functions should ONLY accept an int or a std::s...
Using enable_if you could write the function like template <typename arg_t, std::enable_if_t<std::is_same_v<std::decay_t<arg_t>, int> || std::is_same_v<std::decay_t<arg_t>, std::string>, bool> = true> void func(arg_t arg){}
72,048,553
72,048,689
What is the purpose of ccall and cwarp functions in Emscripten?
I'm following the instructions from the Emscripten documentation here, and I want to practice with minimal examples. My final goal is to create a C++ library, compile it to a single wasm binary file and then use these compiled methods in pure-frontend web application. I do not understand what is the purpose of calling ...
There is no difference in such the tiny example. There might be issues in big projects. Less important. Module.ccall can perform async call with the parameter async=true, whereas call to the exported function Module._doubleNumber is always sync. More important. At higher optimisation levels (-O2 and above), the closur...
72,048,908
72,049,033
Use vcxproj instead of Cmake for internal vcpkg port
We have some libraries written in Visual Studio that we would like to share with other projects in different solutions in different repos. I liked the idea of using an internal vcpkg registry to distribute those libraries to those other solutions/projects. My concern here is that the libraries we'd like to share are vc...
Vcpkg has built-in support for wrapping MSBuild (ie. sln/vcxproj) projects. See the function vcpkg_install_msbuild Many projects still use the deprecated vcpkg_build_msbuild, though. Using git grep I can find a few portfiles that will work as examples: gsoap: https://github.com/microsoft/vcpkg/tree/master/ports/gsoap ...
72,049,284
72,049,946
why does omp_get_schedule() return a monotonic schedule when OMP_SCHEDULE=static?
I am compiling my code with g++8.5 on redhat8 and I notice that when I set OMP_SCHEDULE=static, then inside my application omp_get_schedule() returns a "monotonic" schedule instead of a "static" schedule. Why could this be happening? If I set OMP_SCHEDULE to something else such as "dynamic" then my application recogniz...
omp_sched_t is defined as: typedef enum omp_sched_t { omp_sched_static = 1, omp_sched_dynamic = 2, omp_sched_guided = 3, omp_sched_auto = 4, omp_sched_monotonic = 0x80000000 } omp_sched_t; Note that omp_sched_monotonic is a modifier not a type, so monotonic:static i...
72,049,367
72,052,358
Determine the object type of a HDF5 path
I have a path name (a string) and an open HDF5 file. I have used H5Lexists to ensure an object with that name exists. How do I determine what the object type is? e.g. dataset, group, etc. // open the file hid_t fapl = H5Pcreate(H5P_FILE_ACCESS); H5Pset_fclose_degree(fapl, H5F_CLOSE_STRONG); hid_t hid = H5Fopen(filena...
Use H5Oopen if you don't know the type in advance and use H5Iget_type to determine it. hid_t object = H5Oopen(hid, path.c_str(), H5P_DEFAULT); H5I_type_t h5type = H5Iget_type(object); if (h5type == H5I_BADID) { ... // error handling stuff } else if (h5type == H5I_DATASET) { ... // dataset stuff } else if (h5ty...
72,049,956
72,050,316
Identify laptop display vs external monitor programmatically in C++
I'm IT for my company and multiple of our user know very little of computers. We have multiple drop-in stations with docks and external monitors. So users experience display issues when moving to a different station. Monitors resize, duplicate or change frequencies. I made this easy to use one click tool to resize thei...
Perhaps you are looking for the DISPLAY_DEVICE_REMOVABLE flag in the displayDevice.StateFlags field? Value Meaning DISPLAY_DEVICE_REMOVABLE The device is removable; it cannot be the primary display. https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-display_devicea
72,050,034
72,050,067
Nothing prints on console in SFML
I am trying SFML, but got some strange issue, #include <SFML/Graphics.hpp> #include <iostream> int main() { sf::RenderWindow window; window.create(sf::VideoMode(1100, 600), "SFML - learning"); while (window.isOpen()) { std::cout << "Inside the game loop.\n"; // issue is here sf::Event e...
-mwindows means "don't open a console for my application". You might want to remove it in debug builds.
72,050,274
72,050,430
Can't figure out the function for filling array with random numbers c++
So I am trying to make a function randBetween that is going to generate random numbers and after fill the array with those numbers Problem that I missing out on something when I try to move a statement into function #include <iostream> #include <ctime> using namespace std; void fillArray(int arr[], int size, int min,...
Replacing num = ( rand () % (max - min + 1)) + min; with randBetween(min, max); is missing something crucial: You aren't setting the num variable in the second case. Although you do set num inside the randBetween function, this is actually not the same variable; it's defined inside randBetween, so it's not reachable ou...
72,050,404
72,050,580
What does standalone operator * do at beginning of an equation in C++?
I'm going through some code and came across a line like: x = * y What is the asterisk (*) in this case? I have some programming knowledge, but I'm new to C++. I think I grasp the concept of pointer variables, but the order and spaces make me think it's different than the *= operator or *y pointer.
In x = * y, y is most likely a pointer to something, in which case * is used to dereference the pointer, giving you a reference to the object to which y points and x = *y; copy assigns that value to x. Example: int val = 10; int* y = &val; // y is now pointing at val int x; x = *y; // the space after `*` doesn'...
72,050,664
72,050,776
Why don't standard libraries in g++ violate the One Definition Rule when included multiple times?
I poorly understand the linkage process, and I'm struggling with multi-file compilation with template classes. I wanted to keep definitions in one file, declarations in another. But after a day of suffering, I found out that I should keep definitions and declarations in the same transition unit (see here). But my code ...
You need to differentiate between two categories of entities: Those that may have only one definition in the whole program and those that may have a single definition in each translation unit, although these definitions must be identical (i.e. same sequence of tokens plus some more requirements). In any case a single t...
72,050,699
72,051,045
Is there any way to declare a array, not just its elements, as const?
Using std::array I can declare both the array itself and it's objects as const. const std::array<const int,2> a {1,2}; However, if I read the standard correctly, a declaration such as this only declares the array elements const. See this const int a[2] {1,2}; The reason this matters is that if the complete object, in...
The type of the variable declared in const int a[2] {1,2}; is "array of 2 const int" per the rule you linked, but that itself is a const-qualified type by the resolution of CWG 1059, which can be found in [basic.type.qualifier]/3 of the post-C++20 draft: An array type whose elements are cv-qualified is also considere...
72,051,206
72,053,733
Atomic function pointer call compiles in gcc, but not in clang and msvc
When calling function from an atomic function pointer, like: #include <atomic> #include <type_traits> int func0(){ return 0; } using func_type = std::add_pointer<int()>::type; std::atomic<func_type> f = { func0 }; int main(){ f(); } gcc doesn't complain at all, while clang and msvc have problem with call f...
Clang and MSVC are correct. For each conversion function to a function pointer of the class, a so-called surrogate call function is added to overload resolution, which if chosen would first convert the object via this operator overload to a function pointer and then call the function via the function pointer. This is e...
72,051,753
73,345,620
How does ffmpeg extract audio data from mp3 files?
In the ffmpeg documentation, an example of mp2 decoding is given. I try to apply this to mp3: #define SOURCE_FILE "ignore/audio01.mp3" #define TARGET_FILE "ignore/target-audio01.pcm" #define AUDIO_INBUF_SIZE 20480 #define AUDIO_REFILL_THRESH 4096 #define av_perr(errnum) \ char av_err_buff[AV_ERROR_MAX_STRING_SIZE];...
You may want to check if the input MP3 file starts with ID3 tag (pretty sure it does). FFMPEG does pretty awful job with skipping metadata that is not defined by particular codec standard. Thus, av_parser_parse2() would not skip ID3 tags and then avcodec_send_packet() would complain about data you fed it with (since it...
72,051,855
72,051,879
std::map<int, std::bitset<256 > > thread safety w/o mutex?
I have a std::map<int, std::bitset<256 > > m; After construction no new keys will be inserted and no keys will be removed. Can I safely assign the bitset in one thread while reading it in other threads without using a mutex? // thread 1: std::bitset<256> a = getBitset(); m[1] = a; // thread 2: std::bitset<256> b =...
No, it is not safe. operator= of the bitset is a modifying operation, and as such is not guaranteed to be free of a data race if the bitset is simultaneously accessed in another thread. And in practice, it will almost surely cause a data race, since it needs to write to the object. This is not specific to std::bitset, ...
72,052,108
72,052,186
Meaning of 1[pointer] in C++?
Reading cppreference I found this example: int a[4] = {1, 2, 3, 4}; int* p = &a[2]; std::cout << p[1] << p[-1] << 1[p] << (-1)[p] << '\n'; // 4242 I am confused about the meaning of 1[p] and (-1)[p]. Asking for help elsewhere I was told: "1[ptr] is equivalent to *(1 * sizeof(T) + ptr)". So I understand mechanically wh...
Assume p is a pointer or array, and n is an integer. When the compiler sees this: p[n] It logically interprets that expression as: *(p+n) So when it sees this: n[p] The compiler treats it as: *(n+p) Which is algebraically the same as *(p+n) Hence: p[n] == n[p]
72,052,141
72,052,151
Make user-defined types true/false in boolean context in c++
I have a Line that represents the relevant information of a line on the cartesian plane. The type that has, among other members, a bool that indicates whether the slope is defined. I would like to be able to do the following: if(my_line){ double new_slope = my_line.slope * 9; } where the instance my_line itself is ...
In your Line class, implement a bool conversion operator. You could also optionally overload the operator!, but that is not required in C++11 and later. See Contextual conversions. For example: class Line { bool mSlopeDefined; ... public: ... explicit operator bool() const noexcept { return ...
72,052,214
72,052,546
Boost ASIO "Bad address" error when passing unique_ptr to completion handler
I'm trying to implement a simple TCP server using ASIO. The main difference here is that I'm using std::unique_ptr to hold the buffers instead of raw pointers and I'm moving them inside the completion handler in order to extend their lifetime. Here is the code and it works just fine (I guess) void do_read() { auto ...
Yeah it's the order in which argument expressions are evaluated. The std::move can happen before you do .get(). Another Bug: Besides, there seems to be a large problem here: auto data = std::make_unique<uint8_t>(1500); That dynamically allocates an unsigned char (uint8_t) which is initialized from the integer value 15...
72,052,572
72,052,673
illegal instruction occur while using pointer and reference
when reading the source codes of realtime_tools::RealtimeBuffer, I got lots of questions about the pointer and reference. The related codes are shown below: void writeFromNonRT(const T& data) { // get lock lock(); // copy data into non-realtime buffer *non_realtime_data_ = data; new_data_available_...
I tried to change ptr = &data; to *ptr = data;, and ran again the code, the error("illegal instruction") occurred. The problem is that the the pointer ptr was uninitialized(and does not point to any int object) and so dereferencing that pointer(which you did when you wrote *ptr on the left hand side) leads to undefin...
72,052,797
72,057,456
Regex in c++ for maching some patters
I want regex of this. add x2, x1, x0 is a valid instruction; I want to implement this. But bit confused, how to, as I am newbie in using Regex. Can anyone share these Regex?
If this is a longer project and will have more requirements later, then definitely a different approach would be better. The standard approach to solve such a problem ist to define a grammar and then created a lexer and a parser. The tools lex/yacc or flex/bison can be used for that. Or, a simple shift/reduce parser ca...
72,052,949
72,053,252
KeyPressedEvent not registering
I am new to Qt and trying to implement what should be a pretty straightforward "key pressed" event method, but it doesn't seem to be registering properly. Here is the declaration in my header file: #include <Qt> #include <QKeyEvent> class MainWindow : public QMainWindow { Q_OBJECT protected: void KeyPressEven...
It is, as you say, almost exactly what the examples show. They should show void keyPressEvent(QKeyEvent* event) override; See QWidget::keyPressEvent. Note that C++ is case sensitive (K -> k). Also, I've added the override keyword - then the compiler will tell you if you try to override a function which the compiler do...
72,053,134
72,053,220
I'm learning C++ lambda function. Why does it have this output?
This is my code #include<iostream> int* p = nullptr; auto fun() { int a = 1; p = &a; std::cout << &a << std::endl; auto z = [&a]() {std::cout << &a << " "; a++; std::cout << "lambda call " << a << std::endl; }; return z; } int main() { auto z = fun(); std::cout << *p << "\n"; z(); ...
Yes, the problem is that a is a local variable in the fun function and gets destroyed by the time fun finishes. That means, the returned lambda z is referencing an area on the stack where a used to be, but now when z is called this area is used for something else (this is why you see 21880). In order to avoid this prob...
72,054,441
72,054,607
Why is there no warning from -Wfloat-equal when comparing containers of doubles?
If I use the compiler option -Wfloat-equal with GCC or Clang, equality comparisons of float/double values cause a warning. However, when comparing containers (like std::vector or std::tuple) of float or double values, no such warning is raised. Example code (also at https://godbolt.org/z/YP8v8hTs3): #include <tuple> #i...
GCC doesn't report warnings for system headers by default. The desired behavior may be obtained by adding -Wsystem-header compiler flag. Quotation from the documentation: -Wsystem-headers Print warning messages for constructs found in system header files. Warnings from system headers are normally suppressed, on the as...
72,054,860
72,054,960
How template deduce const pointer type?
I've tried following codes in cppinsights: #include <iostream> #include <string> #include <type_traits> #include <vector> template<typename T> void printType(T x) { std::cout << typeid(x).name() << std::endl; } void test() { const std::vector<int>::pointer a = new int[2]; const int* c = new int[2]; print...
Since std::vector<int>::pointer = int*, why const std::vector<int>::pointer a has been interpreted as int* instead of const int*? Because const std::vector<int>::pointer will be interpreted as int* const instead of const int*. Adding a const-qualifier to a pointer makes itself unmodifiable, not the value it points to...
72,055,063
72,056,635
Append to registry without expanding variables
I'll just start off by saying that I'm by no means an expert in C++, so any pointers/tips are greatly appreciated. I'm having some difficulties reading and writing from registry, while keeping variables, i.e. not expanding them. I'm trying to append my executable path to the PATH environment variable (permanently), but...
You are trying to change the PATH setting in the registry. So one would expect that you would get the current PATH setting from the registry, change it, and set the new PATH setting in the registry. But you are not getting the PATH setting from the registry. You are getting the PATH variable from the environment instea...
72,055,210
72,055,520
OpenMP array initialization impact
I am working in parallel with OpenMP on an array (working part). If I initialize the array in parallel before, then my working part takes 18 ms. If I initialize the array serially without OpenMP, then my working part takes 58 ms. What causes the worse performance? The system: Intel(R) Xeon(R) CPU E5-2697 v3 (28 cores ...
There are two aspects at work here: NUMA allocation In a NUMA system, memory pages can be local to a CPU or remote. By default Linux allocates memory in a first-touch policy, meaning the first write access to a memory page determines on which node the page is physically allocated. If your malloc is large enough that ne...
72,055,546
72,055,895
Is this pointer always a runtime construct
I am learning about the this pointer in C++. And i came across the following statement from the standard: An expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine, would evaluate one of the following expressions: this, except in a constexpr function or a co...
The only way to use this in a core constant expression is to call a constructor (and use it in the constructor) or call a member function on an existing object. this except in a constexpr function or a constexpr constructor that is being evaluated as part of e; (emphasis added) In your attempt, the constant expressio...
72,056,424
72,057,076
Why {} is better candidate to be int than string for C++ overload resolution?
Overload resolution favours to consider {} as being of some fundamental type as opposed to some container. For example: #include <iostream> #include <string> void foo(const std::string&) {std::cout << "string\n";} void foo(int) {std::cout << "int\n";} int main() { foo({}); } That compiles without any diagnostics and...
From over.ics.list#9.2: if the initializer list has no elements, the implicit conversion sequence is the identity conversion. [ Example: void f(int); f( { } ); // OK: identity conversion  — end example ] Thus, the conversion from {} to int is an identity conversion, while {} to const std::string& is...
72,058,944
72,059,062
Why is signed and unsigned addition converted differently for 16 and 32 bit integers?
It seems the GCC and Clang interpret addition between a signed and unsigned integers differently, depending on their size. Why is this, and is the conversion consistent on all compilers and platforms? Take this example: #include <cstdint> #include <iostream> int main() { std::cout <<"16 bit uint 2 - int 3 = "<<ui...
When you do uint16_t(2)+int16_t(-3), both operands are types that are smaller than int. Because of this, each operand is promoted to an int and signed + signed results in a signed integer and you get the result of -1 stored in that signed integer. When you do uint32_t(2)+int32_t(-3), since both operands are the size o...
72,059,107
72,062,630
Order of static initialization with function call
I have a static global variable initialized with a function call. This causes the initialization order to be not respected, eve inside a translation unit. This is a reproducer (the order of the code makes little sense here but it resembles the original arrangement in my use case, and is important to trigger the issue, ...
It’s not that you used a function call: it’s that that function isn’t constexpr, and that it’s a (specialization of a) variable template being initialized. The former prevents constant initialization, and the latter removes all ordering constraints for dynamic initialization. Obviously in this case the fix can be tri...
72,060,014
72,068,731
How do i convert gmt time to other timezones in c++
I have wrote a basic code to get the gmt time and i want to add specific hours to get another timezone how do i do that? (if there is any simpler way to do this that will work too) #include <iostream> #include <conio.h> #include <ctime> int main() { time_t tim = time(0); tm* timenow = gmtime(&tim); std::c...
clang/libc++/libstdc++ isn't yet fully supporting the C++20 <chrono> specification. However there exists a free, open-source preview of this part of C++20 that works with C++11/14/17. It exists in namespace date rather than namespace std::chrono, but otherwise is a pretty good approximation of the C++20 spec. It cons...
72,060,593
72,060,701
Pointer obejct function call without instantiating it
I don't understand how does following code called f() function successfully. As object b is not instantiated using new keyword. Please help and Thanks in advance for answers. #include <iostream> using namespace std; class A{ public: void f(){cout<<"f";} }; int main() { A *b; delete b; b->f(); ret...
I don't understand how does following code called f() function successfully. The program has undefined behavior since b is not initialized and is also not pointing to memory allocated by new. Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never...
72,060,900
72,119,352
how to change access time of a file using utime and mktime syscalls and c++?
I was trying to change the access time of a file, but i didn't get the result i wanted. this is what i tried: struct tm time; time.tm_sec=56; time.tm_min=48; time.tm_hour=20; time.tm_mday=12; time.tm_mon=8; time.tm_year=1905; struct utimbuf utime_par; utime_par.actime=mktime(&time); if(utime("fi...
According to the documentation of the function utime, struct utimbuf (which you pass to the function utime) is defined in the following way: struct utimbuf { time_t actime; /* access time */ time_t modtime; /* modification time */ }; However, you are only setting the actime field of this struct, whi...
72,060,984
72,089,631
Generating C# code for a given .proto file produces an error while opening a file
I'm working on Cpp-written dll, which will be used in my C# project. I use google::protobuf::compiler::csharp::Generator to generate .cs file. First, I create google::protobuf::compiler::Importer. To do so, I need to get an instance of DiskSourceTree and implement MultiFileErrorCollector: class ErrorCollector : public ...
Turns out, those were some extra code for a certain customization. If all you do is generating a proto-class (in any supported language), you simply have to register the generator in google::protobuf::compiler::CommandLineInterface: #include <google/protobuf/compiler/command_line_interface.h> #include <google/protobuf/...
72,061,157
72,061,343
What is the time complexity of a recursive function that calls itself N times with one less?
What is the time complexity of a recursive function with this structure void f(int n) { if (n == 0) return; for (int i = n; i >= 1; --i) { // something O(1) f(n - i); } } My thinking is that it follows T(n) = T(0) + ... + T(n-2) + T(n-1) = (T(0) + ... + T(n-2)) + T(n-1) = T(n-1)...
Your analysis seems to be sound. When in doubt you can measure it. If the complexity really is O(2^n) then you can count how often the inner loop is executed and for increasing n the count divided by 2^n should converge: #include <iostream> struct foo { int counter = 0; void f(int n) { if (n == 0) ...
72,061,504
72,061,735
Is there a way to stop GoogleTest after a specific test is run, whether it passes or fails?
I have a large number of unit tests run through GoogleTest. Currently one of them (call it fooTest) is failing when the full test suite is run, but passing when run alone. So one (or more then one) of the tests that run before fooTest is doing something that causes it to fail, which of course is a big nono for testing ...
You have several options: Simply call exit function at the end of fooTest. Create a test fixture. In SetUp check for a flag that is always false, but it sets to true if fooTest is executed. Something like this: bool skip_testing = false; // Class for test fixture class MyTestFixture : public ::testing::Test { pro...
72,062,387
72,068,228
Forward declared friend template class don't need to include header file
Let us have an abstract template class Stack which will inherit realisation from second class parameter in template. // file Stack.h template <class T, template<typename> class Implementation> class Stack : private Implementation<T> { public: Stack() {} virtual ~Stack() {} void push(const T& x) { Implementa...
In order for template code to be compiled, it needs to be called somewhere. In your case, you have two header files both defining what a template should be. The call to the template is being made in a file that includes both Stack and ListStack. Since you are creating the Stack variable in main.cpp, you can get away wi...
72,062,606
72,062,727
Can I initialize object of different types in an if statement?
I know I can write if (int a = 1; /* whatever */) {} and even if (int a = 1, b{3}; /* whatever */) {} but how can I declare, say, a of type int and b of type std::string? Such a thing doesn't work: if (auto a = 1, b{"ciaos"s}; /* whatever */) {} I've not included a standard, because I'm interested in the answer in g...
You are only allowed one variable declaration statement in a if statement and each variable declaration statement can only declare a single type. This is convered in [stmt.if]/3 where is shows the grammar for the if statement you are trying to use is if constexpr(opt) ( init-statement condition ) statement and init-st...
72,062,610
72,064,243
Loading a Bitmap Image into openGL program
I am trying to load a bitmap to my openGL 3d object, however I get this error: loadbitmap - bitcount failed = 8; what I am trying to do is that I have an object and 3 separate bitmap images (Body, Eye, Head) bitmap images, so I`ll try to draw the texture till vector 6498, which are the triangles for the body part. Thi...
According to the posted code, the error message loadbitmap - bitcount failed = 8 indicates that the loaded image uses 8 bits per pixel, probably an 8-bit grayscale image. The documentation of the biBitCount member of the BITMAPINFOHEADER structure (wingdi.h) says: biBitCount Specifies the number of bits per pixel (bpp...
72,062,898
72,064,028
ImportError: No module named <module_name> with pybind11 on MacOS
I am trying to import C++ module created using pybind11 to python script. The directory structure is: pybind_test: main.cpp build CMakeLists.txt test.py pybind11 (github repo clone) It builds successfully and the file module_name.cpython-39-darwin.so is created. However when running test.py I get: ...
As you noticed, the compiled library must be in a route (in terms of file path) reachable by the Python executable (which you achieved by moving test.py to the build directory, where your compiled library is). You could also move the compiled library to your Python's site-packages folder, where other modules are stored...
72,063,191
72,063,402
Can C++20 concepts be redeclared or not?
This one's rather straightforward: according to the cppreference article, concepts can be redeclared no problem: So I figured alright, cool, I don't have to worry about redeclaring my concept for creating "printable enums"; I can declare the concept in both my logging header and my common types header, so I only have ...
This one's rather straightforward: according to the cppreference article, concepts can be redeclared no problem: No, it doesn't say that. This snippet: template<Incrementable T> void f(T) requires Decrementable<T>; template<Incrementable T> void f(T) requires Decrementable<T>; // OK, redeclaration Doesn't redeclar...
72,063,357
72,063,757
Taking the address of a returned temporary object
I have a piece of C++20 code that I believe is valid, but our static analyzer thinks it's unsafe. struct Foo { explicit Foo() { activeFoo = this; } ~Foo() { activeFoo = nullptr; } Foo(const Foo&) = delete; Foo(Foo&&) = delete; inline static const Foo* activeFoo = nullptr; }; Foo makeFoo() { // Is there a...
makeFoo and copy elision (which as you noted is guaranteed in this specific example since C++17) don't even matter. activeFoo can never be dangling. If it was pointing to an object after its lifetime ended, then the destructor of that object would have reset activeFoo to nullptr, meaning it cannot be pointing to the ob...
72,064,332
72,064,369
create a base class object use a derived class constructor c++
Is someone can tell why A a = B(); call constructor fisrt and then destructor immediately? And why the output like this? C A C B D B D A test1 A D A class A { public: A() { cout<< "C A" <<endl; } ~A() { cout<< "D A" <<endl; } void test1() { cout<< "test1 A" << endl; ...
In this declaration A a = B(); there is at first created a temporary object of the type B. So its base constructor A and the constructor of B are called. C A C B The object a is created using the default copy constructor of the class A. After the declaration the temporary object of the type B is destroyed calling ...
72,064,838
72,064,922
What's the different between pointer new and default constructor in Qt?
I'm a newer for Qt and C++. And I feel about below: //1 widget a; a.show(); //2 widget *b=new widget(); b->show(); And I remember widget class (inherited from QWidget) have default constructor. But if I use it in a button like: void MainWindow::on_pushButton_clicked() { //widget v; //v.show(); widget *v=ne...
It is because in the first snippet, the object gets placed on the stack, so it will be destructed once it goes out of scope. The new keyword places it on the heap. This means that it will live unil you delete it again, or exit the app. So you have to think about this, because if you don't make sure your object gets del...
72,065,710
72,068,573
Zakat of cows calculation
For every 30 cows, zakat is cow of one years old, and for every 40 cows zakat is female cow of two years old. EXAMPLE: 30-39 cows -> zakat: 1 cow of one years old 40-49 cows -> zakat: 1 female cow of two years old 50-59 cows -> zakat: 1 female cow of two years old 60-69 cows -> zakat: 2 cows of one years old 120-129 co...
Consider a number of cows, N. The maximum number of two-years female cows (V2 for short) is floor(N/40). So, your zakat may have a number of V2 ranging from 0 to floor(N/40), which leaves N-40*V2 cows untithed. These obviously require floor((N-40*V2)/30) V1 to complete zakat. Pseudo-code: N := number of cows MV2 := flo...
72,065,854
72,066,142
How do I fix my current openGL error, my cmakelist may be my issue
I have included the library <GLUT/glut.h> and all my syntax is correct, yet I am receiving this error. Undefined symbols for architecture arm64: "_glBegin", referenced from: triangle(float*, float*, float*) in main.cpp.o "_glClear", referenced from: displayTriangle() in main.cpp.o "_glClearColor", ref...
Please provide more details like your relevant section of CMakeLists.txt for getting more info and getting quicker help from community. Now, coming to the error logs, it seems you are cross-compiling the source files using a arm-based compilers. The error message "ld: symbol(s) not found for architecture arm64" looks t...
72,066,464
72,067,394
How can I implements erase( iterator erase(const_iterator first, const_iterator last)) of vector in c++
https://www.cplusplus.com/reference/vector/vector/erase/ I want to make erase() method of vector in c++ iterator erase(const_iterator position) { theSize--; int index = position - begin(); Object* newObj = new Object[theCapacity]; for (int i = 0, j = 0; j <= index; ++j) ...
You don't need to reallocate the array; use move semantics instead. Even if you use the current implementation, you benefit from moving the values from the old array instead of copying them. Furthermore it's more efficient for erase(const_iterator, const_iterator) to receive its own implementation. Your actual problem ...
72,066,657
72,066,741
Merge two arrays of pointers into a third array of pointers in C++
arr1,arr2 are two arrays of pointers, I have to merge these into arr3. When the program gets arr3[1] (when k=1) the program is closes , I don't get why. Please help. class Node { public: Node* left; T data; Node* right; int height; }; void mergeArrays(Node<T>** arr1,Node<T>** arr2,int len1,int len2)...
You're not copying pointers. You're copying values from one data member of some object to another data member of some object. But the problem is, there is no "there" there to copy to . You allocate a bed of pointers for arr3, but there are no objects behind those pointers so this: (arr3[k++])->data = (arr1[p++])->data;...
72,067,768
72,068,040
C++ vector of custom template class as member
I'm currently coding a program in c++ using a template class: template<typename TYPE> class TemplateClass { private: TYPE t; }; I have another class which acts as manager of my TemplateClass which should store multiple instances of this class in a vector. Different instances should have different types e.g. int, s...
If you know all the types that will be stored in the std::vector at compile time I'd use an std::variant in such a case. // This is used for the visitor pattern. template<class... Ts> struct overload : Ts... { using Ts::operator()...; }; // The below line not needed in C++20... template<class... Ts> overload(Ts...) -> ...
72,068,206
72,068,953
libusb_open returns LIBUSB_ERROR_NOT_SUPPORTED on windows 10
OS: Windows 10 64bit Compiler: MSVC 19 std:c++20 static linking I have below code which just initialize and print some information about the device #include "libusb.h" #include <iostream> int main() { libusb_context* cntx{ nullptr }; int status{ libusb_init(&cntx) }; if (status != LIBUSB_SUCCESS) { std::ce...
libusb can enumerate all USB devices. But it can only open devices that have the WinUSB driver (or libusbK or libusb0) installed. WinUSB is the generic driver to work directly with the USB device and its endpoints, without the need for implementing and providing your own device driver. This is appropriate if the device...
72,068,313
72,074,755
Whenever i use while(cin>>(var)) in my code, the istream gets stuck in error state
The code i am trying to run is given below. Here in line 9 I am trying to take multiple inputs using the while(cin>>n) method. The input I gave is like : 2 4 5 6 45 357 3 (ctrl+z)(ctrl+z) to indicate EOF in windows. Then, even thought the numbers get added into the vector v1, the istream is stuck into error state caus...
the statement cin>>n return the cin object itself, put it inside while does something like while(true){ cin >> n; if(cin){ // equals to if(!cin.fail()) // ... body of while } else break; } so yes, after you leave the loop, cin is in fail state, thus any subsequence operator >> would not success until...
72,068,339
72,068,544
Creating a derived class as a subset of superclass
I have created (for purely eductional value, this is not production code, there are libraries out there, more efficient implementations exist) a templated matrix class. I want to do 2D graphics, so I need a 2D vector. Because of homogenous coordinates this will have three items. Moreover, I want a new constructor, I wa...
Which works, but is this the best way? Is there a better way to achieve what I want? The best way depends on how you intend to use your Point2D. If you really want Point2D and Matrix<3,1> to be the same, a possible approach is to make Point2D a type alias and write a make function to create it: using Point2D = Matrix...
72,068,465
72,068,514
cast from WNDPROC to LONG
static LRESULT CALLBACK wndProcNew(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_DESTROY: PostQuitMessage(0); break; } return DefWindowProc(hwnd, msg, wParam, lParam); } int CALLBACK wWinMain(HINSTANCE hInst,HINSTANCE,PWSTR szcmdLine,int cmdShow){ us...
On 64-bit Microsoft Windows, pointers (including function pointers) have a size of 64 bits, whereas a variable of type long or LONG has a size of 32 bits. Therefore, a variable of that size is unable to represent the value of a pointer. If you want to set 64-bit values, I recommend that you use SetWindowLongPtr instead...
72,068,948
72,069,971
Is std::from_chars supposed to handle uppercase hexadecimal exponents?
On upgrading to Ubuntu 22.04 (amd64), I have noticed that the following code has started to give the result 1.4375 instead of the expected value 1472: #include <charconv> #include <iostream> #include <string_view> int main() { std::string_view src{"1.7P10"}; double value; auto result = std::from_chars(src....
Is std::from_chars supposed to fail with uppercase exponent characters, or is this a bug in g++/libstdc++? This is a bug of libstdc++, submitted 105441. From [charconv.from.chars], emphasis mine from_chars_result from_chars(const char* first, const char* last, double& value, chars_format...
72,069,293
72,077,249
Reverse string with one space
I need to reverse string but to keep only one space between words. EXAMPLE: " na vrh brda vrbaa mrdaa!!! " "!!!aadrm aabrv adrb hrv an" Code: #include <iostream> #include <string> std::string ReverseOneSpace(std::string s) { std::string str = s; int j = 0; for (int i = s.length() - 1; i >= 0; i--) { ...
Another solution is to use what is available in the C++ library: Usage of std::istringstream removes the need to check for spaces. Usage of std::reverse will reverse the string automatically. Putting these together results in the following program: #include <iostream> #include <string> #include <sstream> #include <al...
72,069,476
72,069,565
Disabling possibility of instantiation of base struct
I have a usecase for two different structs (just storage of data) which share some common members, e.g. struct Foo { int i; int j; }; struct Bar { int i; float f; }; The common data could be represented in a base struct but I'd like to disable the possibility of creating an object of the base struct.
If you make the constructor protected, then only derived classes can access it: struct Base { int i; protected: Base() = default; };
72,069,868
72,070,075
C++ decltype evaluate wrong type
I have the function which type the same as minimal argument: #include <iostream> template<typename A, typename B> auto Min(A a, B b) -> decltype(a < b ? a : b) { return a < b ? a : b; } int main() { auto b = Min(5, 2.0f); // float auto a = Min(5, 6.0f); // also float ?! std::cout << typeid(a).name() ...
The conditional operator (?:) can only yield a single type. In your case, int and float share the common type float, so that is the type the expression will yield. If you don't want that, you'll need to move your code from being executed at run time and move it into being executed at compile time. Doing that allows y...
72,069,924
72,069,980
How do I get my linked list to display on one line and not create a new line each time? C++
So I need help on making the program display the linked list in only one line with nothing in between them. I also need to the use _getch(), getch() or getchar() functions not cin or something similar, the current program uses the _getch() function. I'll provide my code, output and desired output. Thank you for the hel...
You could create the string you want to print first using a std::stringstream, then print it on a single line, like this: std::stringstream ss; for (current = head; current; current = current->next) { ss << current->data; } std::cout << "+------------+" << std::endl; std::cout << "|" << std::setw(12) << ss.str() <...
72,070,260
72,073,593
What's the right way to partially initialize a struct?
For a user-defined allocator, the relation between the allocated-units must be constructed at the beginning, while the memory space for elements should be left uninitialized. A simple demo: template <typename T> struct Node { T _item; Node* _prev; Node* _next; }; template <typename T, typename ParentAlloca...
You need to modify Node to make it default constructible, and you don't want to default construct T even if it has a default constructor. So you can replace T _item with: std::aligned_storage<sizeof(T), alignof(T)> _item; Or in C++23 because std::aligned_storage is deprecated: alignas(T) std::byte _item[sizeof(T)]; ...
72,071,206
72,075,784
QTextDocument and selection painting
I am painting a block of text on a widget with QTextDocument::drawContents. My current goal is to intercept mouse events and emulate text selection. It's pretty clear how to handle the mouse, but displaying the result puzzles me a lot. Just before we start: I can not use QLabel and let it handle selection on it's own (...
You can use QTextCursor to change the background of the selected text. You only need to select one character at a time to keep the formatting. Here is an example of highlighting in blue (the color of the text is highlighted in white for contrast): void MainWindow::paintEvent(QPaintEvent *event) { QPainter painter(thi...
72,071,391
72,071,485
How to group data in tuples of tuples into a tuple of vectors
I want to group data of tuples in tuples into a tuple of vectors. Given is a tuple of tuples containing data. There are multiple duplicate types, that's data should be grouped into a vector of each unique type. So far boost::mp11 is the most elegant way I found, to build a type std::tuple<std::vector<T1>, std::tuple<st...
You can use std::apply to expand the elements of merged_tuple, and use std::get to extract the corresponding vector in vector_t according to the type of the element, and fill into the vector through push_back std::apply([&vec](auto... args) { (std::get<std::vector<decltype(args)>>(vec).push_back(args), ...); }, merg...
72,071,397
72,072,531
I Want This Code To Prove If An Integer Is A Palindrome. How Do I do It?
I am sure this code isn't perfect, but I am new to programming and am trying to work out a challenge for checking if a number is a palindrome or not. I tried writing a bool-type function in the code to return 'true' if the number is a palindrome and 'false' otherwise. Anyway, jumping to context, I want this code to pri...
I'm not sure what you're trying to do in isPalindrome. One way to check if a string of size len is palindrome is to compare its i-th and (len-i-1)-th characters for i ranging in [0, len / 2). If they differ at any point the string is not palindrome. Here's how you may do it: bool isPalindrome(std::string const& md) { ...
72,071,571
72,085,313
What is an alternative to the negative lookbehind (that's not implemented) in CTRE?
I'm trying to match a part of a string that surrounds a word inside of it. For example: [This]. I would like to match [This], but only when the character before it is not a backslash, so for example, not this \[This]. for (auto match: ctre::range<R"((((?<!\\))\[[^\]]*\])">(input)) { // you can use match.str() here }...
The regex is the following: (?:^|[^\\])(\[[^\]]*\]) where: (?:^|[^\\]) is a non-capturing group that uses alternation (|) for choosing between ^ (the beginning of the string) or [^\\] (any character that is not a backslash). (\[[^\]]*\]) captures the desired pattern.
72,071,734
72,072,100
Best practice to link modules split into multiple files with gcc/g++
I would like to have a file containing only the declarations in a module and one or more files containing the definitions. According to How to split a module into multiple files (and this awseome cppcon talk: https://youtu.be/nP8QcvPpGeM at 12:04) I should split my files like this: Log.cpp: export module Log; int i =...
Modules are basically orthogonal to the linking process. Each module file is its own translation unit and therefore will produce its own object file. You can combine them into a library (or a single object file), but otherwise, you're going to have to link to all such object file.
72,072,023
72,072,046
A shortcut to compare data on the heap in C++
Consider two arrays of data allocated on the heap: int *A = new int[5]; int *B = new int[5]; // Some code which changes data pointed to by A and B Now I want to compare these two arrays (not the pointers, but the data A and B point at). That is, I want to check out if the elements of the arrays are equal. One might s...
Since you're mentioning memcpy, there's also memcmp. This seems to be what you're after? See also Compare fast two memory regions.
72,072,035
72,072,852
Compiling a cpp file with vscode, in Ubuntu
I'm trying to follow this link on how to get started with c++ and vscode in ubuntu. I have gcc already installed with the latest version. Running sudo apt-get install build-essential gdb gives: Reading package lists... Done Building dependency tree Reading state information... Done build-essential is already the...
Its best to get GCC working in your commandline, then get it working using VS Code tasks. I suggest that you create the most simplistic project structure you can. Use only a project directory, and a single file named main.cpp. Something that looks like this: PROJECT (dir) // path = ./ │ └──> main.cpp ...
72,072,236
72,073,572
Is exists SFINAE technique to check several statement?
In C++17, I want to check some prerequisite before invoke some function using SFINAE, example: class TestClass { public: bool foo() const { return true; } bool bar() { return false; } }; template<typename T> class Checker { public: template<typename Fn, typename = std::enable_if_t<(std::is_same_v<invoke_re...
It seems like what you need is is_invocable_r_v, i.e., we can just determine whether Fn can be invoked with the zero argument or one argument of type const T& to yield a result that is convertible to bool template<typename T> class Checker { public: template<typename Fn, typename = std::enable_if_t< ...
72,072,310
72,097,071
Apache Ignite: Manual Data Colocation
So I understand data can be colocated together by use of an affinity function. My questions is, if it is possible to force data to be placed in a particular node? And then force rebalancing if I need that partition to be moved to another node. This would be useful for a scenario where I have a client that will be using...
You can use a node filter to limit which nodes store data, but you can't easily force data to a specific node. But the good news is that's really a design anti-pattern. You should let Ignite figure it out for you. Part of the reason for that is that you appear to assume that a client connects to a server. That's not th...
72,072,494
72,084,045
When changing build target to release in Visual Studio, thousands of errors appear
I setup a simple Empty Project on Visual Studio 2022. I attached some GLFW / Glad sources to it so that I could do a basic rendering project. I've been editing it for around two days with no issues. It runs fine. I went to build it and noticed the debug version builds the debug console and everything into the EXE, whic...
You can refer to the Document: Set debug and release configurations in Visual Studio. Visual Studio projects have separate release and debug configurations for your program.
72,072,629
72,072,927
lots of OpenGL glDebugOutput Shader Stats / Shader Compiler / Other / notification severity messages with mesa radeon
I have an opengl toy code that I am using to learn ogl and 3d graphics. I am using glDebugMessageCallback and glDebugMessageControl to check for OGL errors and on windows I did not have any messages. I am now testing my code on linux and I am getting a lot of these message: Debug message (1): Shader Stats: SGPRS: 16 VG...
My question is why do i not get these message in windows The debug messages are completely implementation-specific. In the worst case, you could not get any message at all. The verbosity of the different drivers can vary a lot, the mesa open source drivers on Linux are notably on the more verbose end of the spectrum....
72,072,721
72,091,965
AVX divide __m256i packed 32-bit integers by two (no AVX2)
I'm looking for the fastest way to divide an __m256i of packed 32-bit integers by two (aka shift right by one) using AVX. I don't have access to AVX2. As far as I know, my options are: Drop down to SSE2 Something like AVX __m256i integer division for signed 32-bit elements In case I need to go down to SSE2 I'd apprec...
Assuming you know what you’re doing, here’s that function. inline __m256i div2_epi32( __m256i vec ) { // Split the 32-byte vector into 16-byte ones __m128i low = _mm256_castsi256_si128( vec ); __m128i high = _mm256_extractf128_si256( vec, 1 ); // Shift the lanes within each piece; replace with _mm_srli_...
72,072,804
72,075,659
MessageBox has 2 different styles in C++? (Windows)
Not too long ago I found that there are 2 different styles/looks for the standard Windows Message Box. The interesting thing is, even having the exact same program/code for the message box, you might get either style 1 or style 2. As you can clearly see, there are some differences in the style, but the code behind th...
They are different commctrl versions but, as of 2022, there is no point of not using the newer style, nobody would target an older system nowadays. Put this to a cpp: #if defined _WIN64 #pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchit...
72,072,834
72,083,892
Is there a way to use the RtlSetProcessIsCritical function from the Windows API in Python?
I want to use the RtlSetProcessIsCritical function that sets a current process as critical but I really couldn't find a way to use it with Python. Here is the example of it in C++: #include <windows.h> typedef VOID(_stdcall* RtlSetProcessIsCritical) ( IN BOOLEAN NewValue, OUT PBOOLEAN OldValue, IN B...
Try to load ntdll.dll in python. Requires Pywin32 library. import win32process import win32api import ctypes from ctypes import * ntdll = WinDLL("ntdll.dll") ntdll.RtlSetProcessIsCritical(1,0,0)
72,073,110
72,077,222
Missing certain overloaded SFML methods, while others are fine
Im trying to build an application on SFML and decided to build it myself instead of using apt package manager. Im also using cmake but i don't think that matters much for my question: In my file UserInterface.h i have #include <SFML/Graphics.hpp> which worked fine before when i used SFML-dev from apt. Compiler tells th...
Found my answer: The apt SFML package i used earlier must have been an older version of SFML. I found these merged pull requests at their github just a couple of weeks ago. SFML decided that numerical pairs are not needed, as usage of sf::Vector2T is more consistent with the rest of the API. - So i'll just change my co...
72,073,303
72,073,318
cout printing garbage when string is concatenated with array value
Here is my very basic C++ code: #include <iostream> char values[] = {'y'}; int main() { std::cout << "x" + values[0]; } My expected output would just be xy, but instead I am just getting random text/symbols
Perhaps you meant to do: std::cout << "x" << values[0]; Otherwise, you are taking "x" (which decays into a pointer to the 1st element of a const array that holds the characters {'x', '\0'} in memory), and adding 'y' (which has the numeric value 121 when converted to an int) to that pointer. Adding an integer to a poi...
72,073,481
72,073,514
How do I access individual numbers in a string?
Say I have a string that goes: 199 200 208 210 200 207 240 269 260 263 How do I make it so if that string is called s, then s[0] = 199 (rather than 1), s[1] = 200 (rather than 9), s[2] = 208 (rather than 9), etc. I am sorry to keep coming back here, but I really want to resolve this. By the way, this is my c...
You can simply use vector of string for this purpose, std::vector <std::string> numvec; numvec.push_back("199"); numvec.push_back("200"); // accessing the element numvec[0] // equals to 199 You can take input for the vector as: std::string str; for (int i = 0 ; i < 10000 ; ++i){ std::cin >> str; // take i...
72,073,493
72,073,592
Two notify_one() methods do not work on Cygwin
On Cygwin, when dealing with threads in two different functions using two different conditionals, the main thread does not notify one of the waiting threads on the notify_one() call. On visual studio, this method works fine. Does Cygwin not allow a main thread to handle two different unique_locks? For example: mutex m_...
Your code does not assure that freeway.wait(block); happens before freeway.notify_one();. Therefore the thread may start waiting only after you tried to notify it and then wait forever. In fact, the locks guarantee that freeway.notify_one(); happens before freeway.wait(block);, because someWaitingOtherThread will first...
72,073,866
72,073,945
How do I copy a C-style array into a void pointer in C++?
So basically I've recently started coding in C++ instead of C so maybe that's not the C++ way of doing this, but I've got a program where the user passes an array as a function parameter (void foo(void* pass_array_here)) and I want to copy it in a private member of a class, also declared as void* array_private. I'm cop...
As already commented above, using void* is not very useful. If you need an array object, it's recommended in C++ to use either std::array for a fixed size array, or std::vector for dynamic size array. This line: array_private = pass_array_here is simply assigning the pointer, not copying the array content. If you use ...
72,074,190
72,074,572
How to check the element is in the vector using std::lower_bound?
The book, "Effective STL," (by Scott Meyers), suggests that using sorted vectors instead of associative containers is efficient in some conditions. It shows the example of using std::lower_bound on std::vector. But I found some code in it that looks incorrect: vector<Widget> vw; // alternative to set<Widget>...
The !(*i < w) is clearly wrong (or, at the very least, redundant) because, if the std::lower_bound() search does not return vw.end(), then the result of that test must be true. From cppreference: Returns an iterator pointing to the first element in the range [first, last) that is not less than (i.e. greater or equal t...
72,074,771
72,074,903
Do static libraries behave like dynamic libraries in terms of ABI compatibility?
I have learned that you cannot use shared libraries compiled with different compilers together because their ABIs are usually incompatible. The exception is of course if you have a pure C interface, then it is possible. However, I did not find a clear statement about static libraries in this regard, hence this question...
There are several kinds of mismatches which could occur, including: Name mangling. This is a major reason why different compilers may be incompatible. However, many compilers are cross-compatible. Calling conventions. How to pass function arguments, return values, etc. Tends to be tied to the CPU architecture and ...
72,075,289
72,075,318
Copy constructor implicitly called?
I have the following class with both a normal constructor and copy constructor defined. #include <iostream> class Bla { public: Bla() { std::cout << "Normal Constructor Called\n"; } Bla(const Bla& other) { std::cout << "Copy Constructor Called\n"; } }; int main() { Bla a...
Before C++17, the copy operation might be elided but the copy constructor still needs to be present and accessible. This is an optimization: even when it takes place and the copy/move (since C++11) constructor is not called, it still must be present and accessible (as if no optimization happened at all), otherwise the...
72,075,467
72,092,294
python ctypes module how to transfer uint64_t from c++func return to python int,not set restype=c_long_long
i use python ctypes module to cal crc from c++ function it return uint64_t type. In python, i do not set restype(c_long_long), i get a python int value -870013293 , however set restype the value is 14705237936323208851. can you tell me the relation about int_val and long_val.
The default return type for ctypes is c_int which is a 32-bit signed value. If you don't set .restype = c_uint64 for a 64-bit value, the return value is converted incorrectly from C to Python. You can see that the value was truncated to 32 bits if you display it in hexadecimal: >>> hex(-870013293 & 0xFFFFFFFF) # two...
72,075,577
72,075,705
"error: cannot convert 'int*' to 'int**'"
I try to implement a template avl tree while Node includes a pointer to the object : template <class T> class Node { public: Node* left; T* data; Node* right; int height; }; template <class T> class AVLTree{ public: Node<T*>* root; Node<T*>* insert(Node<T*>* p, T* key){ Node<T*>* t; ...
T = int* and you say that you want a T* (that is, an int**) in T* key so when you try to supply an int* instead, it fails. I suggest changing the Node to contain a T instead of a T*: template <class T> class Node { public: Node* left; T data; // not T* Node* right; int height; }; template <cla...
72,075,776
72,075,814
ASSIMP : mNumMeshes is 0
When I was following the LearnOpenGL, a problem come up: I can't figure out why the scene->mRootNode->mNumMeshes is 0. However the scene has been imported rightly (I guess, 'cause scene->mNumMeshes is 7). void Model::loadModel(std::string path) { Assimp::Importer import; const aiScene *scene = import.ReadFile(p...
Meshes are not necessarily attached to the root node. They can also be attached to any of the child nodes (or children's child nodes). Having a scene which contains 7 meshes with scene->mRootNode->mNumMeshes beeing 0 is perfectly valid. But, the recursive loop in your code is wrong. You have to iterate over node->mNumC...