question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
71,948,568
71,948,740
Convert void pointer to a dynamic type
I am trying to convert a void pointer to a dynamic type. For example, I passed double variable to test1 function which I expected the sum function will work. But I got C2664 cannot convert argument error on sum(*reinterpret_cast<myType*>(tmp)). If I using this, it will work. double c= *reinterpret_cast<double*>(tmp); ...
First of all, dynamic type is really only meaningful when you're using inheritance. For example, if you have code like this: class Base {}; class Derived : public Base {}; int main() { Base *b = new Derived; } In this case, b has a static type of Base *, but a dynamic type of Derived * (because it was declared a...
71,949,173
71,949,353
How to print out debug info to terminal when running c++ with CMake?
I am reading a C++ project and want to print out the #ifdef _DEBUG message when running the program at a Linux terminal. For example: #ifdef _DEBUG cout << s1 << endl; #endif Currently, it doesn't print out the debug info above, but only prints out logger info as below: logger_(MY_MODULE_LOG_...
Options are meant to be provided from outside not to be modified in the CMake file. In fact you can't change an option with the option command once it is set in the cache (after the first CMake run). So run your cmake like this: cmake -DDEBUG_OUTPUT=ON .. and you will get your macro defined.
71,949,970
71,977,538
C++ generate new EC_KEY using OpenSSL 1.1.1n
I'm very new to this OpenSSL stuff and trying to learn my way through it. I want to generate an ec key but its keep failing to generate. I'm currently using OpenSSL 1.1.1n and here's a snippet based on understaning of EC_Key through documentation and from other people's example online: EC_KEY* key = EC_KEY_new_by_curve...
Answering myself in case someone is having this same issue. I was able to get around this problem by building OpenSSl with no-shared flag. I'm not sure how that is affecting the lib in getting an entropy but that's the parameter that made the EC_KEY_generate_key() work. Here's my working configuration command: perl Con...
71,950,689
71,950,894
Why is the built-in array subscript can be an lvalue?
Indicate in cppreference that the expression representing the subscript must be a prvalue of unscoped enumeration or integral type. So why can a for loop that traverses a built-in array, which beginners have learned, be compiled. such as: int a[10] = {0}; // as we know ,i is a lvalue for(int i = 0; i < 10; i++) { ...
Indicate in cppreference that the expression representing the subscript must be a prvalue of unscoped enumeration or integral type. // as we know ,i is a lvalue So why can a for loop that traverses a built-in array, which beginners have learned, be compiled. A glvalue expression may be implicitly converted to prvalu...
71,951,159
71,952,159
How do I find the line number and line item number in a text file?
I need to find the line number and position number in the line with the specified character in the text file. I did this, but found the last symbol. I have a task to find the fourth point "." from the end of the text file, how is this possible? Text file: One One Two .... Three .. Three Now I get the following result: ...
In my comment, I sketched the following possible algorithm to solve OPs issue: What you could do: While reading the file you can count the line numbers. Scan the line for one (or multiple) .s. The results can be stored in an array of 4 entries. (You have to manage an index for this.) For each found ., you store the li...
71,951,408
71,955,157
iOS biometrics, how to create LAContext instance from C++?
I'm trying to implement biometric authentication on iOS from a C++ codebase. Here is one example. In order to achieve this, I need to use the LAContext obj-c APIs. However, when I try to initialize the class from C++ I get a pointer/reference error: // Cannot initialize a variable of type 'LAContext *__strong' with an ...
As it turns out, the problem was not with mixing C++ and Obj-C code, but rather with my library being linked via cocoapods and the LocalAuthentication framework being missing. I needed to add: s.frameworks = "LocalAuthentication" to the podspec and creating a LAContext instance works just fine.
71,952,109
72,110,574
How do I translate this simple OpenACC code to SYCL?
I have this code: #pragma acc kernels #pragma acc loop seq for(i=0; i<bands; i++) { mean=0; #pragma acc loop seq for(j=0; j<N; j++) mean+=(image[(i*N)+j]); mean/=N; meanSpect[i]=mean; #pragma acc loop for(j=0; j<N; j++) image[(i*N)+j]=image[(i*N)+j]-mean; } As you can see...
In case anyone sees this, here's the correct answer: First code: for(i=0; i<bands; i++) { mean=0; for(j=0; j<N; j++) mean+=(image[(i*N)+j]); mean/=N; meanSpect[i]=mean; q.submit([&](auto &h) { h.parallel_for(range(N), [=](auto j) { image[(i*N)+j]=image[(i*N)+j]-mean; }); }).wait(); } ...
71,952,784
71,964,329
Using constexpr and string_view in module
Modern C++ offers constexpr and std::string_view as a convenient alternative to string literals. However, I am unable to link to a "constexpr std::string_view" within a module. By contrast, I am able to use string_view (not constexpr) within the module as well as a "constexpr std::string_view" outside of the module. Fu...
I have found a work around solution: adding a getter method. In the module interface unit (my_string.cpp) add: static std::string_view GetStringAtCompilation(); In the module implementation unit (my_string_impl.cpp) add: std::string_view MyString::GetStringAtCompilation(){ return string_at_compilation; } And now ...
71,953,007
71,977,776
C++ How to read/split EPRT command?
I am currently writing a C++ FTP server and I was wondering what would be the best way to read the EPRT command from the client. << DEBUG INFO. >>: the message from the CLIENT reads: 'EPRT |2|::1|58059|\r\n' ^ ^ ^ ...
int ipVersion; char ipv6_str[64], rest[47], port[12]; int scanned_items = sscanf(receive_buffer, "EPRT |%d|%s", &ipVersion, rest); char *first = strchr(rest, '|'); *first = 0; scanned_items = sscanf(rest, "%s", ipv6_str); char *portT = ...
71,953,477
71,954,829
Error: This compiler appears to be too old to be supported by Eigen
I am trying to compile a project that includes the eigen library and I get this error: In file included from /home/--/--/--/Eigen/Core:19, from /home/--/--/--/Eigen/Geometry:11, from /usr/include/rl-0.7.0/rl/math/Transform.h:34, from /home/--/--/--/example.cpp:2: /home/--/--/--/Ei...
As @Lala5th suggested, by changing the C++ standard the problem is solved. I have modified the CMakeLists.txt: From: set(CMAKE_CXX_STANDARD 11) To: set(CMAKE_CXX_STANDARD 17) (It also works with 14)
71,954,053
71,954,517
What does the vertical pipe | mean in the context of c++20 and ranges
There are usages of | which look more like function pipe-lining or chaining rather than a bitwise or, seen in combination with the c++20 ranges. Things like: #include <views> #include <vector> template<typename T> std::vector<T> square_vector(const std::vector<T> &some_vector) { auto result = some_vector | std::vi...
This sort of function chaining has been introduced with C++20 ranges, with the biggest feature allowing lazy evaluation of operation on views (more precisely, viewable ranges). This means the operation transforming the view will only act on it as it is iterated. This semantic allows for the pipeline syntax sugar, putti...
71,954,469
71,962,324
Is safe boost::multi_array_ref returned by a function?
I'm trying to use boost::multi_array_ref to use a block of contiguous data in my code. But I worry about if I use the code like below, the 1d C array won't be confirmed to save: #include <iostream> #include "boost/multi_array.hpp" boost::multi_array_ptr<double, 2> test(int N,int c,int d) { double *data = new double...
double *data = new double[N]; That's a raw pointer and no-one owns the allocation. You're correct that it leads to memory leaks. However, since you want to include ownership, why use multi_array_ref? Live On Compiler Explorer #include <algorithm> #include <numeric> #include "boost/multi_array.hpp" auto test(int c, in...
71,954,780
71,959,655
How to check a type has constexpr constructor
I want my class use another implementation for types don't have constexpr constructor. like this: template <typename A> class foo { public: // if A has constexpr constructor constexpr foo() :_flag(true) { _data._a = A(); } // else constexpr foo() : _flag(false) { _data.x = 0; } ~foo(){} bool ...
I suppose you can use SFINAE together with the power of the comma operator Following your idea, you can rewrite your f() functions as follows template <typename T, int = (T{}, 0)> constexpr bool f (int) { return true; } template <typename> constexpr bool f (long) { return false; } Observe the trick: int = (T{}, 0) fo...
71,955,172
71,955,422
C++ std::for_each printing repeats of indexes
Greetings so I'm making a program for my CS1 class, and in this program, for some odd reason it'll randomly repeatedly print some values. For example, I tried 2 students for the printReportCard function and it printed the first one twice and the second one once. Then I tried 3 students, and it printed each one twice in...
"You need to reset current_card at the beginning of each loop iteration, otherwise it just keeps getting longer and longer. The most obvious way would be to move string current_card = "2022 First Semester Report Card\n\n"; inside the loop at the beginning. You should read Why does std::getline() skip input after a form...
71,955,796
71,956,426
Is increment stackable? I.e x++++; or (x++)++;
When me and my friend were preparing for exam, my friend said that x+++; is the same as x+=3; It is not true but is x++++; same as x+=1; or is (x++)++;? Could I generalize it? I.e. x++++++++++++++; or ((((((x++)++)++)++)++)++)++; is equivalent to x+=7; Maybe it's completely wrong and it is true for ++++++x; or ++(++(++...
The behavior of your program can be understood using the following rules from the standard. From lex.pptoken#3.3: Otherwise, the next preprocessing token is the longest sequence of characters that could constitute a preprocessing token, even if that would cause further lexical analysis to fail, except that a header-na...
71,956,169
71,960,041
Performance problems using QVector<QPair<QPair<QString, QString>, QString>>
I am having serious performance issues using a QVector<QPair<QPair<QString, QString>, QString>> instance. Let's say I have a class EmojiList which does nothing but to hold this vector which is being filled with about 4000 emojis and their respective shortname and category: emojilist.h #include <QVector> class EmojiLis...
I managed to reduce the compile time to 3 seconds by outsourcing the emoji list parsing into the .cpp file: emojilist.h #include <QVector> class EmojiList { public: struct EmojiData { EmojiData(const QString& _code, const QString& _shortname, const QString& _category) : code(_code), ...
71,956,803
71,957,395
normalize image with opencv in c++?
I have a TfLite model that takes a standardized float32 image as an input, the pixel range should convert from the [0~255] to [-1~1] I wrote a demo function but it didn't work. I couldn't set the color value back to the image; How can I set the color back to the "des" image? and Is there a better way to do that? this i...
please do not write for loops. instead: src.convertTo(dst, CV_32F); dst -= 127; dst /= 255; // EDIT
71,956,811
71,956,898
How to get the result of Windows_x64 message without truncation in Qt5?
In Qt5, the function for processing native Windows messages is: bool QWidget::nativeEvent(const QByteArray &eventType, void *message, long *result) and the documentation says, that the third parameter means LRESULT on Windows. In Qt6, the parameter was changed to qintptr: bool QWidget::nativeEvent(const QByteArray &e...
what should be done on Windows x64?" Don't use Qt5. Well, you can use Qt5 for most of your program, but you can't use Qt for processing this particular message. What you can do is subclass the window (see WinAPI function SetWindowSubclass) and write your own window procedure which processes only that single message,...
71,956,916
71,956,983
What does (1) mean when declaring a vector?
What does the ...(1) do? std::vector<std::vector<cv::Point>> tight_contour(1);
tight_contour is a std::vector object containing elements of type std::vector<cv::Point>. The (1) is constructing tight_contour to hold 1 initial default-constructed element.
71,957,099
71,957,295
c++: how to remove surrogate unicode values from string?
how do you remove surrogate values from a std::string in c++? looking for regular expression like this: string pattern = u8"[\uD800-\uDFFF]"; regex regx(pattern); name = regex_replace(name, regx, "_"); how do you do it in a c++ multiplatform project (e.g. cmake).
First off, you can't store UTF-16 surrogates in a std::string (char-based), you would need std::u16string (char16_t-based), or std::wstring (wchar_t-based) on Windows only. Javascript strings are UTF-16 strings. For those string types, you can use either: std::remove_if() + std::basic_string::erase(): #include <strin...
71,957,465
71,957,541
Errors when statically linking libsndfile with vcpkg and running sf_open
So here's a bit of example code: #include<sndfile.h> int main() { SNDFILE* sndfile; SF_INFO sfinfo; sndfile = sf_open("", SFM_READ, &sfinfo); std::cout << "Hello, World!"; } So basically I'm statically linking it from vcpkg, and I followed all the steps like using :x64-windows-static at the end, changing th...
These are functions from the windows api. Just Google them and the msdn help page will tell you which windows library you need to link. For example PathCombineW has this help page: https://learn.microsoft.com/en-us/windows/win32/api/shlwapi/nf-shlwapi-pathcombinew in the Requirements section it tells you that you need ...
71,958,041
71,959,195
Format string based on word match
I ran out of ideas. I need to format this text creating a paragraph for each instance of the word 'Group'. Notice Group1, Group2: ('uniqueName', 'Group', True ), ('Value', 'float', 0, 5, 1 ), ('Value', 'int', 1 ), ('Value', 'bool', true), ('uniqueName', 'Group', True ), ('Value', 'bool', true), .... I need to separate...
Thanks to Aconcagua's comment I found a solution. Just had to check for each Group match and add a new line before copying the line to the file. Then check for everything that was not a group and add it to the file after adding the group: If(Group) { // add a blank line // Copy the group to the file } if(!Group) { ...
71,958,323
71,961,194
How bad it is to lock a mutex in an infinite loop or an update function
std::queue<double> some_q; std::mutex mu_q; /* an update function may be an event observer */ void UpdateFunc() { /* some other processing */ std::lock_guard lock{ mu_q }; while (!some_q.empty()) { const auto& val = some_q.front(); /* update different states according to val */ ...
How bad it is to lock a mutex in an infinite loop or an update function It's pretty bad. Infinite loops actually make your program have undefined behavior unless it does one of the following: terminate make a call to a library I/O function perform an access through a volatile glvalue perform a synchronization operat...
71,958,824
71,960,646
QFileSystemModel doesn't emit fileRenamed signal
I am trying to watch the changes in a directory using QFileSystemModel. Whenever I rename a file in the root path, only the directoryLoaded() signal is emitted. I want the fileRenamed() signal to be emitted so that I know which file is renamed to a new name. Here is my code: model = new QFileSystemModel; model->setRoot...
I am afraid you expect too much from this QFileSystemModel class. It does not and cannot catch if the renaming operation happens outside of the model. I looked up all uses of fileRenamed() signal and it seems that the only place where it is emitted is here: https://code.woboq.org/qt5/qtbase/src/widgets/dialogs/qfilesys...
71,959,452
71,959,817
std::filesystem::path::u8string might not return valid UTF-8?
Consider this code, running on a Linux system (Compiler Explorer link): #include <filesystem> #include <cstdio> int main() { try { const char8_t bad_path[] = {0xf0, u8'a', 0}; // invalid utf-8, 0xf0 expects continuation bytes std::filesystem::path p(bad_path); for (auto c : p.u8string...
The current C++ standard states in fs.path.type.cvt: char8_­t: The encoding is UTF-8. The method of conversion is unspecified. and also If the encoding being converted to has no representation for source characters, the resulting converted characters, if any, are unspecified. So, in a nutshell, anything involving t...
71,960,298
71,960,358
c++ calling int twice
I was writing a code, and accidentally put int before a variable twice, and noticed something different in the end product. int main () { int number = 123456789; int step = 0; while (number>0) { cout << number%10 << endl; number = number/10; step = step+1; cout << "step ...
C++ is block scoped. When you redeclare step inside the while loop (by using int step instead of just step), you "shadow" the step from outside that scope; while the outer step (with value 0) still exists, it cannot be read directly from the inner scope (a pointer/reference to the outer step with a different name could...
71,960,411
71,960,514
Why can I "captureless-capture" an int variable, but not a non-capturing lambda?
The following function is valid (as of C++20): void foo() { constexpr const int b { 123 }; constexpr const auto l1 = [](int a) { return b * a; }; (void) l1; } even though l1 does not capture anything, supposedly, it is still allowed to "captureless-capture" the value of b, as it is a const (it doesn't even...
This has to do with odr-use. First, from [basic.def.odr]/10: A local entity is odr-usable in a scope if: either the local entity is not *this, or an enclosing class or non-lambda function parameter scope exists and, if the innermost such scope is a function parameter scope, it corresponds to a non-static member funct...
71,961,061
71,967,349
DElem<T,N> derives from BElem<T> and DContainer<DElem<T,N>> derives from BContainer<BElem<T>> How to code it?
The question is easy to explain in code. I have coded several template classes that they derive from a unique template class: template<typename T,unsigned N> struct DElem : public BElem<T> {}; My problem arises when I have to code a container of these anterior derived types from a container of the base class: t...
You are out of luck. A container of DElem<T, N> is not substitutable for a container of BElem<T>. If it could, the following nonsense would be allowed. DContainer<T, 10> d10Container; BContainer<T> & bContainer = d10Container; DElem<T, 20> d20; bContainer.push_back(d20); // pushed a d20 into a container of d10 What yo...
71,961,417
71,974,275
How can I achieve native-level optimizations when cross-compiling with Clang?
When cross-compiling using clang and the -target option, targeting the same architecture and hardware as the native system, I've noticed that clang seems to generate worse optimizations than the native-built counter-part for cases where the <sys> in the triple is none. Consider this simple code example: int square(int ...
TL;DR: for the x86 targets, frame-pointers are enabled by default when the OS is unknown. You can manually disable them using -fomit-frame-pointer. For ARM platforms, you certainly need to provide more information so that the backend can deduce the target ABI. Use -emit-llvm so to check which part of Clang/LLVM generat...
71,961,678
71,961,757
How to change the position of a window scrollbar?
How to change the position of the Vertical Scrollbar of a window? I'm referring to the position in xy, for example set it in the middle of the window instead of the edges.
You cannot reposition a scrollbar that is built-in to a window. You will have to disable the native scrollbar (remove the window's WS_HSCROLL/WS_VSCROLL style) and then create a separate ScrollBar control as a child of the window. Then you can position that child wherever you want, using the x/y parameters of CreateW...
71,961,793
71,961,856
Odd behavior from character array
I am trying to write a helper program for Wordle which will display all of the letters which have not been eliminated and the letters which have been confirmed. I've broken the program into functions, and I'm having an issue with the confirmed_letters() function. I have this array declared in the global scope: char* wo...
word[temp_num - 1] = &temp_letter; stores the address of a local variable that will be reused on the next loop iteration and hold whatever new value the user inputs. The old value will be lost, so it'll look like all of the used slots store the same letter. Because they do. Worse, the variable goes out of scope at the ...
71,962,198
71,962,230
I would like to know how this code can be rewritten as an IF statement?
mcPlayerTurn = (mcPlayerTurn == 'W') ? 'B' : 'W'; I am making a game of two players and after one player another player's turn comes.
Per Conditional operator on cppreference.com: The conditional operator expressions have the form E1 ? E2 : E3 The first operand of the conditional operator is evaluated and contextually converted to bool. After both the value evaluation and all side effects of the first operand are completed, if the result was true, t...
71,962,514
71,962,558
Why the destructor of a struct in vector are called every time I iterate over them?
I'm trying to implement a HashMap in LeetCode 706. Design HashMap with C++, it's a simple HashMap with add, remove, get operations: struct Slot { int key; int val; void setValue(int v) { cout << "-set " << v << "fo SV"<<endl; val = v; } ~Slot() { cout << "dtor Slot " << key <...
Your put(), get() and remove() methods all making the same mistake. On this statement: auto bucket = buckets[key % BUCKET_SIZE]; bucket is a copy of the vector located at index key % BUCKET_SIZE, and thus it makes its own copy of all of the Slot objects. You are then looping through, and accessing/modifying, that copi...
71,962,608
71,962,643
Do invalid statements provide valid results
I made this code and it should be invalid #include<iostream> using namespace std; int main() { int a,b; a=3,014; //invalid b=(3,014); //invalid cout<<a<<endl<<b; } Output: 3 12 However both the invalid statements give valid results. But the result should be 3014. It is changed. Why does this happen?
There's nothing "invalid" about either of those. a = 3,014; This parenthesizes as (a = 3) , 014; So a gets assigned the value 3, and then 014 (a number) gets evaluated and discarded. Hence, a = 3. b = (3 , 014); Here, we've explicitly put in parentheses. So the right-hand side is an application of the comma operator...
71,962,952
71,963,361
Can we take the value of iterator which was returned from lower_bound as vector index?
I'm new to vector in C++ and trying to get how it works. First, I have a vector array: vector<int>container; Then I want to get the position of a given number in a vector array. vector<int>::iterator position; position = lower_bound(container.begin(), container.end(), temp); After that, I want to get the value at...
Welcome to stackoverflow :) First of all, we should understand what an iterator is. According to the hackingcpp objects that point to a location may point to a readable memory address / object .. There are a lot of containers in C++ STL, such as vector, list, map and others. A iterator is an abstraction of pointer,...
71,963,029
71,970,071
Emscripten: Can't using emscripten::val in pthread
I'm working on project to attach video from c++. I have success create video element from c++. video = emscripten::val::global("document").call<emscripten::val>("createElement", emscripten::val("video")); video.set("src", emscripten::val("http://jplayer.org/video/webm/Big_Buck_Bunny_Trailer.webm")); video.set("crossO...
This is because emscripten::val is represents an object in JS and the JS state is all thread local. Another way of putting it: Each thread gets is own JS environment, so emscripten::val cannot be shared between threads.
71,963,142
71,965,951
The parameters of the Main function in C++
When I try to compile this code, an error appears : #include<iostream> using namespace std; int main() { char* p = "Hello"; return 0; } error C2440: 'initializing': cannot convert from 'const char [6]' to 'char *' This error is fixed when I add the word const in the declaration of p. This code compiles and ...
Let's see what is happening in your example on case by case basis: Case 1 Here we consider the statement: char* p = "Hello"; On the right hand side of the above statement, we've the string literal "Hello" which is of type const char[6]. There are two ways to understand why the above statement didn't work. In some con...
71,963,214
71,966,692
C++ reordering Singly Linked List
Hi I'm trying to write a code for singly linked list that reorders the nodes so that: L1->L2->L3->...->Ln to L1->Ln->L2->Ln-1->L3->Ln-2... So I tried to do this by finding the node at the end of the list and setting that node as the next of current node and then finishing the loop by setting the current node as the...
I have modified your code to show a correct answer: #include <iostream> struct ListNode { int val; ListNode* next; ListNode(): val( 0 ), next( nullptr ) {} ListNode( int x ): val( x ), next( nullptr ) {} ListNode( int x, ListNode* next ): val( x ), next( next ) {} }; void printlist( ListNode* head ) { whi...
71,963,600
71,997,121
Migrate a "zmq_send" command to Python
I have a c function that publish data to a c++ subscriber, now I want to migrate this c function to Python: void setup_msg_publish() { int r; zmqcontext = zmq_ctx_new(); datasocket = zmq_socket(zmqcontext, ZMQ_PUB); r = zmq_bind(datasocket, "tcp://*:44000"); if (r == -1) { printf(zmq_strerro...
The solution was found after testing to go from C++ -> Python thank you J_H for the idea. Instead of using a namedtuple a packed struct was used. import zmq import struct def send_zmq(): struct_format = 'Idd' msg_type = 0 x = 1.0 y = 1.0 msg = struct.pack(struct_format, msg_type, x, y) context =...
71,963,867
71,964,521
matplotlib-cpp connecting first and last point in the data set
I was able to link matplotlib-cpp to visual studio. When I set the data and plot it everything works fine except first point and last point gets connected. I know that the first point and last point is not the same. My code #include <iostream> #include <vector> #include <cstdio> #include "matplotlibcpp.h" namespace p...
These two lines: int num = 139; std::vector<double> xval(num + 1), yval(num + 1); create vectors xval and yval of 140 double elements initialized to 0. You only load 139 points from your dataset and the first point in the dataset is (0,0); so your first (0-th) and last (139-th) points are indeed equal. You may try: i...
71,964,315
71,964,358
Unexpected iterator behavior as a member variable
I'm having trouble with iterators: class Foo { private: std::istream_iterator<char> it_; public: Foo(std::string filepath) { std::ifstream file(filepath); it_ = std::istream_iterator<char>(file); } char Next() { char c = *it_; it_++; return c; } bool HasNext() { return it_ != std::i...
Here: Foo(std::string filepath) { std::ifstream file(filepath); it_ = std::istream_iterator<char>(file); } You store an iterator to file. Once this constructor returns files destructor is called and all iterators to the ifstream become invalid. It is similar to using a pointer to a no longer existing object. Y...
71,964,541
71,965,024
Mutex does not work as I expect. What is my mistake?
I was trying to figure out the data race theme, and I made this code. Here we work with the shared element wnd. I thought that by putting lock in the while loop, I would prohibit the th1 thread from working with wnd, but this did not happen and I see an unobstructed output of the th1 thread. #include <iostream> #includ...
You are not using the mutex and specially std::unique_lock properly. #include <iostream> #include <thread> #include <mutex> #include <chrono> int main() { bool wnd = true; std::mutex mutex; std::thread th1{[&]() { for (int i = 0; i<10000; ++i) { std::unique_lock<std::mutex> lock(mut...
71,965,085
71,966,177
Why does capturing stateless lambdas sometimes results in increased size?
Given a chain of lambdas where each one captures the previous one by value: auto l1 = [](int a, int b) { std::cout << a << ' ' << b << '\n'; }; auto l2 = [=](int a, int b) { std::cout << a << '-' << b << '\n'; l1(a, b); }; auto l3 = [=](int a, int b) { std::cout << a << '#' << b << '\n'; l2(a, b); }; auto l4 = [=](int ...
What's happening in the first example is not what you think it is. Let's say l1 has type L1, l2 L2 , etc. These are the members of those types: struct L1 { // empty; }; sizeof(L1) == 1 struct L2 { L1 l1; }; sizeof(L2) == sizeof(L1) // 1 struct L3 { L2 l2; }; sizeof(L3) == sizeof(L2) // 1 struct L4 { ...
71,965,838
71,966,231
no suitable user-defined conversion, but the convertion is specified
I am coding a vector class with iterators for a school exercice. I am getting the following error and I don't know how to go about it: 'no suitable user-defined conversion from "vectorIterator" to "vectorIterator<const int>" exists' This is the code I am trying to execute: vector<int> v; v.push_back(1); v.push_back(2);...
Since vectorIterator is a template class, which means that vectorIterator<int> and vectorIterator<const int> are two different types, they can not be converted to each other. You need to add a conversion constructor for vectorIterator<const int> that accepts vectorIterator<int>, using template should be enough (some co...
71,966,191
71,966,366
Is it valid to use const char*[] as the type of second parameter of main
I am learning C++ and learnt that the following given declarations are equivalent: int main (int argc, char *argv[]); //first declaration int main (int argc, char **argv); //RE-DECLARATION. Equivalent to the above declaration My question is that if i change the declaration to say: //note the added const int main (int...
Adding const changes the type of the function. It is not declaration of the same function. Whether that is valid for main in particular, depends on language implementation: [basic.start.main] An implementation shall not predefine the main function. Its type shall have C++ language linkage and it shall have a declared ...
71,967,571
72,028,202
SDL driver fails when starting debug session on remote linux
On Win10, I have a visual studio c++ project for linux that uses the SDL2 driver. The target machine is a VirtualBox - Ubuntu 18.04. I configured Visual studio to compile remotely on the target system, which works fine. Running the output file from console on the remote machine shows that SDL uses the XServer: SDL_GetC...
In Project Settings: Configuration Properties -> Debugging -> Pre-Launch Command -> export DISPLAY=:0
71,967,878
71,967,894
Slicing string character correctly in C++
I'd like to count number 1 in my input, for example,111 (1+1+1) must return 3and 101must return 2 (1+1) To achieve this,I developed sample code as follows. #include <iostream> using namespace std; int main(){ string S; cout<<"input number"; cin>>S; cout<<"S[0]:"<<S[0]<<endl; cout<<"S[1]:"<<S[1]<<en...
It's because S[0] is a char. You are adding the character values of these digits, rather than the numerical value. In ASCII, numerical digits start at value 48. In other words, each of your 3 values are exactly 48 too big. So instead of doing 1+1+1, you're doing 49+49+49. The simplest way to convert from character valu...
71,967,949
71,969,771
How can we change behaviour of c++ method depending on initialization parameter?
In python I can write something like class C: def __init__(self, mode): if mode == 0: self.f = self.f0 elif mode == 1: self.f = self.f2 (...) else: raise KeyError def f0(self, a1, a2): <do stuff> def f1(self, a1, a2): <do ...
Thanks to @AlanBirtles and @Yksisarvinen ! The working solution I ended up with was stuff.h: class C{ C(int mode); const int mode; double f(int i, int j, int k); using FunctionType = double(C::*)(int, int, int); double f0(int i, int j, int k); double f1(int i, int j, int k); FunctionType ...
71,968,902
71,968,958
Forwarding reference and argument deduction
I'm trying to understand perfect forwarding a bit deeply and faced a question I can't figure out myself. Suppose this code: void fun(int& i) { std::cout << "int&" << std::endl; } void fun(int&& i) { std::cout << "int&&" << std::endl; } template <typename T> void wrapper(T&& i) { fun(i); } int main() { wrap...
Types and value categories are different things. Each C++ expression (an operator with its operands, a literal, a variable name, etc.) is characterized by two independent properties: a type and a value category. i, the name of the variable, is an lvalue expression, even the variable's type is rvalue-reference. The f...
71,968,955
71,969,908
Publisher/Subscriber on the same node C++ ROS
I aim to create a Subscriber and a Publisher in the same node! I want to access a part of the message available on a topic of a rosbag. The message of the thread is as follows: Type: radar_msgs/RadarDetectionArray std_msgs/Header header uint32 seq time stamp string frame_id radar_msgs/RadarDetection[] detections...
Here: chatter_pub.publish(pub_data); You are publishing a double in a topic that expect radar_msgs::RadarDetection. The error is telling you that it cannot call __getMD5Sum on a double, which is obviously accurate. If you intend to publish a double you MUST create a publisher specific for that type: ros::Publisher cha...
71,969,019
71,970,139
OMP parallel for is not dividing iterations
I am trying to do distributed search using omp.h. I am creating 4 threads. Thread with id 0 does not perform the search instead it overseas which thread has found the number in array. Below is my code: int arr[15]; //This array is randomly populated int process=0,i=0,size=15; bool found=false; #pragma omp parallel ...
Your problem is that you have a parallel inside a parallel. That means that each thread from the first parallel region makes a new team. That is called nested parallelism and it is allowed, but by default it's turned off. So each thread creates a team of 1 thread, which then executes its part of the for loop, which is ...
71,969,045
71,969,117
passing 2 arrays of different sizes using templates in C++
I have the following code template <size_t size_x, size_t size_y> void product(int (&arr)[size_x][size_y],int (&arr1)[size_x][size_y]) { for (int i=0;i<size_x;i++) for (int j=0;j<size_y;j++) { cout << "The size of a1[][] is" << arr[i][j] << endl; } for (int i=0;i<size_x;i++) for (int j=0;j<size...
How can I pass an array of 22 and 32 array to a function? This can be done simply by providing extra template parameters template <size_t size_x1, size_t size_y1, size_t size_x2, size_t size_y2> void product(int (&arr)[size_x1][size_y1],int (&arr1)[size_x2][size_y2]); Demo
71,969,281
71,972,102
__declspec(dllexport) and __declspec(dllimport) in C++
I often see __declspec(dllexport) / __declspec(dllimport) instructions on Windows, and __attribute__((visibility("default"))) on Linux with functions, but I don't know why. Could you explain to me, why do I need to use theses instructions for shared libraries?
The Windows-exclusive __declspec(dllexport) is used when you need to call a function from a Dll (by exporting it) , that can be accessed from an application. Example This is a dll called "fun.dll" : // Dll.h : #include <windows.h> extern "C" { __declspec(dllexport) int fun(int a); // Function "fun" is the functi...
71,969,411
71,999,093
Python bytestream to image
I'm trying to achieve the same thing as this question, but with color image : How to I transfer an image(opencv Matrix/numpy array) from c++ publisher to python sender via ZeroMQ? Here is my input image This is what my code display C++ side : cv::Mat frame = cv::imread("/home/victor/Images/Zoom.png"); int height = fra...
Managed to make it work : changed python side into image2 = Image.frombytes('RGB', (height,width), image_bytes) self.currentFrame = ImageQt(image2) and displaying with qimg = QImage(self._socket.currentFrame) pixmap = QtGui.QPixmap.fromImage(qimg) self.imageHolder.setPixmap(pixmap) self.imageHolder.show() ...
71,969,416
72,039,026
C++ member variables are not initialized when using a debug version static library
Environment: Windows10, cpp17, visual studio 2019, debug version static library Recently I tried to use Cesium-Native to read 3DTiles files in my project, but there was a confusing problem that some member variables are not initialized correctly. As following codes show, Tileset() use initializer list to initialize i...
The problem solved by carefully checking all setting in running correctly original project and my project. And try to clean Visual Studio Cache and rebuild project and lib may be helpful for the problem. At first I used the different library version for inlucde and lib files, then I found that, I change the same versio...
71,969,651
71,970,331
Why does a defaulted default constructor depend on whether it is declared inside or outside of class?
In the following example, struct A does not have default constructor. So both struct B and struct C inherited from it cannot get compiler-generated default constructor: struct A { A(int) {} }; struct B : A { B() = default; //#1 }; struct C : A { C(); }; C::C() = default; //#2 #1. In struct B, defaulted ...
Note that if you actually try and instantiate B then you'll also get the error that B::B() is deleted: https://gcc.godbolt.org/z/jdKzv7zvd The reason for the difference is probably that when you declare the C constructor, the users of C (assuming the definition is in another translation unit) have no way of knowing tha...
71,969,830
71,970,563
arrange line in txt file in ASCII order using array and display them
#include <stdio.h> #include <string.h> #include <fstream> #include <iostream> using namespace std; int main() { ifstream infile; // ifstream is reading file infile.open("read.txt"); // read.txt is the file we need to read std::cout << infile; string str; if (infile.is_open()) { w...
Your code does not work, because: The line std::cout << infile; is wrong. If you want to print the result of istream::operator bool() in order to determine whether the file was successfully opened, then you should write std::cout << infile.operator bool(); or std::cout << static_cast<bool>(infile); instead. However, i...
71,970,051
71,970,369
Why is std::variant required to become valueless_by_exception in move assignment?
I have seen the following notes on cppreference regarding to the valueless_by_exception method: A variant may become valueless in the following situations: (guaranteed) an exception is thrown during the move initialization of the contained value during move assignment (optionally) an exception is thrown during the co...
Note that Cppreference is talking about a different situation. When it says copy/move assignment, it's talking about copy/move assignment from a variant, not from a T. Assignment from T is dealt with in the next statement: (optionally) an exception is thrown when initializing the contained value during a type-changing...
71,970,390
71,970,724
Are there difference between fn(); and fn<T>(); in template class member function of C++
template <class T> class Stack { public: Stack(); }; template <class T> class Stack { public: Stack<T>(); } By the way, what's the meaning of <T>?
From injected-class name in class template's documentation: Otherwise, it is treated as a type-name, and is equivalent to the template-name followed by the template-parameters of the class template enclosed in <>. This means that both the given snippets in your example are equivalent(Source). In the 1st snippet, the ...
71,970,435
71,970,740
How do I use the __cpp_lib_* feature test macros?
I wanted to use the feature test macros to check if std::filesystem was available, but __cpp_lib_filesystem isn't defined even when I know std::filesystem is present. For example, the following test program: #include <iostream> int main () { std::cout << "__cpp_lib_filesystem: " #ifdef __cpp_lib_filesystem ...
There are two ways to use the __cpp_lib_XXX macros: Actually include the corresponding header: https://godbolt.org/z/xo68acnrz And the given library also need to support such feature with the given C++ version e.g., __cpp_lib_constexpr_vector will not be defined under C++17 even if <vector> was included. Uses C+...
71,970,568
71,970,721
Why can't ranges be used if in a function?
I'm trying to get a range like python like below: #include <iostream> #include <ranges> auto Range(double start, double end, double step) { if (start <= end) { auto step_fun = [=](auto x) { return x * step + start; }; auto end_pred = [=](auto x) { return x <= end; }; auto range = ...
A function must have one return type, auto doesn't change that. Your two returns have different, incompatible types, because each lambda expression has a unique type. The error message rather buried it: blah blah Range::<lambda_3>,Range::<lambda_4> vs blah blah Range::<lambda_1>,Range::<lambda_2> You can do some arithm...
71,970,806
71,970,807
Is there an equivalent of torch.distributions.Normal in LibTorch, the C++ API for PyTorch?
I am implementing a policy gradient algorithm with stochastic policies and since "ancillary" non-PyTorch operations are slow in Python, I want to implement the algorithm in C++. Is there a way to implement a normal distribution in the PyTorch C++ API?
The Python implementation actually calls the C++ back-end in the at:: namespace (CPU, CUDA, where I found this). Until the PyTorch team and/or contributors implement a front-end in LibTorch, you can work around it with something like this (I only implemented rsample() and log_prob() because it's what I need for this us...
71,971,092
71,971,236
Infer type of non-type template argument
I'm not great at template metaprogramming, so apologies if this is a dumb question. I have a type like template<int n> struct S { typedef decltype(n) type_of_n; // ... }; and I'd like to write functions that look something like template< typename T, typename T::type_of_n n, typename = std::enable_if_t<std:...
If you are looking to only accepts S and want to also deduce the value of n, then you can since c++17 use auto to deduce the type of a non-type template parameter. template<auto n> void f(const S<n> &) { /* ... */ } You can also make it more generic and accept any type with a single non-type parameter by using a templ...
71,971,104
71,971,792
How can I install the filesystem C++ library with minGW?
For a new project i need use filesystem library but when I try to include it, my compilation fail cause it can't find the library. I'm compiling on Windows with gcc installed via minGW and his version should be 6.3. I know for sure that from gcc 8+ this library should be included in the standard one. I' ve also tried t...
The C++ filesystem library was introduced in C++17, but your compiler might be configured to use an earlier version of the language by default. Try using the -std=c++17 option.
71,971,138
71,971,302
Call derived class appropriately
I have a class order and two derived classes: single_order and repeated_order. struct order{ string desc; }; struct single_order : public order{ datetime dt; }; struct repeated_order : public order{ datetime dt1; datetime dt2; }; I have a list<order*> ll that can contain single_order and repeated_order and two metho...
You knew to tag polymorphism, but you seem to be struggling with the concept. Here's some code: #include <iostream> #include <memory> #include <vector> class Base { public: Base() = default; virtual ~Base() = default; virtual void do_foo() = 0; }; class Bar : public Base { public: Bar() = default; void do...
71,971,345
71,972,541
SQLite: Reading a blob from a table that has no rowid
I'm using the C SQLite library. I need to obtain the value of a blob from a row. The row is in a table that does not have any row id. This causes sqlite3_blob_open to return an error - that rowid is not present in the table. Software like DB Browser for SQLite is able to query the value of these blobs, so there must be...
The answer is to use sqlite3_step() in conjunction with sqlite3_column_blob()
71,971,528
71,971,921
Pass a pointer to a file buffer to a class, expecting to read from file inside a class
I want to learn how to search in the file by passing the pointer of the stream to a class. I can successfully get the first character from the file using std::fstream and std::filebuf* char symbol; std::fstream by_fstream; by_fstream.open("First_test_input.txt"); std::filebuf* input_buffer = by_fstream.rdbuf(); symbol...
You are going about this all wrong. First off, you should pass around (a reference to) the stream itself, not its internal buffer. Use std::istream methods like read() or get() or operator>> to read from the stream, let it handle it own buffer for you. Secondly, you are trying to make a 2nd completely separate object ...
71,971,636
71,979,639
How to create QT Login Page bedore Mainwindow?
My Qt windows application is ready, but when the application opens, I want the login dialog to be opened, how can I do this? I'm new to Qt and C++. It would be great if it was descriptive.
You have many ways to achieve that... QDialog is a nice way. Here is a short sample using QInputDialog. One solution could be to add this code in your main.cpp file, and to load the mainwindow only if the credentials are ok. #include "gmainwindow.h" #include <QApplication> #include <QInputDialog> int main(int argc, c...
71,971,649
71,971,723
Template virtual method for each type
If I have a template as such: template <typename ... TYPES> class Visitor { public: //virtual void visit(...) {} }; Is there a way I can have C++ generate virtual methods "for each" type in the list? For example, conceptually, I would like class A; class B; class C; class MyVisitor : public Visitor<A,B,C>; To ha...
You could add a base class template for Visitor and for each type in TYPES that defines a visit function for the type provided and then you would inherit from those base classes. That would look like template <typename T> class VisitorBase { public: virtual void visit(const T&) { /* some code */ } }; template <ty...
71,972,000
71,981,884
Is having a declaration Stack<T>(); for the default ctor valid inside a class template
I saw this answer to a question on SO related to the declaration for a default constructor of a class template that said that the following code is not valid C++ due to CWG1435: template <class T> class Stack { public: Stack<T>(); //IS THIS VALID? }; While another answer said that the above example is valid C++. T...
The shown snippet is valid for Pre-C++20 but not valid from C++20 & onwards as explained below. Pre-C++20 From class.ctor#1.2: 1 -- Constructors do not have names. In a declaration of a constructor, the declarator is a function declarator of the form: ptr-declarator ( parameter-declaration-clause ) noexcept-specifier...
71,972,269
72,001,860
How to append to CXXFLAGS in Makefile without editing Makefile?
I'm writing a build script for a Qt application. The script first calls qmake on the .pro file and then runs make CXXFLAGS=-DSWVERSION=xxxx. The problem with this is that it overwrites the CXXFLAGS already defined in the Makefile. Currently, the only method I know to solve this problem is to edit the Makefile and chang...
For anyone reading this in the future, the solution I found was to call qmake <project file> DEFINES+="SWVERSION=xxxx". Hope someone finds this helpful.
71,972,492
71,972,833
C++ placement new to create global objects with defined construction order - Is this usage correct?
I am using the Arduino framework. To avoid issues with dynamic memory (heap-underflow as well as stack-overflow), Arduino works widely with global objects. I think that is good practice and I want to continue working with this pattern. At the same time, I want to use dependency injection for those global objects, i.e. ...
The warning that you're seeing isn't related to alignment, but instead type punning. Type punning is referring to the same memory location with two differently typed pointers (long* and T*). From the c++ language reference there are only a few special types where the compiler can't issue a warning (char is one of those...
71,973,148
71,973,478
Why do I get the right output but it also displays the if else output for program 2 and 3
This is a program for admission and there are certain conditions for each program //The front cout<<"Welcome to admission system"<<"\n"; cout<<"---------------------------"<<"\n"; cout<<"Admission open for year 2022"<<"\n"; cout<<"Press 1 for BSc Electrical Engineering Department"<<"\n"; cout<<"Press 2 for BSc Mechanic...
The set of if else statements is incorrect. For example if you entered a value of the qualification not equal to 12 then all three else statements will be executed because the condition qualification!=12 evaluates to true in all three else statements. You need to write either //Program 1 if (pg==1 && marks>=60 && quali...
71,973,876
71,973,938
How to get a subset of map from another map based on a list of keys? C++
I have an old map sample: map<string, int> map_ = {"A": 1, "B": 2, "C": 3, "D": 4, "E": 5} and a list of keys: vector<string> list_ = {"B", "D", "E"} I want to get a new map from the old one based on the key list: map<string, int> mapNew_ = {"B": 2, "D": 4, "E": 5} Is there any smart way to do this?
You can do this with a simple ranged based for loop. That would look like map<string, int> mapNew_; for (const auto& e : list_) mapNew_[e] = map_[e]; If list_ could contain elements that are not in the map, then you would need to add a check for that like map<string, int> mapNew_; for (const auto& e : list_) ...
71,974,052
71,974,175
C++ creating an array pointing to different arrays
The inputs to this program are as follows: 2 2 3 1 5 4 5 1 2 8 9 3 0 1 1 3 I would like n to be an array that points to other integer arrays. So, n should essentially be {{1, 5, 4}, {1, 2, 8, 9, 3}}. If I wanted to access the 0th array and the 1st index, the value should return 5, and if I were to access the 1st array...
cin >> n_l >> q_l; // assigns values to the variables n_l and q_l int *n[n_l]; This isn't allowed in C++. The size of an array variable must be compile time constant. You can create dynamic arrays. Most convenient way is to use std::vector class template from the standard library. The issue with your pointers is tha...
71,974,122
71,974,379
How to write a type trait that checks if tuple types are compatible with function arguments
I am trying to write a type trait that checks whether the types stored in a tuple are compatible with the arguments of a given callable. Currently, I have 'almost working' code, shown below. However, static assert fails in the last statement with a callable that expects reference parameters (e.g. [](int&, std::string&)...
You may want to modify your trait slightly: template<typename Func, template<typename...> class Tuple, typename... Args> struct is_callable_with_tuple<Func, Tuple<Args...>>: std::is_invocable<Func, Args&...> {}; // <--- note & Or not, depending on how exactly you plan to use it. If your tuple ...
71,974,453
71,974,485
Visual Studio Express 2017 Output not displaying for stroke text function
I've been trying to run this program in visual studio express 2017. Using opengl. I found the rendering code and stroke code in a pdf and was trying it out but first it showed many errors, once taken care of I compiled the program. Although the run was without any errors the output screen remains blank. #include "stdaf...
Matrix mode is switched to GL_PROJECTION in myInit but never switched back. Therefore the glLoadIdentity() instruction in render will override the projection matrix. You have to switch the matrix mode to GL_MODELVIEW before glLoadIdentity(): void render() { glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_MODELVIE...
71,974,618
71,976,462
Why are copy-capturing lambdas not default DefaultConstructible in c++20
C++20 introduces DefaultConstructible lambdas. However, cppreference.com states that this is only for stateless lambdas: If no captures are specified, the closure type has a defaulted default constructor. Otherwise, it has no default constructor (this includes the case when there is a capture-default, even if it does ...
There are two reasons not to do it: conceptual and safety. Despite the desires of some C++ programmers, lambdas are not meant to be a short syntax for a struct with an overloaded operator(). That is what C++ lambdas are made of, but that's not what lambdas are. Conceptually, a C++ lambda is supposed to be a C++ approxi...
71,974,667
71,975,399
Efficient Perpetual Numlock Keystate Check
I bought a really nice keyboard (logitech G915) that for whatever inane reason doesn't have a numlock indicator. Thus, I'm using Logitech's lighting SDK to make the functionality myself using the key's rgb backlight. I have an extremely simple console proof of concept that works: while (true) { if (GetK...
At app startup, use GetAsyncKeyState() instead of GetKeyState() to get the key's current state and update the light accordingly. Then, use SetWindowsHookEx() to install a global WH_KEYBOARD_LL hook to detect whenever the key is pressed afterwards. On each callback event, use the state information provided by the hook, ...
71,975,120
71,977,930
Generic set insert function int
I have a little problem with the next task. The insert function should also work for the int type but unfortunately it doesn't work. What might be the problem? Some example for the insert function call: Set<int, 4> s0; s0.insert(2); This is an four-elemet array and the firs element is 2. template <class T, size_t n = 1...
This is a maybe somehow subtle out of bounds bug. Cool. In this while loop while((adat[i] != 0)||(i != n)) i++; you will go out of bounds, because the last element is "(n-1)" and not "n". And you will always go out of bounds, because of the "or" in the condition. The loop will always run at least until "i==n", beca...
71,975,555
71,990,268
C++ Event Dispatcher - callback casting problem
I'm venturing into creating an EventDispatcher using C++ 17 in Visual Studio 2022. Basically I store a string (id) to identify the event and a callback (lambda, function or method of a class) in a vector through the RegisterEvent() method. Then I need to call the DispatchEvent() method passing the event as a parameter....
This question is probably on the edge of what people would normally close, but MSVC is making your life harder by giving a really useless error message here. (You might want to try upgrading your compiler; recent MSVC on godbolt.org give much more helpful messages.) The problem is with dispatcher.RegisterEvent<CustomE...
71,975,610
71,975,649
Vector of vector with unknown size input in c++
I need to input elements of vector of vector. Size of vectors is not known. Row input ends with * character, as well as vector input. EXAMPLE 2 5 1 3 4 * 9 8 9 * 3 3 2 3 * 4 5 2 1 1 3 2 * * Code: #include <iostream> #include <vector> int main() { std::vector < std::vector < int >> a; int x; int i = 0, j = 0; f...
There are two problems with your code: you are indexing into each vector without adding any values to it first, which is undefined behavior. a[i][j] = x; does not make the vectors grow in size. Use vector::push_back() instead. You are not handling the input of * correctly. x is an int, so when std::cin >> x fails t...
71,975,668
71,975,690
How to append a string at the end of string?
#include <iostream> #include <string> #include <cstdlib> using namespace std; class String { private: char* s; int size; public: String() { s = NULL; size = 0; } String(const char* str) { size = strlen(str); s = new char[size]; for (int i = 0; i < s...
Both of your operator+ implementations are wrong. You are modifying the String object that is being added to, and then returning a reference to that object. You need to instead return a new String object that is the concatenation of the added-to and added-from String objects, without modifying the added-to String at a...
71,975,790
71,975,896
Why can an 8-bit string literal contain multibyte characters while a vector of char cannot?
I am trying to figure out why can an 8-bit char data type contain all these weird characters since they are not part of the first 256 characters table. #include <iostream> int main() { char chars[] = " 必 西 ♠ ♬ ♭ ♮ ♯"; std::cout << "sizeof(char): " << sizeof(char) << " byte" << std::endl; std::co...
An 8-bit char can only hold 256 values max. But Unicode has hundreds of thousands of characters. They obviously can't fit into a single char. So, they have to be encoded in such a way that they can fit into multiple chars. Your editor/compiler is likely storing your example string in UTF-8 encoding. Non-ASCII chara...
71,975,930
71,977,358
Limit compilation flags usage to certain files only
I'm trying to introduce -Werror flag to rather big legacy project. As expected, it breaks the compilation completely. Therefore I've decided to introduce it gradually, and for the new code first of all. My original approach was to compile new features as separate static targets and link them to the project, which works...
I don't know about any compiler flags that allow you to apply flags to only some of the files included, so cmake cannot do better for you. Therefore pragmas are the way to go. Basically what you effectively want in your cpp files is something like this: #pragma GCC diagnostic push #pragma GCC diagnostic error "-Wall" ...
71,976,361
71,982,814
How to get a generalized Swap-function?
Using the example for std::swap on cppreference I tried the following SWAP-template: #include <algorithm> #include <iostream> namespace Ns { class A { int id{}; friend void swap(A& lhs, A& rhs) { std::cout << "swap(" << lhs << ", " << rhs << ")\n"; std::swap(lhs.id, rhs.id); } f...
There are 2 problems. Please first read the definition of 'std::swap' here. You will read the requirements for the type. You are using exceptions in your swap function. Remove that. From the description, you can see that your type must be Type requirements T must meet the requirements of MoveAssignable and MoveCons...
71,976,458
71,977,034
The .ccp and .h / header files output error 'this declaration has no storage class or type specifier' with implementation of SendInput function
So my problem is I keep getting error "this declaration has no storage class or type specifier" "the size of an array must be greater than zero" " expected a ';' " I don't know what's wrong. I tried to look online and find no specific solution to my problem other than generic solutions like defining the class for the t...
As it currently is, your header file has "freestanding" execution code. This is not possible in C++ - C++ is not a scripting language where you can execute code in arbitrary files. Every executable code needs to be in a function. So you better declare a function prototype in your Buttons.h with the necessary data types...
71,976,481
71,976,570
why list doesn't work similar like array in c++
Why my code is not printing the value 2 in l[0]? #include <bits/stdc++.h> using namespace std; list<int> l; int main() { l.push_back(2); cout<<l[0]; return 0; }
In C++, List containers are implemented as doubly-linked lists. They excel in performance when inserting and moving elements around, but they must be traversed. They lack direct access to the elements by their position. What you probably would rather have is a vector. Vectors allow for direct access: vector<int> l; int...
71,976,700
71,976,728
Counting elements in an array greater than next element C++
Why is it giving wrong count In this question we have to find out how many elements are greater than the next element of an array #include using namespace std; int main() { //number of testcases int t; cin>>t; while(t--){ //taking number of elements in an array int n,count; ...
There are several problems with your code: Problem 1 You're going out of bounds of the array a which leads to undefined behavior, when you wrote cin >> a[n]; //undefined behavior Note that indexing of arrays starts from 0 instead of 1 in C++. Problem 2 In standard C++, the size of an array must be a compile-time con...
71,976,747
71,976,893
data structures access by index
-Vectors Linked Lists Maps Stack It is little confusing, when it says access, I did not quite understand what it meant. Started thinking about data structures , I know that arrays are indexed. Also know that vector can be accessed by index, but access by index? I think that got me confused
From memory, in c++: std::vector, std::string, std::array, std::deque, std::bitset, std::valarray, std::span (Not a container) So the answer is "Vectors"-ish.
71,976,905
71,976,948
Vector only contains one element
I'm making a Text Adventure in C++ as an attempt to learn the language. The player interacts using commands like look or travel north. So far I've got code that converts the text to lowercase and then splits it into a Vector. This works fine for one word commands, but when I go to implement longer commands I find that ...
Fun fact, when you do this: std::cin >> input; It reads characters up until the next whitespace character, and puts those into the string. That means input will only contain the first word you entered. Want to get the whole line? Well, clearly, you already know how to do that, just call std::getline: std::getline(std:...
71,977,106
71,977,125
seekp not seeking to proper location?
I have the following code: file.open(fileName, ios::in | ios::out | ios::binary); // many lines later file.seekp(fooAddr, ios::beg); printf("foo_addr: %d\n", foo_addr); file.write((char*)fooStruct, sizeof(FooStruct)); I know that fooAddr is 128 due to the printf. Yet, for some reason, when I open the target...
Your hex editor is displaying file offsets in hexadecimal format, not in decimal. Decimal 128 is hex 0x80.
71,977,651
71,977,844
attempting to specialize template function with non-type argument in C++
I have a templated function, which takes an array reference as a parameter: template<typename T, int arrSize> void foo(T (&pArr)[arrSize]) { cout << "base template function" << endl; } I want to specialize this function for C-strings: template<const char *, int arrSize> void foo(const char * (&pArr)[arrSize]) { ...
The problem is that the 2nd overloaded function template that you've provided has a non-type template parameter of type const char* that cannot be deduced from the function parameter. So to call this overloaded version we have to explicitly provide the template argument corresponding to this non-type parameter. To solv...
71,977,913
71,977,953
Why does std::sort work when the comparison function uses greater-than (>), but not greater-than-or-equal (>=)?
On WIN32, Visual Studio 2022. When I define a vector<int> containing one hundred 0s and sort it with the code below, an exception "invalid comparator" throws. vector<int> v(100, 0); sort(v.begin(), v.end(), [](const int& a, const int& b) { return a >= b; }); However, if I use return a > b, it will exe...
This is just how it is required to work. You need strict weak ordering. For the rationale, I believe that the sufficient explanation is that this enables you to determine whether those elements are equal (useful for e.g. std::sets). <= or >= can't do that. <= or >= can also do that, but it seems like it was just decide...
71,977,976
71,978,241
Inlined requires-expression for SFINAE, and using as constexpr bool
TL;DR: My question is that requires {...} can be used as a constexpr bool expression by the standard? I haven't found anything about that in the standard, but it simplifies a lot and results a much cleaner code. For example in SFINAE instead of enable_if, or some ugly typename = decltype(declval<>()...), or something e...
requires {...} is a requires-expression and according to expr.prim.req/p2 it is a prvalue: A requires-expression is a prvalue of type bool whose value is described below. Expressions appearing within a requirement-body are unevaluated operands. So yes, you can use it in a constexpr bool context.
71,978,335
71,978,837
class template's constructor declaration doesn't compile for C++20 but compiles for C++17
I am learning about templates in C++. In particular, i saw here that we can have the following declaration for the constructor: template<typename T> struct Rational { Rational<T>(); }; But the above snippet fails to compile in C++2a and compiles successfully for C++17. Is this a compiler bug or there is a reason w...
It is not a bug. It is the consequence of a change in the standard. Affected subclauses: [class.ctor] and [class.dtor] Change: A simple-template-id is no longer valid as the declarator-id of a constructor or destructor. Rationale: Remove potentially error-prone option for redundancy. Effect on original feature: Valid ...
71,978,346
71,978,403
Clion compile with -O3
I'm writing a c++ program using CLion and I need to specify -O3 flag on the compiler, using set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}" -O3) on the CMakeList file does not work. Is there a way to do it?
Use either add_compile_options(-O3) to add it globally or target_compile_options(YourTarget -O3) to add it locally to a specific target. You could also do it by using CMAKE_CXX_FLAGS but that is a pretty old way of doing things in CMakeLists files, that's how it would look like: set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}...
71,978,743
71,978,915
How to DLLImport function with array return type in c#?
Here it is: static uint8_t* Compress(const uint8_t* input, uint32_t inputSize, uint32_t* outputSize, int compressionLevel); I've tried : [DllImport("Mini7z.dll")] public static extern byte[] Compress(byte[] input, uint inputSize, out uint outputSize, int compressionLevel); and this [DllImport("Mini7z.dll")] public sta...
You need to tell the marshaller the size of the array he needs to generate upon return from the function. Therefore you need to specify an attribute on the return value. Try this: [DllImport("Mini7z.dll")] [return:MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I1, SizeParamIndex = 2)] ...
71,979,212
71,979,239
error: a function-definition is not allowed here before ‘{’ token
I've been trying to solve the error. How do I solve it? I've tried putting the functions outside the main function but its still not working. int mutexlock = 1, full = 0, emp = 20, x = 0, buffer[100]; void producer(); void consumer(); int randomgenerator(); int main() { void producer() { int d = randomgenerato...
You should put all functions out of the main function. Besides, please put the code you want to run after program starts in the main function. Example: int main() { producer(); consumer(); }
71,979,351
71,979,383
Why does p3 need a default constructor in this example?
Let's say I have C++ code like this: //main.cpp #include "p3.h" #include "tri3.h" int main() { p3 point1(0.0f, 0.0f, 0.0f); p3 point2(1.0f, 0.0f, 0.0f); p3 point3(2.0f, 0.0f, 0.0f); tri3 triangle(point1, point2, point3); } //p3.h #pragma once class p3 { public: float _x; float _y; fl...
tri3(p3 p1, p3 p2, p3 p3) The constructor fails to initialize its class's _p1, _p2, and _p3 members, therefore they must have a default constructor. _p1 = p1; _p2 = p2; _p3 = p3; This is not construction. This is assigning to existing objects. They are already constructed. To properly cons...