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
63,601,509
63,606,569
Does the following situations create race conditions in multithreading?
I'm new to C++ multithreading (apparently it's different from python multithreading / multiprocessing since multiple threads can use multiple CPUs inside a single process). I'm aware that a race condition would occur if 2 threads try to change the same data at the same time or if one threads reads something while anoth...
Don't go there. If there's data that's only ever written/read by one thread, it isn't shared data by definition and it doesn't need to be global. If there is data that is written by one thread and eventually read by another, use a lock, std::atomic, or some other synchronizes-with relationship and call it a day. static...
63,601,526
63,610,121
Error reading variables: Cannot access memory at adress x
so probably a silly question but i'm not very familiar with C++ so... Then i run this code, it crash with no error code after hitting the second if in the main #include <fstream> #include <string> #include "day.cpp" #include "appointement.cpp" using namespace std; // Flags are placed as constants to easy access const...
So after @molbdnilo pointed out, my "command" isn't actually the way it thought it was and only contain the first string in the command (each white space breaks my command in multiples strings). So the issue is then i call the second test, it cannot work because my "command" variable is smaller than the position i trie...
63,602,229
63,602,471
How to implement an abstarct class's method in sub-class by getting variables of it's parents class using a constructor in c++
First of all,there is a parent class called Shape and it has two constructors one with one parameter and another with two parameter.There are two classes which are inheriting properties from class "Shape". They are Rectangle and Circle . I tried it using java and i got what i wanted. Here is the java Implementation.. ...
You get the error because there is no definition for Shape::getArea, nor is it declared as pure virtual: virtual void getArea(); to make it pure virtual you need: virtual void getArea() = 0; Also you should provide a virtual destructor. When it is needed and when not is beyond the scope of this question. The easiest ...
63,602,431
63,602,984
Operations done in one thread visible to another without explicit synchronization
My question is about thread synchronization. Please see the code below: std::vector<int> v_int; for (size_t i = 0; i < 5; ++i) { v_int.emplace_back(i); } auto f_async = std::async(std::launch::async, [](auto v_int) mutable { for (auto& el : v_int.get()) { el += 10; } }, std::re...
std::async is specified as synchronizing with the invocation of the argument ([futures.async]/p5): Synchronization: Regardless of the provided policy argument, (5.1) the invocation of async synchronizes with the invocation of f. [ Note: This statement applies even when the corresponding future object is moved to anoth...
63,602,607
63,603,264
How to convert UINT16 into two signed chars?
I'm doing this conversion is because from a network where the data being received is an array of unsigned char[8]. Every two bytes represent a UINT16 number. I want to send these bytes through a socket however, sockets require the chars to be signed (I'm working in little-endian). Since it is impossible to convert a un...
[This is answered for C. OP has yet to clarify their needs for C versus C++ answers.] To pass an array of unsigned char named buffer using the send function, which has an parameter of type of const char *, simply cast the array to the required type, as with: send(socket, (const char *) buffer, length, flags); In C, ch...
63,602,839
63,603,131
Vector sorting with lambda function, how to pass in variable to capture group when not in the same scope?
Essentially I have quite a large lambda function for sorting a vector of custom objects. The only issue is that the lambda function is dependent on a object that is passed to it via a capture group. This has worked fine for some time, however now I want to reuse the same function in different parts of the program. Here...
A lambda is just syntactic sugar for functors. One big plus is that you can write lambdas inline, in the same scope, directly at the place where you use it. On the other hand, if you want to reuse it elsewhere, there is no big advantage of a lambda compared to a plain function object. Maybe it is more clear if you skip...
63,603,266
63,957,033
API to retrieve process creation time (Linux)
I am looking for an API that a process can use to figure out its own creation timestamp. With 'creation timestamp' I mean the point in time where the process was "born", i.e. the birth timestamp. The specifics of my situation: The program I need this for is a C++ library; and is compiled with gcc 7.3.1; and runs on L...
POSIX stat doesn’t define this field, but you can get it from statx. This was added at the start of 2019, so you need fairly new kernel and glibc versions to take advantage of it.
63,603,484
63,603,608
Values in optional<map<string, string>> getting "corrupted" in very specific cases
Sorry for the poor title, but what I'm seeing is bizarre and hard to explain succinctly. Basically, we have an optional<map<string, string>> in our code accessed through a getter/setter, and sometimes when we inspect the values we get very strange results. Here is simplified code which repros the issue: #include <optio...
In this loop: for (auto &item : Get().value()) you are invoking undefined behavior, because the temporary returned by Get() will die at the end of the full expression, and the .value() that your range for loop will be iterating over refers to memory that no longer exists. The strange behavior that you notice with stri...
63,603,833
64,880,549
Problem with using the NDK with other build systems
I am learning Use the NDK with other build systems. Trying to get the example for Autoconf to work. It looks like ./configure --host $TARGET is working as expected. But I get an error while executing make: arm/filter_neon.S -fPIC -DPIC -o arm/.libs/filter_neon.o arm/filter_neon.S:24:17: error: expected string in direc...
There are bug in libpng. Do not use cloning from github. Use released version. There are different link on github https://github.com/glennrp/libpng/releases/tag/v1.6.35 Change this script from official doc and do not clone github repo, just download archive and run this script inside of it. For me all is working.
63,604,269
63,678,275
Unable to run compiled C++ programs on first execution
Ever since upgrading to Mac OS Catalina, any time I compile a C++ program, it does not run the first time. The program compiles as expected and the executable is created and appears normal in all regards. However, when I run the program it immediately prints: -bash: ./a.out: Input/output error Immediately running the...
After days of digging, I was able to resolve the issue. The problem was that my organization uses Cylance, and advanced threat mitigation tool. After Catalina upgrade, Cylance lost its Full Disk Access under the security settings in system preferences. I granted the permissions and was able to get an updated policy tha...
63,604,315
63,604,418
c++ numeric_limits<double>::epsilon() for values other than 1
numeric_limits<double>::epsilon() is defined to be the difference between 1.0 and the next value representable by double, but I want to find/calculate the numeric_limits<double>::epsilon() of a value other than 1.0? Is there any way to do this?
As pointed in the comments, you can use std::nextafter: float nextafter ( float from, float to ); Returns the next representable value of from in the direction of to. float f = /* ... */ float next_after_f = std::nextafter(f, std::numeric_limits<float>::infinity());
63,604,415
63,623,059
How to get rid of Djinni generated unnecessary function - ToString (in Java)/Description (in Objc)?
I am trying to understand the impact of Djinni generated function on binary-size of my cross-platform project. My project does not have a need for these generated ToString/description functions. Is there a way to get rid of them?
There's no built-in flag to disable them, but if you're comfortable modifying the Djinni Scala code it wouldn't be too hard to simply delete the lines which generate those functions. For instance, here's the relevant code block for Java generation: https://github.com/dropbox/djinni/blob/master/src/source/JavaGenerator...
63,604,462
63,604,556
thread - How to access a member variable inside a lambda function?
My case is specific to threads: #include <vector> #include <thread> #include <mutex> #include <condition_variable> #include <iostream> class A { public: std::vector<std::thread> threadVector; std::vector<int> numbers; std::mutex objMutex; std::condition_variable objCondVar; ...
You have used counter without capturing it and note that you are capturing arg by value. By the following, you are capturing counter and arg by ref void func( int arg ) { std::unique_lock< std::mutex > objUniqueLock( objMutex ); objCondVar.wait( objUniqueLock, [&]{ return (arg == counter); } ); std::cout <...
63,604,614
63,604,698
Does --list.begin() == list.end()?
Does the standard guarantee that --list.begin() == list.end() always holds and that it infact is a valid operation? (list is an instance of std::list). It appears to be the case with at least MSVC 2019. This would be useful for instance in the following case: for ( auto i = list.begin(); i != list.end(); ++i ) { ... ...
Does the standard guarantee that --list.begin() == list.end() No, standard does not guarantee that for std::list (nor can such guarantee be assumed given a bidirectional iterator). In fact, the behaviour of --list.begin() is undefined. This would also require ++list.end() == list.begin() to hold; what about that? ...
63,604,783
63,605,052
Check if instance is null or something is in it
I have a timer class in my C++ project, where I have these variables: std::chrono::steady_clock::time_point startTime, endTime; I set my startTime in the constructor, but not the endTime. What I need to do is I want to check, if the endTime is present. As a Java developer, I would do that using endtime == null in java,...
What I need to do is I want to check, if the endTime is present. A time_point is a value type, not a reference type, so you can't compare it to nullptr. However, if a time_point has not been assigned a value, it is default initialized to hold the clock's epoch (ie, time_point::time_since_epoch() returns 0). That can...
63,604,914
63,607,159
How can I speed up the binary GCD algorithm using __builtin_ctz?
clang and GCC have a int __builtin_ctz(unsigned) function. This counts the trailing zeros in an integer. The Wikipedia article on this family of functions mentions that the binary GCD algorithm can be sped up using __builtin_ctz, but I don't understand how. The sample implementation of the binary GCD looks like this: u...
Here's my iterative implementation from the comments: While tail-recursive algorithms are often elegant, iterative implementations are almost always faster in practice. (Modern compilers can actually perform this transform in very simple cases.) unsigned ugcd (unsigned u, unsigned v) { unsigned t = u | v; if (...
63,604,984
63,608,238
Changing float rounding mode
Having the code like below: #include <stdio.h> #include <float.h> #include <windows.h> #pragma fenv_access (on) void precission(void) { unsigned int control_word; int err; float a = 10.0, b = 3.0; char MsgBuff[300]; err = _controlfp_s(&control_word, _RC_UP, _MCW_RC); if (err) { spr...
I suggest that you could Multiply the number, round it, and divide it. int main() { float a = 10.000; float b = 3.000; float c=a/b; float d = (int)(c * 1000+1) / 1000.0; cout << d;//d=3.334 return 0; }
63,605,044
63,605,072
Should I define a destructor for a derivate of QWidget
I would like to know if I should define a destructor of a derivate of QWidget. Example class CustomWidget : public QWidget{ QLabel* field; CustomWidget(QWidget* parent) : QWidget( parent ), field( new QLabel(this) ) {}; } I've already read about the "Widget tree" that will call the destructor...
For the given one, no. The parenting system will take care of field. But u should add Q_OBJECT macro.
63,606,452
63,606,739
My "Longest Common substring with at most k mismatches" algorithm with O(m*n) space complexity is giving wrong answers with large string inputs
I am new to this platform so please bear with me. My program was based on the longest substring problem with no mismatches using Dynamic Programming. Here is a link to the D-P solution. https://www.geeksforgeeks.org/longest-common-substring-dp-29/. Here is a link to the original problem. https://www.hackerrank.com/chal...
Your program don't give correct answer when both of the longest common substrings are not prefixes of each input strings. For example, substringDiff(0, "xa", "ya") returns 0 while 1 is expected. This is because only number of differences from beginning of either strings are calculated. Example table for substringDiff(0...
63,606,730
63,606,756
libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: vector Abort trap: 6. any help would be awesome, thank you
I'm trying to solve fractional knapsack problem, for now logic aside can anyone suggest me or explain me what is happening here? I never seen this runtime-error before, any help would be awesome, thank you. #include <iostream> #include <vector> #include <algorithm> using std::vector; bool myfunction(int a, int b){retu...
Suppose that v is a vector, only elements v[0] to v[v.size() - 1] are available and v[v.size()] is out-of-range. Therefore, for(int i=0;i<=weights.size();i++) and for(int it =0;it<=values.size();it++) should be for(int i=0;i<weights.size();i++) and for(int it =0;it<values.size();it++) (use < instead of <=)
63,607,058
63,607,161
How does a compiler use T::operator< in std::set when the template parameter asks for std::less<T>?
When you create a std::set, one of the template parameters is class Compare, which defaults to std::less<T>. Now, even if you don't give a specialization of std::less<T>, defining T::operator< is good enough for C++ to "figure it out". But C++ isn't figuring anything out, a compiler is. And the compiler is going throug...
The standard library is defined such that std::less<T> will use operator< unless otherwise specialized. So if you don't provide a specialization, if the type supports < then it will work out. From std::less<T> : Function object for performing comparisons. Unless specialized, invokes operator< on type T. And for std::...
63,607,075
63,607,418
How to use variants as the key in unordered_map?
How can I use variants as the key in unordered_map? For example, I'd like to make the following code work. using VariantType = std::variant<int, std::string, unsigned int>; std::unordered_map<VariantType, int, $some_hash_function$> m; How do I implement $some_hash_function$?
There is already a hash template specialization for variant: http://en.cppreference.com/w/cpp/utility/variant/hash The only condition is that every type in the variant must have a hash function: The specialization std::hash<std::variant<Types...>> is enabled (see std::hash) if every specialization in std::hash<std::re...
63,607,128
63,607,172
The correct way to use the GNU linker
I am trying to use a couple of libraries, libglfw3-dev and libglew-dev, on an ubuntu environment but have been unable to get the linker to perform its intended purpose. I would normally use a makefile but for the purpose of debugging I have just used g++ on the CLI. g++ -I-Iinclude -I/usr/include/GL -I/usr/include/GLF...
Remove lib at the beginning of the names. E.g. the library's name is libGLEW.so.2.1.0 Link it with -lGLEW This will link to libxGLEW.so which usually is a symlink to a versioned library like libGLEW.so.2.1.0. -llibrary -l library Search the library named library when linking. (The second alternative with the library...
63,607,389
64,127,833
Building Verilator (C++) with CMake built-in NDK
I tried with this example, but nothing happens: cmake_minimum_required(VERSION 3.8) project(cmake_simulator) set(CMAKE_SYSTEM_NAME Android) set(CMAKE_SYSTEM_VERSION 21) set(CMAKE_ANDROID_ARCH_ABI x86) set(CMAKE_ANDROID_NDK /home/icarolima/Android/Sdk/ndk/21.3.6528147) set(CMAKE_ANDROID_STL_TYPE gnustl_static) set(CMA...
So, just to clarify, the way I solved it can be seen here: Dockerfile, and here: sandbox_template. Thanks for the answers @squareskittles!
63,607,536
63,617,603
ifstream is crashing on x64 bit platform
i am trying to use ifstream to open a txt file and read data from that file with ifstream, while that code works just fine on x86 bit platform, it causing weird application crash when using it on x64 bit platform. ifstream font; font.open(filename); if ( font.fail() ) { return false; } // Used to read 95 ASCII ch...
So as some pointed out, casting from one string type to another type, in this case from const char* to char* is causing undefined behavior, at first i fixed it in the reproducible example but couldn't fix it in my main project but after changing all string types to the ones that original function is taking it solved th...
63,607,541
63,610,680
C++ linux bluetooth sdp_connect only succeed with root privilege
I'm trying to run a bluetooth server program on Linux In order for my client device to find the server, I need to register my service profile on sdp My code is basically similar to code on this page The problem is that I need to get root privilege in order to make sdp_connect succeed When running as a normal user, sdp_...
As you rightly note, there have been 8 tools marked as deprecated as they are no longer maintained or have been replaced by other tools. Running with --compat would seem like a quick fix rather than a long term solution. The supported APIs are Bluetooth Management API which is focused towards system level functions. Th...
63,607,555
63,607,608
Runtime error when compiling Objective-C project using g++
I've made a really small project using Objective-C, and If I run it with the Xcode, It works really well. But, I need to compile it using below command lines: g++ Main.mm -o Main `gnustep-config --objc-flags` `gnustep-config --base-libs` -O2 -DONLINE_JUDGE -DBOJ This command line is what the site I'm trying to upload ...
Those are linker errors, not runtime errors. You need to link against the objc library and Foundation framework. Try: g++ Main.mm -lobjc -framework Foundation ...
63,607,594
63,632,113
c++ math lib what happen when domain error?
According to the asin document , I'm still not clear about the behavior: beside the errno being set, is there any exception thrown, or segmentation fault, or silently, or it's UB, or it's compiler/system/runtime defined? I'm debugging my program, which crash on client's machines. According to the coredump file, it fina...
I would generally prefer cppreference.com over cplusplus.com. According to the cppreference asin documentation, std::asin will not throw any exceptions. It will, on domain error, return NaN (if supported) or some other "implementation defined value" and set errno as you said. According to the C++ standard, the contents...
63,607,715
63,610,889
Macro for calling a series of macro-generated functions with similar names (i.e. f_0, f_1, f_2, ...)
I got stuck with quite peculiar problem, and I at the moment have no idea how to solve it. I am using the following block of macros to generate functions with similar names: #define CONCAT_IMPLEMENTATION(arg1, arg2) arg1 ## arg2 #define CONCAT(arg1, arg2) CONCAT_IMPLEMENTATION(arg1, arg2) #define UNIQUE_FUNCTION_NAME(...
There is no magic in preprocessor. To overload, you have to enumerate all possible cases anyway. #define RUN_ALL_GENERATED_FUNCTIONS_1() UNIQUE_FUNCTION_NAME(0)(); #define RUN_ALL_GENERATED_FUNCTIONS_2() RUN_ALL_GENERATED_FUNCTIONS_1()UNIQUE_FUNCTION_NAME(1)(); #define RUN_ALL_GENERATED_FUNCTIONS_3() RUN_ALL_GENERAT...
63,608,021
63,608,306
Is initializing a vector of empty values more efficient than just calling `push_back()`?
So, I want to avoid constantly push_back()-ing because I know that it is inefficient. Say that I have a class Network that takes a const std::vector<int>& topology. It has a std::vector<Layer> layers property that is created using this topology. The number of layers that are created is equal to the .size() of the topol...
In short, push_back causes re-allocation only when size exceeds capacity. If your concern is preallocation "might" impact performace, then using vector::reserve would let vector preallocate capacity if you know how much you want. Then push_back won't cause allocation when it doesn't exceed capacity. However if you don'...
63,608,712
63,633,382
Is there a way to exclude rows and columns in a C++ array?
Suppose I have an array in C++ such as the following: 1 2 3 4 = arr 5 6 7 8 9 9 8 9 7 6 1 3 Is there a concise way to exclude any row and/or column? For example, suppose I want to do an operation on the following array: 1 3 4 5 7 8 7 1 3 In other programming languages, I can obtain the above array f...
To me, it seems a more straightforward approach is to fill an n-1 length uvec with sequential integers, just skipping i, like so: // [[Rcpp::depends(RcppArmadillo)]] #include <RcppArmadillo.h> // [[Rcpp::export]] arma::mat exclude_one_row_and_col(const arma::mat& X, arma::uword i) { arma::uword n = X.n_rows; // X ...
63,608,716
63,611,785
How to create a videoCapture object in a class
I am trying to use a VideoCapture object in a class , all the examples that i have seen are setting the camera id in the constructor of the object. cv::VideoCapture cam(1); if i declare the object as a class variable cv::VideoCapture cam how can i initialize it in the class constructor to camID = 1;
You can initialize it by using open : class InitialiseTest { VideoCapture cap; public: InitialiseTest(){ cap.open(1); } }; int main() { InitialiseTest obj; }
63,608,967
63,610,528
Function-like macro not accepting nested #define
I am using macros to determine a variable's real type based on a pattern, and I am getting some weird macro errors that I do not understand: a.cpp:15:4: error: '#' is not followed by a macro parameter #define USING_INTEGER\ ^ a.cpp:15:11: error: unknown type name 'USING_INTEGER' ...
As I understood the motivation of the OP's question the intention is: to parse text determine a certain type of input store the value in that type. Types of variables have to be defined at compile time. (That's one of the C++ language core concepts called static type checking. There is no chance to define a type of a...
63,609,000
63,609,396
Partial template specialization of std::atomic for smart pointers
Background Since C++11, atomic operations on std::shared_ptr can be done via std::atomic_... methods found here, because the partial specialization as shown below is not possible: std::atomic<std::shared_ptr<T>> This is due to the fact that std::atomic only accepts TriviallyCopyable types, and std::shared_ptr (or std:...
Several proposals for atomic<shared_ptr> or something of that nature explain a variety of reasons. Of particular note is P0718, which tells us: The C++ standard provides an API to access and manipulate specific shared_ptr objects atomically, i.e., without introducing data races when the same object is manipulated from...
63,609,045
63,609,313
Sorting a vector of structs c++
I have a struct where data is defined as: typedef struct contacts { string name; string nickName; string phoneNumber; string carrier; string address; //callDetails callDetails; } contactDetails; vector <contactDetails> proContactFile; I have like 10 -20 fields of information inside the vecto...
Learning about "custom comparators" will solve your problem. Here is one of the ways to achieve the desired result. I am using cmp as a custom comparator. Notice that it is passed while calling sort(). This way is useful if you need to sort on basis of something else tomorrow, say phoneNumber. The only change you would...
63,609,118
63,609,149
Template Class Inside Template Class - Different Parameter
Is it possible to create a template class inside a template class like the following // Container.h template <typename T> class Container { private: using iterator = Iterator<Node<T>>; using const_iterator = Iterator<const Node<T>>; // Node struct to hold data. template <typename T> struct Node { T dat...
You should define it as template <typename T> // for the enclosing class template template <typename NodeType> // for the member template Container<T>::Iterator<NodeType>::Iterator() { // Implementation ... } BTW: The member class template Node can't use the same template parameter name T as the outer class ...
63,609,321
63,609,536
Multipath recursion Maximum Value in Array
I am having trouble writing a multipath recursive function given an unsorted integer array. std::max(maxArray(a[],first,last)) I understand that I need to split the arrays in half and use the std::max function that compares two integers such as: return std::max(maxArray(a[],Not sure, Not Sure),maxArray(a[], Not sure, ...
I'm struggling to understand your explaination of what it is you don't understand. But the principle behind the code you've been given is that if you divide an array into two halves and find (recursively) the maximum value in each half, then the maximum value for the whole array is the larger of those two values. Somet...
63,609,886
63,609,980
Define member functions once for two similar classes?
Is it possible to avoid defining the same functions for structs A, B below twice? Their members are named exactly the same, but the v0, v1 ... vN members are of different type between the two structs A and B. If it helps the members v* are all derived from the same struct V. Non-trivial functions (i.e. assignment =) ca...
You can keep a common base template class for the common functionalities and inherit from it for class A and B. However, the copy assignment operator is a special member function, which I do not think one could template for different types return in the base class. Therefore you need to provide for each class. Meaning,...
63,609,901
63,610,034
Problem removing a character from char array
I am writing a program to remove the character "&" from a char array if it exist and display the output. Here is my code: #include <iostream> #include <string> using namespace std; void decrypt(char mess[1024]) { int i = 0; int decmp = 0; int len = strlen(mess); char decmess[256] = {0}; while (i < ...
You are overly complicating things mixing strlen() and char[] and #include <string>. You rely on initialization without ever affirmatively nul-terminating decmess, you don't need strcmp() to compare a single character. It appears you wanted to do: #define MAXC 1024 /* if you need a constant, #define one (or m...
63,610,256
63,611,081
what is the meaning of the phrase "preceding initialization" in section [expr.const]
constexpr int func(int const& rf){ return rf; } int main(){ constexpr int value = func(0); } Consider the above code, the variable value shall be initialized by a constant expression, which is func(0), which firstly shall be a core constant expression. To determine whether the expression func(0)is a core consta...
The outcome seems to evidence that "preceding initialization" means "be initialized" rather than have an initializer due to the parameter declaration does not have an initializer in the first example. It does mean "be initialized", but it's more importantly about the visibility of a preceding initialization within th...
63,610,311
63,700,948
WebView2 - How to read data from BLOB URL?
How do i read data as text from a BLOB Url in WebView2 ? I've tried WebView2 callback from Javascript which i couldn't make it work. I appreciate whether it is a Javascript solution or not but i prefer C++.
Unfortunately, Webview2 doesn't support async function results in ExecuteScript. I managed to get data by performing synchronous request with ajax. wstring jquery(L"var jqry = document.createElement('script');" L"jqry.src = 'https://code.jquery.com/jquery-3.3.1.min.js';" L"document.getElementsByTagName('head')[0].appen...
63,610,391
63,611,179
Get path of Csrss.exe
I want to get the path of a PID pointing to Csrss.exe. I cannot use the OpenProcess function because MSDN specifically states that it will return ACCESS_DENIED on processes such as Csrss.exe and Idle. I have tried using Process32Next to get a PROCESSENTRY32 structure, which has an exeName field. However, that's just ...
As it turned out there is new function in Vista and above for getting process path and new process access (PROCESS_QUERY_LIMITED_INFORMATION): You can get the handle of the process with this permission.Here is the sample: #include <Windows.h> #include <psapi.h> #include <iostream> #include <tlhelp32.h> BOOL SetPrivile...
63,610,562
63,618,719
How to get yy::parser::token from yy::parser::symbol_type in Bison c++ variant?
For example, I return yy::parser::symbol_type in flex rule via: [a-zA-Z][a-zA-Z0-9_]* return yy::parser::make_ID(yytext); where ID is a token I defined in bison, it will generate the yy::parser::token structure. Now I want to do some unit test just for flex's token.l, when I invoke the yy::parser::symbol_type yylex()...
There is no object of type yy::parser::token. That struct exists only to hold the enum token_kind_type enumeration (not a member with that value; the enumeration itself). See the Bison manual outline of the C++ API. I don't really understand the motivation for this, but I suppose it comes from a desire to allow ancient...
63,610,623
63,612,020
Warning C26812: Enum type is unscoped. Prefer enum class over enum
It is puzzling me as to why am I getting this warning at all. I do not even have enumerations in my entire code? #include <SFML/Graphics.hpp> #include <vector> using sf::RenderWindow; using sf::VideoMode; using sf::Event; using std::vector; using sf::Vector2f; using sf::RectangleShape; using sf::CircleShape; using sf:...
Unfortunately, this warning comes from the header file SFML\Graphics.hpp and the only option is to contact the SFML developers and ask them to fix this warning as suggested by @spectras in the comment section. There is no solution that I can implement that will solve the warning. However, it is best to disable all the...
63,610,793
63,613,006
Need To Print Repeated Numbers Just Once / C++
Can't use libraries and other methods. As you can see my program finds the repeated numbers and print it but I need to print the numbers just once. As example if entered: 7 1 1 2 1 2 2 9 It should print 1 2 In case there is no any repeated number: 7 1 2 3 4 5 6 7 There should not be any output! Also note, that the firs...
Instead of two bools as the other user suggested I would use the counter basically doing the same thing but with one variable. The trick is to check if you have already had the number you are checking right now before so that you wouldn't print it again. And then to check the rest of the list for duplicates. #include <...
63,611,049
63,613,297
override a C++ virtual function within Python with Boost.python?
I have a C++ class with a virtual method: //C++ class A { public: A() {}; virtual int override_me(int a) {return 2*a;}; int calculate(int a) { return this->override_me(a) ;} }; What I would like to do is to expose this class to Python with Boost.python, inherit from this class in Python and have the correc...
You can provide a thin wrapper around your class that delegates the override_me method calls to boost::python-specific override function. Derived class calculate calls simply call the parent class calculate method, so when they are called from Python, they call the C++ defined calculate method, but still allow override...
63,611,051
63,611,359
Memory occupation with "this" pointer
Could anyone tell me if the pointer "this" in object of class occupy memory when it was created? class Temp { private: Temp &operator=(const Temp &t) { return *this; } }
this is the address of the object whose member function is being called, and it doesn't need to be stored anywhere. It is usually implemented by passing its value as a "hidden" argument to the member functions, so it occupies memory in the same way as any other function argument occupies memory. The "object-oriented" c...
63,611,268
63,612,403
Cannot make std::reference_wrapper work with std::unique_ptr
I have an object pool that holds objects in std::unique_ptr<T>. The pool, like most pools, holds objects that are expensive to create, but once an object is borrowed there is no way of preventing an object with the same settings from being added to the pool so I'd like to extend it to prevent that from happening. I see...
The reference version is just bad - because as soon as the unique_ptr is moved the reference wrap gets invalid. You'd better just store raw pointers instead. But in this case it won't know whether it is destroyed or not. You can make unique_ptr with custom destructor that marks in the pool that the object is destroyed....
63,611,687
63,612,565
C++ Dynamic 2D Array to OpenCV Mat
I've ref the article: How to convert C++ array to opencv Mat It's work for normal 2D array. However, if I use DYNAMIC 2D array as input, it fail... int total_row = 2; int total_col = 4; unsigned short **my_arr = NULL; my_arr = new unsigned short*[total_row]; //allocate memory for each 1D array for (int i = 0; i < tota...
Thanks for Nicholas Betsworth! If using 1D dynamic array, it's working! unsigned short *my_arr = NULL; my_arr = new unsigned short[total_row*total_col]; for (int i = 0; i < (total_row*total_col); i++) { *(my_arr + i) = count; count++; } Mat mat(total_row, total_col, CV_16UC1, my_arr);
63,611,957
63,612,636
Chnging the float roud-up mode
I'm trying to change the round-up mode using the _controlfp_s function. Here is the code: void precission(void) { unsigned int control_word; int err; float a = 10.0, b = 3.0; char MsgBuff[300]; float result1, result2; err = _controlfp_s(&control_word, _RC_UP, _MCW_RC); if (err) { s...
That is due to the limited precision of a float data type. There is no way to represent any value between 3.33333325 and 3.33333349 using a float, because the minimum "step" (epsilon) of a single-precision float is 0.000000119209. int main() { unsigned int control_word; float a = 10.0, b = 3.0; float resul...
63,611,963
63,612,550
How do I append instead of overwrite here? (and how does this code open a file?)
I was going through an OpenFoam (v7) (C++) tutorial and came across this code for IO: // Create a custom directory and write an output file // Create the output path directory fileName outputDir = mesh.time().path()/"postProcessing"; // Createe the directory mkDir(outputDir); // File pointer to...
OFstream constructor: OFstream( const fileName& pathname, IOstreamOption streamOpt = IOstreamOption(), const bool append = false ) So: outputFilePtr.reset( new OFstream(outputDir/"customOutputFile.dat", IOstreamOption(), true) ); ...
63,612,456
63,615,232
JNI:converting jstring(full of number) into jint using Integer.pasteInt by jvmti caused Crash
jclass in = jniEnv->FindClass("java/lang/Integer"); jmethodID ipi = jniEnv->GetStaticMethodID(in, "parseInt", "(Ljava/lang/String;)I"); jint test = jniEnv->CallStaticIntMethod(in, ipi, (jstring)jniEnv->CallStaticObjectMethod(System, getProperty, jniEnv->NewStringUTF("input"))); Here is my code I try to c...
You did not show an actual error, but I can guess at one reason: 10029909473242 is too large to fit into a Java int so I bet Integer.parseInt threw a NumberFormatException. Calling any JNI method with a pending exception will crash the JVM. The root cause here is that you should use Long.parseLong instead, but you shou...
63,612,477
63,612,583
C++ Non-Template Used as Template - Nested Template Classes
I know people have asked similar questions in this area, but I can not seem to find a solution to my exact problem. I have a LinkedList and LinkedListIterator class structured as so. template <typename T> class LinkedList { public: template <typename NodeType> class LinkedListIterator { public: const Li...
Add template keyword before LinkedListIterator so compiler knows it is a template and not e.g. a field template <typename T> template <typename NodeType> const typename LinkedList<T>::template LinkedListIterator<NodeType>& LinkedList<T>::LinkedListIterator<NodeType>::operator++() { // Implementation here ...
63,612,684
63,612,720
How can I set if else conditions inside the for loop?
I try to do this, but the loop doesn't work for some reason, it just skips it. I need to do if the i variable is greater than 10 then check the g condition and if it is equal to 1 complete the loop until two conditions are met the loop should not end int main() { for (int i = 0, g = 12; i < 10 ? g == 1 : false; i+...
I need to do if the i variable is greater than 10 then check the g condition and if it is equal to 1 complete the loop... Your usage to Conditional operator there is wrong. Instead, you should be simply using logical && operator there for (int i = 0, g = 12; /*first condition*/ && /* second condition */ ; i++, g--) /...
63,612,700
63,614,570
QComboBox doesn't display the currently selected item unless another button in the dialog is clicked
I have this QDialog: The QComboBox won't display the currently selected item unless any other button inside the dialog was clicked. Important thing to note is, that this only happens in the deployment. When I run the project in Qt it works just fine. Is there a DLL interfering with the QComboBox? I don't know where to...
I found this workaround that does the same what needs to happen for it to appear, when you use the app. This code gives focus to the checked radio button when the dialog appears. void settings_box::showEvent(QShowEvent *event){ //makes the event happen event->accept(); //which radio button is checked i...
63,612,749
63,612,822
Passing values from a function to another function
I'm new in C++ programming world and I have not understood yet if it's possible (and how) to use an output from a function as input to another function. #include <iostream> using namespace std; int func(int l, int m) { int x = l * m; return x; } int code(x?) { ... } I would like to use output from func ...
Functions only "have" values while they are executed. You can either call the first from the second funtion, or call the first function, read the return value into a variable and give that value as parameter to the second, or call the second and give one of its parameters directly as return value from a call to first f...
63,612,944
63,613,524
How to static_assert to check function signature is correct
The Code I have a templated type that follows the Observer Pattern. template <typename T> class Subject { public: template <template<typename> typename Observer> void AddObserver(Observer<T>& observer) { observers.push_back([&](const T& value) { observer.OnEvent(value); }); } void Event(con...
It's not clear to me what restrictions you want here. The most restrictive would be to enforce something like: static_assert(std::is_same_v<decltype(&Observer::OnEvent), void (Observer::*)(const T&) const>); where the OnEvent function couldn't be a template, it couldn't return anything asi...
63,613,585
63,613,781
C++ Multi-dimensional Array with sum for each row and column
A couple of days ago I re-start coding. This time with C++ and not Java. I have book full of lessons. By one I'm stuck now since two days. Maybe someone here can give me some advices. The lesson starts with this code: #include <iostream> #include <iomanip> using namespace std; int main() { // ein 2-dim. Array ers...
The main idea is to add an extra row and column so that we can store the sum as we fill up the matrix with random numbers. I have tried to keep as much as possible of your code intact. I have added comments wherever the code needs a change. #include <iostream> #include <iomanip> using namespace std; int main() { /...
63,613,676
63,851,293
RocksDB - Double db size after 2 Put operations of same KEY-VALUEs
I have a program that uses RocksDB that tries to write huge amount of pairs of KEY-VALUE to database: int main() { DB* db; Options options; // Optimize RocksDB. This is the easiest way to get RocksDB to perform well options.IncreaseParallelism(12); options.OptimizeLevelStyleCompaction(); // create the DB if it's not al...
A full compaction can reduce the space usage, just add this line before delete db;: db->CompactRange(CompactRangeOptions(), nullptr, nullptr); Note: a full compaction do take some time, depends on the data size. Space amplification is expected, all LSM tree data structure DBs have this issue: https://github.com/facebo...
63,614,208
63,614,344
Measure the execution time of a function
I want to measure the time of a function execution. I could use something like this: using namespace std::chrono; auto start = steady_clock::now(); // process auto end = duration<double>(steady_clock::now() - start).count(); but I it seems pretty non-DRY to me. So I created a small function to do it: template <typenam...
Instantiate this class in a function and it will print the time when the object goes out of scope. class Timer { private: std::chrono::steady_clock::time_point begin; std::string_view func_name; public: Timer(std::string_view func) { func_name = func; begin = std::chrono::steady_clock::now(); } ~...
63,614,268
63,614,383
"invalid use of incomplete type" with variants and CRTP
I have been using the curiously recurring template pattern (CRTP) with an std::variant as follows: #include <string> #include <variant> #include <vector> template<typename T> struct either { std::vector<T> arg; }; template<typename T> struct maybe_either: std::variant<T, either<maybe_either<T>>> { template<t...
The error message is not clear, but in fact there is a mistake at this line: auto expression = maybe_either<var>(either<var>{}); either<var> is not an acceptable type for the variant, but either<maybe_either<var>> is. Writing this instead, works: auto expression = maybe_either<var>(either<maybe_either<var>>{});
63,614,405
63,631,540
Read file as unsigned char* to encrypt with openssl in c++
As far as I can see the EVP funktions in openssl only accepts unsigned char * as input. An example code would be: int gcm_encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *aad, int aad_len, unsigned char *key, unsigned char *iv, int iv_len, ...
Found a more efficient way to solve the problem. Using unsigned char * was a bad idea in the fist place. In the official documentation there is a way beffer solution. However I have made two cahnges. First cahnge: EVP_CipherInit_ex(&ctx, EVP_aes_128_cbc(), NULL, NULL, NULL,do_encrypt); to EVP_CipherInit_ex(ctx, EVP_ae...
63,614,569
63,614,654
why i am getting 3 7 as output even if i am using break statement /* 4 4 2 2 4 3 */ /* o/p 1 2 3 7 */
#include <bits/stdc++.h> using namespace std; //program to find index of number giving sum as m int main() { int m; cin>>m; //sum int n; //size of array cin>>n; int a[n]; for(int i=1; i<=n; i++) { cin>>a[i]; } int k=1; while(k<=n) { for(int i=1; i<=n; i++) ...
In C++ array indexes start at zero not one, so for(int i=0; i<n; i++) { cin>>a[i]; } Similarly here, but also because you access the array at index k+1 you need to compare this against n rather than k. int k=0; while(k+1<n) { for(int i=0; i<n; i++) { if(a[k] + a[k+i]==m) { cout<<k<<" "<...
63,614,604
63,614,873
c++ Algorithm Why does an infinite loop go around
I was trying to solve a problem on the algorithm site and asked a question because I couldn't catch the error. I can't understand why the infinite loop goes. My algorithmic logic is correct. Because if you remove the while in the main statement and print it for each case, the infinite loop does not run. The problem sit...
The input gives width first, not height. cin >> w >> h;
63,614,685
63,614,936
Why does the win32 message loop stop working when threaded?
I am trying to create a WIN32 (C++) program in which I will have to simultaneously process messages and run a while loop. In order to do that, I want to use threads. When I moved the message loop to a separate procedure (called from the function WinMain), all things were working fine. However, when I used the code belo...
The fundamental reason is that Windows has the notion of a thread message queue. Each thread has its own message queue. It's OK to run GetMessage in a thread, but it will get you only the messages that belong to that thread, such as for windows which you create in that thread. Messages belonging to any other thread (no...
63,614,768
63,615,625
Why this Windows message loop does not handle shorcut/tab keys?
There is a following loop in the code used during lengthy processing: MSG msg = { 0 }; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } (can be just added to dialog as an action to button click to demonstrate the issue). During this loop, the dialog is drawn correctly and...
Those features are implemented by IsDialogMessage() which you're not calling. MSG msg = { 0 }; while (GetMessage(&msg, NULL, 0, 0)) { if (!IsDialogMessage(hwndDlg, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } }
63,614,799
63,614,908
moc_kviz.cpp:72: error: undefined reference to `Kviz::on_lineEdit_textChanged(QString const&)'
This error shows me the following: void Kviz::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { Kviz *_t = static_cast<Kviz *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->on_lineEdit_textChanged((*reinterpret_cast...
The qt_static_metacall is automatically generated by the MOC, that should be the reason why it shows after some time. I believe you forgot to delete on_lineEdit_textChanged(QString const&) from either *.c or *.h file.
63,614,988
63,615,124
Explain me about std::function handling by class member method
#include <iostream> #include <functional> class world { public: void hello(){ std::cout << "wow" << std::endl; } }; int main(void) { std::function<world&,void()> pFn = &world::hello; //is this right??? }; I tried this, but it doesn't work :( how to handle it? please explain me cool way
First, std::function is: template< class > class function; /* undefined */ template< class R, class... Args > class function<R(Args...)>; Your std::function<world&,void()> doesn't make sense. You are supposed to pick the function type you want to store in the function object. Next, you need a world to call one of it...
63,615,135
63,668,099
Is it possible to globally #define a macro? (for the real-time error checker to see)
By "macro" I mean simple values like: "#define FOO 123". I installed VS Code (not visual studio), and the C/C++ and Visual Intellicode extensions. I have a folder of a project created in another IDE which I'm still going to use to debug and more, specifically geared to certain embedded targets. That IDE and its config ...
Press Ctrl+Shift+P to open the command window, then, if you installed the C/C++ extension before, there will be several C/C++ settings (how many seem to depend on what kind of sources are in the folder you opened for the workspace). From there, you can select:C/C++: Edit Configurations (UI) On the then opening tab pag...
63,615,193
63,634,923
Using non-member non-friend functions instead of member functions: disadvantages?
Scott Meyers has long advocated using non-member non-friend functions instead of member functions to improve encapsulation. I can see the advantages of this. However, a disadvantage in my eyes is the following: I have a custom metadata class for some custom image class, which contains a number of data members. There ar...
You could provide a tuple-like view of Metadata, and have the conversion functions instantiate a std::index_sequence to populate the result; // file Metadata.h class Metadata { // Getters std::string GetDescription() const; std::string GetTimeStamp() const; float GetExposureTimeInMilliSeconds() ...
63,615,344
63,615,505
std::cout Dosen't Print What I Want?
void menuWaterMark() { std::cout << std::endl; std::cout << " __ __ __ ______ __ __" << std::endl; std::cout << "/ | / | / | / \ / | / |" << std::endl; std::cout << "$$ | ______ $$ | __ $$ | __ /$$$$$$ |$$...
You need to escape the \ character: void menuWaterMark() { std::cout << std::endl; std::cout << " __ __ __ ______ __ __" << std::endl; std::cout << "/ | / | / | / \\ / | / |" << std::endl; std::cout << "$$ | ______ ...
63,615,379
63,615,483
Create std::shared_ptr using factory function
I have a class Foo which is not instantiated directly but through a static factory method Foo Foo::create_foo(). Now I want to create a std::shared_ptr<Foo>. Normally I would use auto ptr = std::make_shared<Foo>(); How can I achieve the same while using the factory? I know that I could rewrite create_foo() to directl...
If the Foo class have copy- or rvalue-constructor overloads (implicit or explicit) then you could use it as: auto foo = std::make_shared<Foo>(Foo::create_foo());
63,615,772
63,615,826
Wrong sign conversion when converting IPv4 address to std::array of bytes
I am confused about the following compiler warning that I get when trying to convert the ipv4 address in_addr from struct sockaddr_in which is a uint32_t to a std::array of bytes. std::array<uint8_t, 4> IpAddress; struct in_addr in_addr = {}; const char* addr_str = "168.212.226.204"; if (inet_pton(AF_INET, addr_str, &...
The warning is here: IpAddress[i] = addr[i]; ^^^ Since i is an int, but the operator [] of std::array accepts size_type, you get a warning. You can fix this by simply changing i to be size_t instead of int: for (size_t i = 0; i < 4; i++)
63,615,895
63,616,232
boost_chrono_FOUND to FALSE so package "boost_chrono" is considered to be NOT FOUND
I am trying to build ripple by following the build guide on GitHub, but boost is continuously throwing some unknown error. Boost is installed and running. I installed boost_1_71_0 as described by the build guide. /home/usman/Downloads/clion-2020.1.2/bin/cmake/linux/bin/cmake -DCMAKE_BUILD_TYPE=Debug -G "CodeBlocks - Un...
There is a similar question here, but your issue appears to be the opposite case. The important section of the error is here: No suitable build variant has been found. The following variants have been tried and rejected: * libboost_chrono.so.1.71.0 (shared, Boost_USE_STATIC_LIBS=ON) * libboost_chrono.a (shared runti...
63,615,995
63,617,071
Bit Manipulation in Integer Array
#define SET_BIT(byte, bit) (byte |= (1 << bit)) #define CLEAR_BIT(byte,bit) (byte &= ~(1 << bit)) uint8_t data [5]; for (int i = 0; i < 5; ++i) { for(int j = 7; j >= 0; --j) { if (some condition) --> CLEAR_BIT(data[i],j); else if (some conditi...
Because you use define the line SET_BIT(data[i],j) is being replaces during pre-processing with data[i] |= (1 << j) (consider using inline instead and have the benefit of type safety). The best way to understand is to make an example of a simple case (avoid these nested loops). (lets assume you're data array is initial...
63,616,337
63,616,482
How to create an alias for a nested structure in C++?
I can't create an alias for a nested structure in C++. Assume that we have this code below. Now, how to create an alias for struct Score using typedef or etc? struct Information { struct Score { struct Score *link; float src; } *src; };
If struct Score only is declared inside struct Information, you won't be able to use it as its own entity. So break it out. struct Score { struct Score *link; float src; }; struct Information { struct Score *src; };
63,616,523
63,616,643
C++ return object member variable when object is called?
How do you make a class for example return a member variable when it is called? Say: class Person { std::string name; // Constructor and Destructor go here.. }; Person mike = "Mike"; // /!\ How do you make "mike" return "Mike" directly when the object mike is called? // This is the same thing like an int re...
You're looking for a conversion operator, which is written like this: class Person { std::string name; public: Person(char const * name) : name(name) {} operator std::string () const { return name; } }; Here's a demo. You could also make the conversion operator a template, like this: template<typename T> ...
63,616,533
63,619,011
Is HelloWindow object deleted?
I created a sample GTKMM project on GNOME Builder. The great thing was that a sample hello world code was automatically generated for my sample project. Since C++ source files are organized into three parts: Header file Implementation file Main file I've modified my sample code in a single cpp file for demonstration:...
Chances are there is an intentional leak, but it's "controlled". The author knows that this method will be called only once. The author also knows the memory needs to be active the entire lifetime of the application. When the application closes, that memory will be freed one way or another (albeit the destructor will n...
63,616,709
63,617,380
Incomplete type `std::variant<...>` used in nested name specifier
I wrote the following code into a file named main.cpp. It involves the curiously recurring template pattern (CRTP) with the standard type std::variant. #include <string> #include <variant> #include <vector> template<typename T> struct either { std::vector<T> arg; }; template<typename T> struct maybe_either: std::...
This is basically LWG3052 which I'm trying to address in P2162. maybe_either<T> isn't a specialization of std::variant - it inherits from one. And std::visit is currently underspecified. It's not at all clear what kinds of "variants" are allowed to be visited. libstdc++ implements the original suggested direction in th...
63,616,776
63,617,080
Keyboard event while inputing text
I don't know how to make a function which will catch keyboard events while inputting a text (stdio) (example) catch_events(); // catch events will check if TAB or others keys are pressed while reading text from stdin getline(cin, bash_command); Like a linux shell when we input ec(pressed TAB) it displays all commands ...
You do not have to implement this yourself, this TAB functionality is implemented by libraries like libreadline or libeditline. Both give you a hook that tells you where the cursor is positioned when TAB is pressed.
63,616,812
63,616,976
A function declaration that I do not understand
When looking through an API today I came across some a function declaration that looks alien to me. GLAPI void GLAPIENTRY glColor3b (GLbyte red, GLbyte green, GLbyte blue); How should the first 3 tokens be interpreted? I did not know what to google on this one...
GLAPI and GLAPIENTRY are going to be macros. They are going to expand to platform specific tokens that describe how the symbol is mangled, what the calling convention is (if not the default), and how the symbol should be found (statically or dynamically). OpenGL uses macros like this because the same header file works...
63,617,179
63,617,599
strcmp - expected primary-expression before ‘[’ token
In my main code i have a operation where i want to to compare a certain character of a string "word[i]" with a latin letter "b". Obviously i tried to use " word[i] == "b" " but got an error. After a bit of research i found out that in C++ " word[i] == "b" " compares two pointers. It was suggested that one should use st...
Obviously i tried to use " word[i] == "b" " but got an error The expression word[i] (according to the presented program it seems you mean test[i] == "b"or more precisely test[0] == "a") has the type char while the string literal "b" has the type const char *. So the compiler issues an error because the types are inco...
63,617,326
63,617,960
How Python Pandas can read C++ struct binary from command line
I have a std::vector of a custom struct called SomeData: struct SomeData { float a; bool b; int c; }; I write this data to file in binary by reinterpet_cast-ing the object to bytes: myfile.write(reinterpret_cast<const SomeData*>(&obj), sizeof(obj)); A Python user wants to load this data in to Pandas from ...
I suggest you switch to a serialization format that is self-describing, such as AVRO. That puts the burden only on the C++ program; your Python code just receives a list of objects. It may seem heavy-handed now, but it will save you time and pain later on.
63,617,780
63,618,354
why it isn't possible to sort a std::map directly using std::sort based upon its value field
I've already seen lot of solutions for sorting a std::map based on its value. But I want to know why it's not possible to sort it directly using std::sort like the code I've written. #include <iostream> #include <map> #include <algorithm> void print_values(const std::map<size_t, size_t>& map_data) { for(const aut...
The map itself is always sorted by key. So you can only sort some other thing, that could refer to map elements. You could sort an array of map iterators: std::vector<decltype(coins_count)::iterator> vec; for (auto i = coins_count.begin(), end = coins_count.end(); i != end; ++i) { vec.push_back(i); } std::sort(vec....
63,617,881
63,620,291
Merge Sort | C++ - Segmentation Fault
I thought I'd revise my concepts by coding some basic DS and Algos. After a great pace, I am kinda stuck now and not being able to identify my mistake. I am getting a Segmentation Fault in the below code result. Any help would be great! #include<bits/stdc++.h> using namespace std; void merge(int *arr, int s, int m, in...
The segmentation error is because you have an infinite recursion loop. There were some problems with the indices and one typo where you meant n2 but wrote n1. #include <iostream> using namespace std; void merge(int *arr, int s, int m, int e){ int n1 = m-s+1, n2 = e-m; int L[n1], R[n2]; for(int i=0; i<n1;...
63,618,645
63,618,808
I am unable to print out the value 201703L for _cplusplus macro for g++
I am trying to get my compiler to use c++ version 17. Here is the code snippet I am using to check if I can compile using c++17 with my g++ compiler. #include<iostream> int main() { if (__cplusplus == 201703L) std::cout << "C++17\n"; // ??? else if (__cplusplus == 201402L) std::cout << "C++14\n"; else if ...
Important part from the output that you quote: Conform to the ISO 2017(?) C++ draft standard (experimental and incomplete support) You are using a compiler which does not support C++17 entirely. The compiler was released in 2015, way before C++17 was finalised. [__cplusplus] prints out 201500 In that case __cpluspl...
63,619,304
63,619,614
What's the best way to express concept requirements for data members in a concept?
what's the best way to define a concept with a nested concept requirements for a data member of the type? Something along these lines: template<typename T> concept MyConcept = requires(T a) { {a.something} -> std::integral; }; This doesn't work because a.something is picked up as a reference (delctype((a.somet...
The downside of copy is that it can create false positives for you. A reference member will decay to a value. The only way to ensure the actual type of the member is analyzed, is to write an explicit nested requirement. template<typename T> concept MyConcept = requires(T a) { requires std::integral<decltype(a.s...
63,619,421
63,619,899
Why is const auto not working with trailing return type? (Error C3551 in Visual Studio)
Description of the error code: if a trailing return type is used then the leading return type shall be the single type-specifier 'auto' (not 'const auto') Basically, this code snippet does not work: const auto begin() const -> decltype(_data.begin()) { return _data.begin(); } May I please know why this does not work...
In a function where the return type is specified after the parameters, auto is not a type specifier. It's just a token that tells the parser to start parsing a function (kinda). However, const auto is a type placeholder for the return type of the function. That is, if you start a function declaration with const auto, y...
63,619,444
63,624,139
Is reintrepret_cast to char* well defined when the char array is modified?
Consider the following example when receiving an expected message from a socket: struct myData { uint8_t type; int value; } myData readFromSocket(int socketFD) { myData data{}; ssize_t bytes = recv(socketFD, reinterpret_cast<char*>(&data), sizeof(myData), 0); if(bytes == sizeof(myData)) ret...
C++ Standard specifies aliasing rules in [basic.lval]/p8: If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined: . . . — a char, unsigned char, or std​::​byte type. The term access is specified in [defns.access]: ⟨execution-...
63,619,788
63,621,517
Issues while trying to define a class within a namespace (allocation of incomplete type)
I am trying to create a class in Qt within the Ui namespace. In my name space I already have 2 classes made with Qt Designer, and using it as reference did not help me solve my problem. In myclass.h I put namespace Ui {class MyClass}; class MyClass : public QObject {Q_OBJECT private: Ui::MyClass* ui; //body } An...
This doesn't look like a Qt issue. It's just C++. To define a class in a namespace, just put the declaration within the namespace: namespace Ui { class MyClass : public QObject { Q_OBJECT private: MyClass* ui; }; // MyClass } // Ui
63,619,945
63,622,876
Formatting for windows structures
Having some trouble using fmt lib to create a formatter to print some Windows structures in my code. I've prepared a basic example below. The purpose is to be able to print a large structure out in a pre-structured manner, and only print what I want out of it, but I dont quite understand the errors im getting. #include...
One problem is that you are trying to pass a pointer to _SECURITY_LOGON_SESSION_DATA instead of a (const) reference to it. It should be: fmt::print(L"LogonSession Data\n{}\n", *pData); Same in the formatter::format method. Another problem is that your formatter doesn't support wchar_t, it should be: template <typename...
63,620,091
63,620,153
How can I specialise a template function designed to return different types?
I currently have a function template that reads a string obtained from a configuration file and creates and returns a shared pointer to a new instance of a derived class: template <typename T> std::shared_ptr<T> foo(std::string& info) { /* */ } I would like to specialise this when I return a particular class, because ...
You just need to supply the template argument after the identifier. Your last attempt was close but the template argument is Derived not std::shared_ptr<Derived> : template <> std::shared_ptr<Derived> foo<Derived>(std::string& info) // Add the template argument here ^^^^^^^ Simplified example : https://godbolt....
63,620,120
63,758,352
Extract type from variadic template class for member function overloading
I would like to have a function overload for each type of a variadic template class. Is that possible ? template<typename ...args> class Example { virtual void doSomething(args(0) arg) { ... } virtual void doSomething(args(1) arg) { ... } /// etc... implementations are the same, but I need access to the ty...
You can derive the class from a templated pack of instantiations of a base class template that defines one virtual function with its single template parameter as the function parameter type. The derived class then holds the function overloads for each template argument type, that are all virtual. template<typename arg>...
63,620,319
63,621,172
How to use a vector variants as key in unordered_map?
How can I use a vector of variants as the key in unordered_map? For example, I'd like to make the following code work. using VariantType = std::variant<int, std::string, unsigned int>; using VecVariantType = std::vector<VariantType>; std::unordered_map<VecVariantType, int, $some_hash_function$> m; How do I implement $...
I enjoy a good terrible idea... I have no idea how or why you would use something like this for something other than a "I wonder if I can get this to compile and run" example. #include <iostream> #include <vector> #include <unordered_map> #include <variant> using VariantType = std::variant<int, std::string, unsigned i...
63,620,677
63,621,891
how to link object file of different directory using cmd?
I am using windows and mingw. this is my program looks like helloworld |---include | |---header1 | |---headerA.cpp | |---headerA.h | |---headerA.o |---main.cpp |---main.o I included header#include"header1/headerA.h" successfully by commamd: g++ -c main.cpp -I.\include but when I tried to link main....
As per gcc documentation, -I flag is used to pass include directories where compiler will look for headers. Your error is a linker error instead. This means that you compiled your translation unit correctly, but when linker tried to resolve symbols, it could not find the definitions. Headers contain only the declaratio...
63,620,717
63,622,067
Is it possible to reserve and copy into a std::string directly?
Is it possible to reserve space in a std::string and get a pointer to copy char data directly into it? I have to interface with a C library that returns strings by copying them into a char *. How can I set up a std::string so that the library can write directly into it, avoiding intermediate copies. Hypothetical exampl...
Is it possible to reserve space in a std::string and get a pointer to copy char data directly into it? Yes. Use its resize() method to allocate the memory, and then use its data() method (C++17 and later), or its operator[], to access that memory. I have to interface with a C library that returns strings by copying...
63,620,842
63,620,923
C++ virtual function call by value
I attempt to modify the vfptr of a Base object to point to vtable which class Derived owns: #include<iostream> using namespace std; class Base { public: virtual void func() { cout << "Base::func()" << endl; } Base() = default; Base(const Base&); }; Base::Base(const Base&b) { *((int*)(this)) = *((int*)(&...
I wonder if the compiler handles such value-call by static binding Base b = d; b.func(); Yes, it does do static binding here indeed. In fact, using dynamic binding would be pointless because the dynamic type of the object is known to be the same as the static type at compile time.
63,620,862
63,627,936
Using file as a mutex with CreateFile()
I've been given a task to create 2 processes. First one opens a file "log.txt" and adds the input given by user to it. The second process is meant to be a "monitor" of that file. It checks if it exists, gives its size and gives the number of characters entered by user since the start of the second process. I'm using th...
FILE_SHARE_WRITE | FILE_SHARE_READ will allow other processes to open and share the read and write access. You need to open the file exclusively (with dwShareMode = 0), but this requires process2 to try to open the file exclusively in a loop. Instead, use CreateMutex to create a mutex, then process1 uses WaitForSingleO...
63,620,894
63,623,562
Is there a Macro for a Function Pointer? UE4 C++
I made a function pointer in ue4 c++ and dont know which macro i can/should use for the pointer in the header file. (things like UPROPERTY() or UFUNCTION()) why i even want to use a macro? Because of the garbage collection and, as far as i know, the gb only works when the variable/function has a macro. btw, is a functi...
Functions and your function pointer are not allocated and deallocated so you don't need the garbage collector in this case, and thus you don't need any UE4 macro (...if you only consider the garbage collector). As for performance, the function pointer is most probably slightly less performant as it adds one more variab...
63,621,067
63,621,737
How to use functor as custom comparator in priority_queue
I am trying to create a functor as custom comparator for my priority_queue which takes in an unordered_map as a parameter for constructor. I am not sure how to call the functor when declaring the priority_queue as I am getting the error: "Line 22: Char 48: error: template argument for template type parameter must be a ...
TL;DR version: priority_queue<string, vector<string>, compareWords> pq(compareWords{wordFreq}); How we got there: With the trivial solution, pass the comparator into pq's constructor, you encounter the Most Vexing Parse and priority_queue<string, vector<string>, compareWords> pq(compareWords(wordFreq)); ...