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
68,493,938
68,494,253
Confusion about operator precedence in c++
I'm learning c++ and currently learning about operator precedence. I'm playing with the following examples. Imagine each piece as distinct pieces of code run at separate times, not multiple code blocks within the same method. int b = 4; int result = ++b; // In the above example the result will be 5, as expected. int ...
It's undefined behaviour, violating sequence rules. Between the previous and next sequence points a scalar object must have its stored value modified at most once by the evaluation of an expression, otherwise the behavior is undefined. int b = 4; int result = ++b + ++b;
68,494,020
68,517,639
Drawing to Multiple Windows Using Vulkan
I am trying to create an application that could dynamically create additional windows. Each window will be drawn to using Vulkan and I know that this means that each window will have to contain it's own SwapChain resources (image views, framebuffers, etc.) and graphics pipeline (as it is references the swap chain's ext...
On Windows you could largely assume everything can render to everything. But use you should check that is so anyway. vkGetPhysicalDeviceWin32PresentationSupportKHR does not need surface, and gives a strong hint that the device\queue is a presentation able, and not e.g. compute accelerator or something. Similarly while...
68,494,156
68,494,527
Overriding pure virtual functions
I've been trying to figure out why I get an error when I try to build this code in QTCreator. I found some other posts similar to this but I think I have a similar but different issue. In main.cpp I basically have some Filter (a templated struct with a pure virtual function) that I'm creating that returns to me a vecto...
Your compiler tells you where the error occurs. /Users/marcokok/Qt-workspace/Open_Closed_Principle/main.cpp:112:36: error: allocating an object of abstract class type 'Specification<MyProduct>' AndSpecification<MyProduct> as(cs, ss); ^ The attempt to instantiate Specification<MyP...
68,495,089
68,495,177
for some reason I keep getting this error: no match for 'operator>>' (operand types are 'std::istream' {aka 'std::basic_istream<char>'}
i keep getting this error: C:\Users\Owner\Downloadss tl\madlibsgame\main.cpp|69|error: no match for 'operator>>' (operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'})| whenever I run the program, im using codeblocks btw it seems line 69...
Haven't read the logic, but the problem is in line cin >> getmode. In place of getmode should be lvalue reference, but you passed function name. This int main() will fix the compile error. int main() { int x; cin >> x; getmode(x); } P.S. change your code to make it at least readable
68,495,110
68,501,604
Debugging code to write last digit of sum of squares of n fibonacci numbers
I'm using the convention F_0 = 0, F_1 = 1 and so on, where F_n is a fibonacci number. I've written code for finding the last digit of the sum of squares of n fibonacci numbers. It gives the correct answer for n<60. n = 60 onwards it gives wrong answer. Could someone please help? #include<iostream> using namespace std;...
Consider the function that calculates the last digit of the squares of the Fibonacci numbers: long long fib_last_sq (long long n) { if (n<=1) { return n; // ^ If n == 0, 0 is returned, here. } n = n % PISANO_PERIOD; // If n is a multiple of 60, now n becomes 0... long lon...
68,495,121
68,495,700
How can i print the mirrored left inverted number pattern in c++?
This is the code I tried but I need a pattern like this: 1 2 3 4 2 3 4 3 4 4 Please help me with the code. #include <iostream> using namespace std; int main() { int rows; cout << "Enter number of rows: "; cin >> rows; for(int i = rows; i >= 1; --i) { for(int j = 1; j <= i; ++...
we should know that the space of each line from left increases frequently.you did not choose loops start and end correctly.outer loop must start from 1 to rows and inner loop must start from index of outer loop to rows.as we see the space of each line increases and first line has no space , so we define a variable name...
68,495,344
68,495,465
Bit field initialization in C++20 with `|| new int` construction
I came across the page about C++20 bit field initialization https://en.cppreference.com/w/cpp/language/bit_field#Cpp20_Default_member_initializers_for_bit_fields , where for C++20 the following example present (simplified here): struct S { int z : 1 || new int { 0 }; }; The page does not explain the construction |...
There are two ways to parse this declaration: int z : (1 || new int) { 0 }; int z : (1 || new int { 0 }); where everything inside () is interpreted as the size specifier. Since "the longest sequence of tokens that forms a valid size is chosen" as indicated by cppreference, the second alternative is assumed. There...
68,495,411
68,495,509
What does this warning mean in C++ for exception handling?
I have written a code for exception handling for division operation: I had include the Zero division error, Negative value error (Not an exception but I included it!) and Indeterminate form error (I included it also). Then after compilation it shows some warnings, but the .exe file is running as expected. Here is the c...
A stripped down version of your code that triggers the same warning is this: #include <iostream> #include <stdexcept> int main() { int numerator = -1, denominator = -1; try { if (numerator < 0 || denominator < 0) { throw std::invalid_argument("Invalid Arguments: Negative...
68,496,313
68,496,355
Why doesn't the push_back function accept the value/parameter?
I am trying to store some specific characters of a string in a vector. When I want to push back the characters though, there is a problem with the value and I do not know why. Going over the cpp reference page didn't help me unfortunately. Could someone please help? Here is the code: int main() { std::string str1 =...
Vector needs to be of type char, not string.
68,496,608
68,502,748
How random32_unbiased function works in Monero's Schnorr signiture algorithm
In the Zero to Monero book, I am reading about Schnorr signatures. Section 2.3.4 references the random32_unbiased() function from src/crypto/crypto.cpp of the codebase. My understsanding is that this function generates a random integer between 1 and l-1 (both inclusive), where l is a large integer. That function is: vo...
Monero uses edwards25519 as the underlying elliptic curve which it uses to produce EdDSA (Edwards digital signatures), to create transactions on the Monero blockchain. edwards25519 is a curve which is of composite order, that is, it's not a prime order curve like secp256k1, which is used by Bitcoin. Owing to this fact,...
68,497,175
68,497,512
c++ Integer overflow in spite of using unsigned int and modulo operations
int orders=1000000000; int mod=pow(10,9)+7; unsigned int total=4294967295; total=(orders*(orders+1))%mod; total/=2; return total; expected Answer= 21 BUT getting runtime error: signed integer overflow: 1000000000 * 1000000001 cannot be represented in type 'in...
Basically problem is you have integer overflow just after multiplication. To overcome this problem you have to approach topic using one of two solutions. use integer type which can hold a result of such magnitude, for example: unsigned long long int use algorithm which is able to do that calculation without integer ov...
68,497,811
68,763,295
Is there any way to avoid fully-specified class-names in a header without namespace pollution?
We have a lot of classes not in any namespace, which use std extensively. e.g.: class MyClass { std::map<std::string,std::vector<std::string>> mLookup ... This is tedious but because it's a header I cannot just do using namespace std; or I will cause awful pollution. Neither can I (I think) move this class into a new ...
From looking further the short answer is: NO. You can employ using a::b::c within methods or functions defined in header files and you can of course use namespaces in your .cpp files, but there is no way to do this in a header without polluting the codebase. The proper way is to move things into namespaces but the ques...
68,498,167
68,498,303
C++ glfw Error: 'GLFW/glfw3.h' file not found
I'm new to Vulkan and trying to recreate what the tutorial from the webpage showed me, i'm using VS Code and the error showed up when trying to compile, it showed that GLFW/glfw3.h not found even though i include it to my project in the includePath in the c_cpp_properties.json. { "configurations": [ { ...
What you're doing is with c_cpp_properties.json is only for the IDE / intellisense. You have to pass the include paths to the compiler as well in your tasks.json, because the compiler needs to know about them, too.
68,498,337
68,527,312
PyObject_CallObject is returning NULL when trying to pass an array
I am trying to pass a 2D array from C++ to Python function but the PyObject_CallObject function is returning NULL.This happens in case of 1D array as well. It works fine when I do not pass any argument or in case the argument is just single variable and not an array. My code is as follows: #include <stdio.h> #include <...
PyObject_CallObject takes a callable and a tuple of arguments for the callable, or NULL for no arguments. You're trying to pass it a NumPy array instead of an argument tuple.
68,498,382
68,499,022
Is it legal to delete copy/move functions of a Coroutine in C++20 and instantiate it?
I have noticed that the following code is both accepted by MSVC and GCC (shortened TLDR version below): template<typename T> struct Generator { struct promise_type { std::suspend_always initial_suspend() { return {}; } std::suspend_always final_suspend() noexcept { re...
I believe the Generator object is retrieved through a call to get_return_object(), which returns a prvalue. This, as of C++17, requires mandatory copy elision. See cppreference.com: Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/m...
68,498,596
68,808,476
Program execution continues after procdump created a dump on an exception
I am throwing an exception throw std::exception("dummy") (as a test) which is not being caught anywhere. Without ProcDump attached this immediately crashes the process as it should. When I attach ProcDump with -e to a debug build, ProcDump properly detects the unhandled exception, creates a crash dump, and exits. But t...
I don't have a good answer, unfortunately. It looks that there is a bug in procdump. You may report it on the Sysinternals forum or contact Mark Russinovich (@markrussinovich) or Andrew Richards (@arichardmsft). I can confirm that it happens when you attach to the process, for example, procdump -e prog. It behaves as e...
68,498,616
68,498,732
Getting millisecond or microsecond-accurate boot time in Linux (C/C++)
Does Linux have any way to obtain a milli or microsecond precision time for boot time, for converting boot time-relative timestamps into something like a Unix timestamp? The closest I've found is /proc/uptime (as suggested in places like this answer), but unfortunately this only gets you to 10ms precision best-case. Fo...
Use clock_gettime(CLOCK_BOOTTIME, &ts).
68,499,097
68,499,878
logic behind assign binary literals to an int
Found that logic on a code and don't get the reason behind that; why use it instead of assign normal int? (its a character controller in a 3D environment) // assumes we're not blocked int blocked = 0x00; if ( its_a_floor ) blocked |= 0x01; if ( its_a_wall ) blocked |= 0x02;
0x00 is a "normal int". We are used to base 10 representations, but other than having 10 fingers in total, base 10 is not special. When you use an integer literal in code you can choose between decimal, octal, hexadecimal and binary representation (see here). Don't confuse the value with its representation. 0b01 is the...
68,499,573
68,499,825
Why does this Boost TCP socket work in one method and not in another?
I want to establish a socket connection in one method and use this connection in another method of a class. While in the first method (where I establish the connection) I can read and write from and to the socket as much as I want, in the second method I always get a Bad file descriptor error. Note that I use version 1...
As per the comment sock, io_service and acceptor members of SocketManager are initialized to point to local variables within SocketManager::initialize. When that completes you then have dangling pointers. I don't see any reason to use pointers at all here. Just make them non-pointer data members and initialize them in...
68,500,089
68,500,238
Aggregate initialization in C++
I have a base class Event, from which concrete events derive: struct Event { }; struct CollisionEvent : Event { //CollisionEvent(Entity entityA, Entity entityB) : entityA(entityA), entityB(entityB) {} Entity entityA; Entity entityB; }; this class is a POD, and I should be able to perform aggregate initi...
For aggregate initialization you need to initialize the base class, even if it's empty. eventBus->DispatchEvent<CollisionEvent>(Event{}, mEntities[i], mEntities[j]); There were also some changes regarding what is and what isn't an aggregate in recent standards - until C++17 a class having a base class can't be aggrega...
68,500,368
68,547,179
Encoding agnostic parsing with c++2b
Sometimes I have to parse text files with various encodings, I wonder if the upcoming standard will bring some tools for this because I'm not very happy with my current solution. I'm not even sure if this is the right approach, however I define a functor template to extract a character from stream: #include <string> #i...
In c++17 we gained type-safe unions. These can be used to map between runtime and compile time state together with std::visit. template<auto x> using constant_t = std::integral_constant<std::decay_t<decltype(x)>, x>; template<auto x> constexpr constant_t<x> constant = {}; template<auto...Xs> using variant_enum_t = st...
68,500,733
68,503,022
How does including gtest.h break template argument deduction for a std algorithm?
I upgraded to the latest release of Google Test, and several of my tests no longer compiled. I've reduced it to this: #include <gtest/gtest.h> #include <algorithm> #include <cctype> #include <iostream> #include <string> int main () { const std::string foo = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const auto uppers = s...
It appears that <gtest/gtest.h> is now including <locale>, which introduces template< class charT > bool isupper( charT ch, const locale& loc ) into the scope. That means that std::isupper now has two possible functions it could point to and without you specifying which one to use, you get an ambiguity which causes ...
68,501,130
68,504,252
Curious behaviour of c_str() and strings when passed to class
I came across a curious behaviour (and I am sure it is just curious to me and there exists a perfectly valid c++ answer) when playing around with c-strings and std::string. Typically, when I pass a string to a class' constructor, I do something like this: class Foo { public: Foo(const std::string& bar) bar_(bar) { } ...
As already noted, the problems in the posted code rise from dangling references to temporary objects, either stored as class members or returned and accessed by .c_str(). The first fix is to store actual std::strings as members, not (dangling) references and then write accessor functions returning const references to t...
68,501,427
68,502,152
split string into struct without knowing structure
I have 8 bytes string with flags, some of them are booleans and some are chars. What I want is access that flags by it's names in my code, like myStruct.value1 I created some struct according to my wishes. I would expect I can split the string into that struct as both have size of 64 bits in total. // destination typed...
memcpy expects its first two arguments to be pointers. Arrays like your buf will implicitly decay to pointers, but your type myStruct_t will not. myStruct_t myStruct; memcpy(&myStruct, buf, 8); // ^ produces a POINTER to myStruct
68,502,197
68,503,110
How do "omp single" and "omp task" provide parallelism?
I am confused about omp single and omp task directives. I have read several examples which use both of them. The following example shows how to use the task construct to process elements of a linked list. 1 #pragma omp parallel 2 { 3 #pragma omp single 4 { 5 for(node* p = head; p; p = p->next) 6 ...
Adding to the other answers, let me dig a bit deeper into what happens during execution. 1 #pragma omp parallel 2 { 3 #pragma omp single 4 { 5 for(node* p = head; p; p = p->next) 6 { 7 #pragma omp task 8 process(p); 9 } 10 } // barrier of single const...
68,503,307
68,503,527
Extract diagonal of a matrix
I am exercising using the std of C++ for school and I would like to find a way to extract the diagonal of a matrix with std::copy. This is what I came out with but it is giving me a segmentation fault error. What am I doing wrong? Is there maybe a more C++ way to do this without using for loops? Thank you #include<vect...
The reason you're getting a segmentation fault is because of the way you're using copy, which you're giving invalid parameters. There's not really a way to iterate through a 2D array or vector diagonally (although if you are using a 2D array (not a vector), you can give it a start and end point diagonal from one anothe...
68,503,341
68,512,572
Dynamic Eigen Matrix Random Initialization
I have a vector<MatrixXf*> called weights. In the loop, a new MatrixXf is allocated, pointer pushed to the vector, and meant to be initialized to random values. However, I want to avoid setRandom() in favor of my He distribution. The uncommented code below works as-is, but it feels very clunky to create a 'local' matri...
You could use a vector of shared pointers: #include <memory> ... vector<shared_ptr<Matrix>> weights; ... Matrix m = Eigen::MatrixXf::NullaryExpr(c, p, he); weights.push_back(make_shared<Matrix>(m)); Perhaps one could criticize that this approach is syntactic sugar that doesn't change much in the inner workings of the ...
68,503,586
68,507,395
Using openMP to parallelize a loop over a vector c++ objects
I'm trying to increase the performance of a c++ code using openMP but am not seeing very good scaling. Before delving into the details of my code, I have a very general question that I think could save a lot of time if I can get a definitive answer to it. The basic structure of the code is a vector of objects (let's sa...
The speed of your program mainly depends on the speed of memory read/write (including cache utilization,etc). Depending on the hardware you may or may not observe speed increase. For more details please read e.g. this. On my laptop (i7-8550U, g++ -fopenmp -O3 -mavx2 saxpy.cpp) I got similar result, but on a Xeon server...
68,503,738
68,503,793
append a rvalue vector to a vector in O(1) time
I was wondering how to append the rvalue vector in constant time (O(1)) to another vector. I know methods by using std::insert and std::move, but is there any method to append a std::vector<T>&& to std::vector<T>& in O(1) time.
Why would being an rvalue matter at all to this? Big-O notation counts the number of operations done in a process. Whether those operations are copy or move, if the number of operations performed is directly proportional to the number of items in the source list, then it is an O(n) process. And if you're going to copy/...
68,503,851
68,511,313
TIdTCPServer sharing of serial port
Recently I changed a program which acts as a TCP server to help share the traffic on a serial port connected to a device. Multiple clients connect and should have access to the Serial Port and act simultaneously. Application is built using C++Builder, using TIdTCPServer in the server and TIdTCPClient in the client appl...
TIdTCPServer is a multi-threaded component. Each connected client runs in its own independent thread. The OnExecute event runs in those threads. So, it is your responsibility to make sure your OnExecute code is thread-safe, by serializing access to any shared resources. You are using a mutex inside of ProcessSerialMess...
68,504,025
68,504,284
C++ How to pass lambda [&]() as an argument for void (*draw)()
I have a method which takes a void function as an argument. Like so, void update(void (*draw)()); inside main how will I pass a lambda which could take an out-scope variable to be passed to update? it works if I do it like this Player player(20, 20); void drawFace(){ player.draw(); } int main() { myClass.upda...
Using std::function<void()> in declaring the argument solves the problem. instead of defining update void update(void (*draw)()); Use it like this solves the issue void update(std::function<void()>draw); Now I can pass either function or lambda to it and both will works out of the box. Works! Player player(20...
68,504,044
68,504,551
Wrong output when using stl map application in arrays
Here is my code, I am using an array instead of a map to check if the element is repeated or not, and then I'm adding the corresponding values of indexes at which the element is present, in the vector , but every time it is returning 0. class Solution{ public: //Function to return the position of the first repe...
One of the first things to note is your if statement syntax. In c++ if it is more than 1 line long you must encapsulate it with {}. So for this section: if(a[arr[i]]==-1) a[arr[i]]=i+1; v[i]=a[arr[i]]; It is always going to execute v[i] regardless of what the if evaluates to. So if(some condition){ //lines ...
68,504,051
68,504,140
C++ project not compiling, errors are in previously functioning third party header file that also has nothing to do with the changes
Are there any tips/guidelines/recommended routes to go, when trying to figure out why something like this is happening? I'm using Visual Studio 2019, I've tried cleaning, rebuilding, restarting VS 2019. Nothing is working. My coworker is using the same branch as me and it works on their machine. When I checkout the bra...
In my experience, syntax error: 'constant' on MSVC is almost always some mysterious Windows macro that #defines a common identifier to some literal value. For example, I wouldn't be surprised if in some Windows header there exists something like #define MIN_PRIORITY 0, which would cause your first line to turn into sta...
68,504,978
68,507,064
RcppEigen #define works when using sourceCpp() but ignored with R CMD build
I've noticed that sourceCpp() respects C++ #define while devtools::document() and R CMD build seems to disregard them, at least in the case of Eigen matrix initialization. Consider this .cpp file: #define EIGEN_INITIALIZE_MATRICES_BY_ZERO //[[Rcpp::depends(RcppEigen)]] #include <RcppEigen.h> //[[Rcpp::export]] Eigen:...
I think, to be used in a package, you need to add -DEIGEN_INITIALIZE_MATRICES_BY_ZERO to src/Makevars, e.g. as in https://github.com/privefl/bigstatsr/blob/master/src/Makevars#L2 (there are 2 flags for armadillo there). Or maybe just a problem of ordering? Try putting the #define after #include <RcppEigen.h>.
68,505,162
68,505,347
Is the method overridden or overloaded?
We have two classes. class A{ public: void fun(){ cout<<"Parent\n"; } }; class B:public A{ public: void fun(){ cout<<"Child\n"; } }; I am trying to figure out if the function fun() will be considered overloaded or overridden. I tried using the override keyword and it says that the method is not overr...
B::fun neither overloads nor overrides A::fun. It hides it. It's not an override because you can still get the A::fun behavior on a B by treating it as an A B x; A &y = x; y.fun(); // outputs Parent When you try to access the fun method through the A interface, you get the Parent behavior. Were A::fun declared virtual...
68,505,381
68,505,466
How does the wait() call get invoked with notify in this code?
I have a c++ code as follows that uses condition-variable for synchronization. #include <iostream> #include <condition_variable> int n = 4; enum class Turn { FOO, BAR }; Turn turn = Turn::FOO; std::mutex mut; std::condition_variable cv; void foo() { for (int i = 0; i < n; i++) { std::unique_lock<std::mu...
How would the cv.wait inside the foo() get triggered in the beginning? It would be triggered by the predicate evaluating to true. The equivalent loop: while (!pred()) { wait(lock); } would not call wait() even once (the first time that line of code is visited, anyway).
68,506,276
68,506,691
Overload C++ template class method by it's template classes
I am writing a template class that manages a union of 2 classes. All the functions are pretty simple except the Get() functions. It looks like this: UnionPair.hpp template <class First, class Second> class UnionPair { public: UnionPair() : state_(State::kEmpty){}; ~UnionPair(){}; void Reset(); void Set(std::...
First off, you can't split template code into separate .h and .cpp files: Why can templates only be implemented in the header file? Second, a union's data is not set until runtime, so there is no way for the compiler to validate the template parameter of Get() at compile-time, at least not the way you want. It is poss...
68,506,357
68,508,510
Cython not compiling void function - "empty declarator"
I have a very simple c++ class defined in foo.cpp: class Foo { int x; public: Foo() {} Foo(int _x) : x ( _x ) {} int getX() { return x; } void print() { std::cout << "Foo { " << x << "}" << std::endl; } }; In trying to wrap it with cython, I create foo.pxd with the following dec...
The problem isn't that print is a built-in function. That's fine. You can override the names of built-in functions with no problem. list = 1 # perfectly valid code; (but may confuse future users) The problem is that print is a built-in keyword. This is because Cython defaults of Python 2 syntax when reading .pyx (fo...
68,506,798
68,506,824
Converting struct headers to and from vec<char>
I am trying to pack a message buffer vector with smaller messages of char* interleaved along with their respective headers. These headers are cast as char* from a struct. A receiver unpacks the buffers by jumping from header to header. Using the header, they can identify the size of the corresponding message and at whi...
With every iteration, you increment step by the size of the current packet. It is an index into stream of where the next packet starts. However, you add to bitr this index, resulting in Undefined Behavior because bitr has been increased past the end of the buffer. What you get is: start of 1st loop: bitr = 0 start of 2...
68,506,926
68,507,628
How does vector class takes multiple argument and create a array out of it?
vector example vector<int> a{ 1,3,2 }; // initialize vectors directly from elements for (auto example : a) { cout << example << " "; // print 1 5 46 89 } MinHeap<int> p{ 1,5,6,8 }; // i want to do the same with my custom class Any idea how to do accept multiple arguments in curly braces and form an array?...
Any idea how to do accept multiple arguments in curly braces [...] It is called list initialization. You need to write a constructor which accepts the std::initilizer_list (as @Retired Ninja mentioned in the comments) as argument, so-that it can be achieved in your MinHeap class. That means you need something like as...
68,506,943
68,507,736
Enforcing templated base-class types with mixins
I have the following (not meant to compile, but to illustrate the concept efficiently) class abstract_mixin { ... } template<class X> class concrete_mixin_A : public abstract_mixin, public X { ... } Here, abstract_mixin defines a family of mixins, and concrete_mixin_A is one member of that family (there will be _B, _...
Yes it is possible. template <template <class> class A, class B> void mixin_checker(const A<B>&) requires (std::is_base_of_v<abstract_mixin, A<B>> && std::is_base_of_v<abstract_mixin_compat, B>) {} template <class T> concept my_mixin = requires(T t) { mixin_checker(t); }; templa...
68,506,945
68,506,977
remove the path from the received
hey so i made this real quick : std::string ProcessIdToName(DWORD processId) { std::string ret; HANDLE handle = OpenProcess( PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processId /* This is the PID, you can find one from windows task manager */ ); if (handle) { DWORD bu...
Supposing that using Windows API is allowed, you can use PathFindFileNameA function. #include <shlwapi.h> std::string ProcessIdToName(DWORD processId) { std::string ret; // omit: same as original code return PathFindFileNameA(ret.c_str()); }
68,507,264
68,508,857
How can I change a class element via QLineEdit in QT?
I'm new to QT and trying to practice. It came to signals and slots. I'll get to the point. I have a User class: (User.h) class User : public QObject { Q_OBJECT public: static int counter; explicit User(QObject *parent = nullptr); ~User(); QString getName(); QString getPassword(); int getAge...
connect(ui.login, &QLineEdit::text, this, &QtWidgetsApplication::inputUserName); connect(ui.password, &QLineEdit::text, this, &QtWidgetsApplication::inputPassword); First, text is not QLineEdit's signal. QObject::connect(ui.login, &QLineEdit::textChanged, &user, &User::setName); void setName(QString name); void setPas...
68,507,329
68,507,573
reading non-text file in c++
I open the mp3 file by mistake with notepad++ ( Open with ) and show the entire file in text inside the notepad it was so cool. since I am learning c++ again, I told myself let write a program that opens any file inside the console and display their content on the console so I begin my code like this : int readAndWrite...
Like all other non-text files, mp3 files don't contain lines so you shouldn't use std::getline. Use istream::read and ostream::write. You can use istream::gcount to check how many characters that was actually read. Since you are dealing with non-text files, also open the files in binary mode. You should also test if op...
68,507,435
68,507,492
round() function displaying scientific notation in c++
I'm writing a C++ code that divides two floats and outputs a whole number. but when I try dividing and rounding off using the round() function the number I get: 8878323 / 5 = 1.77566e+06 Every other number is being outputted as a whole number. Not sure why this one isn't. code: #include <iostream> #include <cmath>...
It's just a precision issue with cout. Pretty much any sufficiently large float will generate this issue. Try this: Add #include <iomanip> to the top of your program. Then adjust your cout statement to use a setprecision specifier: cout << setprecision(15) << ans[i] << " "; Alternatively, you could simply cast the r...
68,507,445
68,507,526
Function template overloading and ambiguity
The code is taken from Partial template function specialization with enable_if: make default implementation . I was expecting the call to dummy(5) to be ambiguous between the "Generic" and the "Integral" overloads as T is deduced as int in both cases. The second parameter resolves to void in both cases. Aren't they equ...
The "Integral" overload can't be called because the 2nd template argument can't be inferred. (Note that typename std::enable_if<std::is_integral<T>::value>::type is trying to decalre a non-type template parameter with type void when T is integer type, which is invalid.) If you change the type to pointer (as non-type te...
68,508,042
68,522,966
Library compile time settings mismatch when linking spdlog from conan using CMake/VS2019?
I'm trying to add spdlog 1.9.0 to my CMake project, and for this project I'm using VS2019's new CMake-based project system for building/running it. When I include spdlog in my implementation using a very simple invocation, I get a linker error when I try to build. #include <spdlog/spdlog.h> App::App() : m_win(0) {...
When you do the conan install to install dependencies, you will see the "profile" being used to install binaries, including settings like build_type, compiler.version, etc. something like this: Configuration: [settings] arch=x86_64 arch_build=x86_64 build_type=Release compiler=Visual Studio compiler.runtime=MD compiler...
68,508,224
68,513,494
Getting [e][wifigeneric.cpp:739] hostbyname(): dns failed when performing POST request
I am getting started with electronics and microcontrollers programming. I have made a simple circuit where I use DHT22 sensor to measure temperature and humidity. I have also made my own API in Node and Express (MongoDB as a database). It is very simple API, just two endpoints: one for getting. and one for posting data...
You're calling the begin() method on http with two arguments, which are meant to be a hostname and a port number (and optionally a URI/path). Instead of passing a hostname, you're passing a full URL, which the HTTP client is attempting to resolve as a hostname. The single argument form of http.begin() does take a URL. ...
68,508,240
68,508,281
OpenMP - expect data race situation but did not actually occur
I write the following code and I expect that the data race would occur because of several thread may modify a at the same time and get a wrong answer. // test.c #include <stdio.h> #include <stdlib.h> int main(void) { int a = 0; #pragma omp paralle for for (int i = 0; i < 10000000; i++) { a = a + 1...
You've written #pragma omp paralle for when you meant #pragma omp parallel for (notice parallel instead of paralle). If you fix this then you'll see your data race.
68,508,480
68,508,623
undeclared identifier / c++
I am trying to solve this simple problem in C++ (complier: Visual Studio). The result should be the smallest and largest sum you can make with the elements of a given vector, but always excluding one element when getting the sum. My solution was to make all the sums, put them in a vector, sort them and then show the fi...
I checked your program with Visual Studio. It compiles. Please try to select the commands "Clean Solution" from the build menu and then "Rebuild Solution" Maybe that will help you. Additionally: But when you run your program, exceptions will be thrown. This, because in Visual Studios default debug modus, out-of-bounds ...
68,508,558
68,508,987
How to emulate structured binding init-capture in lambda C++?
Is there any equivalent to structured binding inside the init-capture list in lambda? I know this is invalid, but is there any way to declare 'i' and 's' without declaring outside of the lambda? std::pair<int, std::string> p { 1, "two" }; auto f = [[i, s] = p] mutable -> std::pair<int, std::string> { ++i; s += '_'...
There is no syntax that directly does that. You can copy the pair and use a structured binding inside the lambda: auto f = [p]() mutable { auto& [i, s] = p; ++i; s += '_'; return std::make_pair(i, s); }; (Note that the omission of () in front of mutable is not permitted as of C++20.) Alternatively...
68,508,566
68,510,803
How to detect stack unwinding in C++20 coroutines?
The typical advice in C++ is to detect stack unwinding in the destructor using std::uncaught_exceptions(), see the example from https://en.cppreference.com/w/cpp/error/uncaught_exception : struct Foo { int count = std::uncaught_exceptions(); ~Foo() { std::cout << (count == std::uncaught_exceptions() ...
The archetypal reason for wanting to know if a function is being executed due to stack unwinding is for something like rolling back a database transaction. So the situation looks rather like this: Your function does some database work. It creates a database transaction governed by a RAII object. That object is on the f...
68,508,605
68,508,669
Call variadic function template with template parameters of variadic class template?
Given a variadic class template, how can I call a variadic function template with the template parameters of that class? Example: template <typename T0,typename... Ts> void test_variadic() { std::cout<<typeid(T0).name()<<std::endl; if constexpr (sizeof...(Ts) > 0) test_variadic<Ts...>(); } template...
You can declare a class template with partial specialization as: // primary template (might implement it with default behavior) template <typename T> struct test_variadic_impl; // partial specialization for variadic class template template <template <typename...> typename C, typename... Args> struct test_variadic_impl...
68,508,647
68,531,565
How to properly using infinite loop in Qt GUI?
I am new to and learning the Qt GUI framework. I have an ultrasonic sensor wired up to the Raspberry Pi, to measure water level. If I were coding in C, I would have used a while(1) loop to constantly read the sensor input. But when I put while(1) inside MainWindow.cpp, the window cannot be displayed. However, using qDe...
The main thread where the GUI of Qt runs never should be blocked by long-lasting operations like an infinite while-loop, because otherwise you would block the event system and nothing will work anymore. Instead you usually create a worker thread in parallel (see QThread) where you do your loop in the run function of th...
68,508,791
68,508,841
Call a function after x seconds while keep running rest of the program in C++
I have a program in which I want to call a function after x seconds or minutes while keep running rest of the program.
You should run new thread: #include <string> #include <iostream> #include <thread> #include <chrono> using namespace std; // The function we want to execute on the new thread. void task(int sleep) { std::this_thread::sleep_for (std::chrono::seconds(sleep)); cout << "print after " << sleep << " seconds" << en...
68,509,535
68,509,597
Returning an array from a function declared with decltype(auto)?
I would like to return an array (or reference to an array) from a function as follows: decltype(auto) bar() { static int a[2]; return a; } Unfortunately, it results in very cryptic errors. GCC complains: error: cannot convert 'int [2]' to 'int [2]' in return and Clang is not better in explaining the problem: error: a...
The problem is indeed decltype(auto). The return type is deduced by following this list (the expression in question is the one given to the return statement): [dcl.type.decltype] (redacted for emphasis) decltype-specifier: decltype ( expression ) 1 For an expression E, the type denoted by decltype(E) is defined a...
68,509,563
68,517,761
2-D array(Matrix) layer rotation code. Trying to optimise a code for matrix layer rotation
I was trying to write a code to rotate a given matrix a, int r times which is passed to the function as an argument. My code is correct but it gives TLE in some cases. Can anyone optimise this code? The function rotates the matrix by 1 step r number of times. If r = 1 it will rotate a matrix that looks like this 1 2...
Optmisitiion: A ring(any layer) of a matrix m * n can only have 2*(m+n-2) possible rotations. That means we only need to rotate the ring of the matrix by a maximum of 2*(m+n-2)-1 in worst case. I've noticed that as we go into the inner rings (layers) the number of rotations required is reduced by 8 (I've verified it wi...
68,509,566
68,512,469
How does casting this pointer to an unrelated class work?
This confuses me because if "this" points to its own object, how would casting it (without inheritance) allow me to access other class members? I think I'm just overall confused on what exactly casting "this" is doing for the compiler, considering its address doesn't change. template<class T> class A { public: voi...
A non-static method call is just like a plain function call but with a hidden this parameter pointing at the object. The code shown is roughly equivalent to the following: class A {}; class B {}; void B_fn(B* this); void A_call_fn(A* this) { B_fn(reinterpret_cast<B*>(this)); }; void B_fn(B* this) { std::cou...
68,509,578
68,509,757
How to read a complicated type?
I know that using type alias and typedef make the code so readable, less error-prone and easy modify. However in this example I want to know this complicated type: #include <iostream> #include <typeinfo> char ( * (* x() )[] )(); int main(){ std::cout << typeid(x).name() << std::endl; } As the rule of thumb says...
char - returning a char * (* - of pointers to *---v ^ (* - returning a pointer to *---v ^ v ^ x() - a function `x` --^ v ^ v ^ )[] - an array *---^ v ^ )(); - functions ...
68,509,644
68,509,765
C++: How to pass array into an instance of a class and get the sizeof() it?
I want to pass an array into an instance of a class to be used within it. However, I can't get sizeof() the array. I get the warning "Sizeof on array function parameter will return size of 'float *' instead of 'float []'. " int main() { float info[]={1.0f,2.3f,1.0f,1.0f,1.0f,1.0f,1.0f,1.0f,1.0f,67.8f}; Store test(info)...
For a static C-style array it is possible to infer its size using the expression sizeof(info) / sizeof(*info) This is also commonly implemented via a macro ARRAY_SIZE. Beware however that in the above code there is no check that the actual array is a static one. Conversely, for a dynamically allocated C-style array, t...
68,509,933
68,510,145
Why was string as pointer or string as raw array always called as pointer in overloaded function?
I have a function check_str that is overloaded for const char* and const char(&)[N] types. void check_str(const char*) { std::cout << "string as pointer!!" << '\n'; } template <size_t N> void check_str(const char(&)[N]) { std::cout << "string as array!!" << '\n'; } Then, I declared arr_01 as const char[]: con...
Use std::array: #include <algorithm> #include <array> #include <cstddef> #include <cstdio> template <std::size_t sz> [[nodiscard]] constexpr auto to_array(char const (&cstr)[sz]) noexcept { std::array<char, sz> std_arr; std::copy_n(cstr, sz, std_arr.data()); return std_arr; } void check_str(char const*) { st...
68,509,958
68,510,029
Whats wrong in this code , its been identified as Wrong answer by the online judge?
#include <bits/stdc++.h> #include <cmath> #include <iostream> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; int w1, c1, r1, w2, c2, r2; int x1 = 0; int x2 = 0; cin >> t; for (int i = 0; i < t; i++) { cin >> r1; cin >> w1; cin >> c1; // t=0 ...
Whats wrong in this code , its been identified as Wrong answer by the online judge? The part is wrong is: x1 = r1 + w1 + c1; x2 = r2 + w2 + c2; It does not test which person is better than the other in most statistics. It sums up each statistic, but that does not say anything about if one person was better ...
68,510,257
69,068,391
Copying vs Moving while casting objects
I am trying to implement a class for linear algebra column vectors. I have the following code snippet, where I try to cast an object without copying anything. #include <iostream> #include <fstream> #include <cassert> #include <vector> using namespace std; class Vector { public: std::vector<int> vect; pub...
You don't need to write the copy and move constructors as the compiler will implicitly generate them if the only behavior is to copy/move the std::vector member. By the way, you may want to implement your ColumnVector as a view of the Vector (something like std::string_view) so that there is even no move.
68,510,375
68,563,241
Getting the Value of a CPP Object using IDA Pro and IDAPython
I've set a breakpoint using IDA Pro on a function that returns a cocos2d::Image object pointer as a response, as can be seen in the screenshot below. However, I'm at a complete loss at how I can use IDAPython to print out the Object members, and such. Is there a way to do it? The Docs haven't been too helpful, and onl...
Use print Dword(addr) for printing dword-sized members and print Byte(addr) for printing byte-sized members. Result is stored in eax, so you can use relative offsets from eax to get member addresses. To print all the members from the screenshot that will be: eaxVal = GetRegValue("eax") print Dword(eaxVal+45) print "\n"...
68,510,870
68,510,937
pass std::istringstream as a parameter doesn't work
I've just started to learn C++ 11 and I have this header file: #pragma once #include <string> #include <fstream> #include <sstream> class Parser { public: Parser(); ~Parser(); void Parse(const std::string& path); private: std::ifstream inFile; void LoadFile(const std::string& path); void P...
The & character has a variety of (sometimes very confusing) uses in C++. It can be used as the bitwise AND operator, the address-of operator and, in function declarations/definitions, to declare that a given parameter should be passed by reference. In your case, the declaration, void Process(const std::istringstream& i...
68,510,988
68,511,828
How to copy a prefix of an input stream to a different stream in C++?
There's a neat trick that can be used to copy file contents in C++. If we have an std::ifstream input; for one file and an std::ofstream output; for a second file, the contents of input can be copied to output like this: output << input.rdbuf(); This solution copies the entirety of the first file (or at least the enti...
I tried different solutions, including the one presented by @Some programmer dude, and ultimately decided to go with a manual read and write loop. Below is the code that I used (based on this, with small modifications) and at the bottom are the benchmark results: bool stream_copy_n(std::istream& in, std::ostream& out, ...
68,511,019
68,511,046
error: expected primary-expression before 'int' on the terminal of my vscode
I'm a beginner, it doesn't seem to have an error on the code. But when I try to run it, on the terminal it says that I had to put expected primary-expression before 'int'.. #include <iostream> using namespace std; int main() { int a = 1; cout << a << endl; cout << sizeof(a) << " byte" << endl; cout <...
add #include <limits> you need to add the header file to use it
68,511,577
68,515,956
Aspects that affects the efficiency of OpenMP parallelism
I would like to parallel a big loop using OpenMP to improve its efficiency. Here is the main part of the toy code: vector<int> config; config.resize(indices.size()); omp_set_num_threads(2); #pragma omp parallel for schedule(static, 5000) firstprivate(config) for (int i = 0; i < 10000; ++i) { // the outer loop that...
Private copies of config or, random access of ref_tables are not problematic, I think the workload is very small, there are 2 potential issues which prevent efficient parallelization: atomic operation is too expensive. overheads are bigger than workload (it simply means that it is not worth parallelizing with OpenMP) ...
68,511,704
68,511,741
How can a string be assigned to a const char*?
How is it possible to assign a string (an array of chars, if I'm understanding this correctly) to a const char*? Any other pointer requires the new keyword followed by a type, but in this case the string is just assigned to a pointer. The pointer is a memory address, not an array of chars, but somehow it accepts the ar...
Arrays can be implicitly converted to pointers to their first elements. Most (but not all) operations on arrays perform this conversion, so arrays and pointers are often confused with each other. Good job figuring out the difference early on. Any other pointer requires the new keyword Not true, consider this: int x;...
68,511,711
68,515,443
SetEndOfFile error 1224: ERROR_USER_MAPPED_FILE, even the file mapping closed successfully
I'm writing a program which logs out to the file with file-mapping. When I want to read the log, Logger::Destroy() is called so that the content writed on file-mapped-view could be flushed to the physical file. The code is as follows: int Logger::Destroy() { if (m_lpMapAddress) { auto bRet = UnmapViewOfFile...
I'll answer my own question. The problem was that I called OpenFileMappingA() after CreateFileMappingA(), so the m_hMapFile returned by CreateFileMappingA() is leaking. I've removed OpenFileMappingA() and the problem disappeared. I used to know that it must be once opened after create handle, and I used to do that in m...
68,511,992
68,512,523
Is accesssing an atomic struct containing two floats more efficient than accessing two seperatate atomic float variables when working with a high freq
I am pulling sensor data at a high frequency (during some measurements 1ms, sometimes every 2/5/10 ms) and displaying them on the interface (live plot/gauges) in the same thread. Now that I am splitting it up into two threads for obvious efficiency reasons (the data display thread is accessing the shared variables only...
Taking gcc on Intel as a baseline, if you look at the code over at Godbolt, you can see that using a struct containing two floats is marginally more efficient. This is because: The struct is small enough to be lock-free (which is important - locking a mutex is slow). Both floats can be retrieved from (or stored in) ...
68,512,448
68,512,497
When I run the program, the output is "inf"
#include <iostream> using namespace std; int main() { float sum = 0; int n; cout << "Nhap gia tri n = "; cin >> n; for (int i = 0; i <= n; i++) { sum += 1 * 1.0f / i; } cout << "Tong la: " << sum << endl; return 0; }
You start your loop by i==0. In the C++ floating point, 1/0==inf. After that, it does not matter, what you add to it, because inf + anything is inf. You probably want to start your code with i=1. In your case, I would also filter out the n<1 inputs, it will result 0. Just exit with an error message like Cáa duu vao nho...
68,512,686
68,512,976
Any way to make a variable type the same type as the class it is in and being static and a const and not a pointer?
I would like to have a variable of the same type as the class it is in. I don't want to use a pointer. I want it to be static AND a const. I have not found a way to do this. I also want an identifier for it. When I used a pointer, I got a supposed "memory leak". What I want: class A { std::string str; A(std:...
How about class A { std::string str; A(std::string str) : str(str) {} static const A& getA() { static const A b("hi"); return b; } } That might be a solution, depending on your needs.
68,512,687
68,512,874
partial_sort not working correctly for vector
Trying to solve 'move zeros' question. I have to shift all zeros of vector at last and then all other numbers need to be arranged in ascending order. class Solution { public: void moveZeroes(vector<int>& nums) { int position = nums.size()-1; for(int i=0;i<nums.size();i++){ if(nums[i...
Take a look at what std::partial_sort() does: Rearranges elements such that the range [first, middle) contains the sorted middle - first smallest elements in the range [first, last). In other words, the partitioning you did is ignored. There are a few alternatives: std::sort() it all, and std::rotate() the zeroes to...
68,513,324
68,513,459
Variadic template for validation
I have a class which initially tries to read settings from a configuration and if the values are invalid, they should be populated with a default. This is what I got (custom Optional implementation): template <typename T> struct dont_deduce { using type = T; }; template <typename T> using dont_deduce_t = typename dont...
The &clamped is not a valid function pointer. Since the clamped is a template function, you need to instantiate with a valid template argument so that you can get the function pointer. For example: readOrPopulateDefault(20, &clamped_validator<int>, Optional<int>(0), Optional<int>(12)); // ^^^^^^^...
68,513,387
68,513,443
Why does my recursive solution to pruning binary tree not work?
Link to question: https://leetcode.com/problems/binary-tree-pruning/ Basically, given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed. My code: /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left...
if ( ... ) In order for this if statement to evaluate to true, both of the recursive calls in the if statement must return false. This if statement uses the boolean && operator. In C++, the boolean && operator requires both its left-hand and right-hand side expressions to be true which in this case will happen only i...
68,513,951
68,514,238
pthread_create() appears to leak memory
I've written a simple wrapper.so over calloc() and free() to monitor memory calls and appears that pthreads_create() is leaking memory. After an initial allocation with calloc(17, 16) (most of the time calloc(18, 16)), it seems like that memory is being attempted to be free'd, but a nullptr is passed to free() instead....
The memory region in question is the DTV (dynamic thread vector), which can't be deallocated until program termination. You can see it in GDB if you break on calloc: (gdb) bt #0 __libc_calloc (n=17, elem_size=16) at malloc.c:3366 #1 0x00007ffff7fc52fa in calloc (nmemb=17, size=16) at wrapper.cpp:56 #2 0x00007ffff7fe...
68,515,199
68,515,271
How to unfold a template to string when the possible type be float or string?
In C++, i want to build a string only container from a template. For example: template<typename T> void show(const T & t) { // the T can be map<string, string> or <string, float> or <string, int> std::unordered_map<std::string, std::string> r; for (const auto & i : t) { const auto & j = i.first; const au...
IF you can use C++17, then constexpr if statement is what you want. That would give you template<typename T> // the T can be map<string, string> or <string, float> or <string, int> std::unordered_map<std::string, std::string> show(const T & t) { std::unordered_map<std::string, std::string> r; for (const auto & i...
68,515,453
68,515,569
C++ - Capitalize the first Character for each word in the given string
I have a char pointer , then i convert it into string format. So i would like to capitalize the first character of each word in this string, I wrote the code below : #include <iostream> #include <cstring> #include <stdlib.h> #include <time.h> #include <string> using namespace std; void transform(char *s); int main(int ...
First thing to note here is that islower returns non zero(>0) number if argument is lowercase instead of 1. Second you are trying to capitalize char by checking if char before it was whitespace. Nothing wrong with this approach but it won't work on first character so you can do it by adding an extra line before the l...
68,515,575
68,518,244
Operation of Inserting in middle of linked list is giving me a wrong output
where am I going wrong in this insertion of the linked list problem? Node *insertInMiddle(Node *head, int x) { Node *temp = new Node(x); int len = 0; if (head == NULL) return temp; Node *curr = head; while (curr->next != NULL) { len++; curr = curr->next; } Node *...
The calculation of mid is such that when the list size is even, the insertion happens too far to the right. You can actually simplify the initialisation of mid to this: int mid = (len - 1) / 2; Or: int mid = len / 2; The difference between these two will only be be noticed when the list size is odd, like 1->2->3. If ...
68,515,881
68,516,163
Can an element in an array itself be called a subarray?
For example: int arr[5]={1,2,3,4,5}; Now here can I say that each element is a subarray of arr? I got confused when the question asked to find count subarrays with a given target sum.
Each element of an array can itself be considered a sub-array of size 1. So, given: int arr[5]={1,2,3,4,5}; each of 1, 2, 3, 4, 5 are subarrays: {1}, {2}, {3}, {4}, {5} In the question you were given, this is important in that if an element on its own matches the target sum, it counst as a sub-array towards your sol...
68,516,546
68,516,579
What's the difference between std::ranges::swap() and std::swap()?
In C++20, there are two swap function templates: std::ranges::swap(T&&, U&&) and std::swap(T&, T&). I just wonder: What's the difference between they two?
In rough terms: std::ranges::swap generalizes std::swap. If T and U are the same, then it's equivalent to invoking std::swap. Otherwise it will swap the arguments as two ranges - if they're ranges. Otherwise it will perform a swap-like procedure with move assignment between the different types T and U. If even that ca...
68,516,898
68,518,024
gtkmm 4: How to get X window ID from inside widget?
In gtkmm 4, how can one get the X Window ID of type XID as defined in X11/X.h, from inside a class, that inherits from Gtk::Widget?
Not all of them have one. Those widgets that do will implement the GtkNative interface, which provides the gtk_native_get_surface function, allowing you to obtain a GdkSurface. In gtkmm, this will correspond to casting to to Gtk::Native and calling get_surface. To obtain a Window handle from that, you can use the GDK_S...
68,516,917
68,517,792
Check if the content of a QTextEdit is a valid font. - Qt
I'm currently making a notepad in Qt and now I'm making the font section. I want the user to input a font in a QTextEdit and when he presses enter the app checks if it is a valid font, otherwise it will show a MsgBox saying that it isn't and to enter a new one. How do I make this?
I resolved the problem, I'm so stupid tho. I used a Font ComboBox.
68,517,247
68,517,295
Why does the C++ Standard define a partial ordering for cv qualifiers?
The C++20 standard (checked on N4892) states: There is a partial ordering on cv-qualifiers, so that a type can be said to be more cv-qualified than another. Table 13 shows the relations that constitute this ordering. 6.8.4.5. With table 13: no cv-qualifier < const no cv-qualifier < volatile no cv-qualifier < const vo...
Just search for "more cv-qualified" in the standard document. There will be a lot of matches. Maybe the most obvious example: char* pointer1; ... const char* pointer2 = pointer1; // OK because it's more cv-qualified In my opinion, if you are looking for common sense, just think about "const" instead of "cv".
68,517,920
68,518,528
What happens when std::istream_iterator<int>(std::cin) Equals to the end iterator std::istream_iterator<int>()
i am learning about iterators by checking/writing different examples. In one such example(given below) when i enter an invalid type say char into the input stream the next cout statement is not executed. The example is as follows: #include <iostream> #include <iterator> int main() { std::istream_iterator<int> s...
std::istream_iterator reads ahead: the first read in constructor, subsequent reads in operator++. operator* returns the previously read, cached value. If any of the reads fail, the iterator becomes equal to the end iterator. So this is what happens in your example. starting_it reads 1 in constructor. The first iteratio...
68,517,921
68,518,165
Building GCC SIMD vector constants using constexpr functions (rather than literals)
I'm writing a piece of code using GCC's vector extensions (__attribute__((vector_size(x)))) that needs several constant masks. These masks are simple enough to fill in sequentially, but adding them as vector literals is tedious and error prone, not to mention limiting potential changes in vector size. Is it possible to...
Technically possible, but complicated to the point of being unusable. An example unrelated to SIMD. Still, the workarounds aren’t that bad. SIMD vectors can’t be embedded into instruction stream anyway. Doesn’t matter your code says constexpr auto mask, in reality the compiler will generate the complete vector, place t...
68,517,961
68,518,269
Can this be considered as a valid implementation of singleton class in C++?
#include <iostream> using namespace std; class Singleton { public: int val; static int count; Singleton() { if (count == 1) throw 0; Singleton::count++; val = 100; } }; int Singleton::count = 0; int main () { try { Singleton a, b; } catch (...) { cout <...
C++11 and above: You make your constructor private and define a static instance in a static function. It synchronizes construction so the object is constructed once no matter how many threads try to access it: class Singleton { private: Singleton() { /* ... */ } public: static auto& instance() { static...
68,517,977
68,518,046
How do i get all the bits present on odd positions in binary representation of integers?
The bits are enumerated from left to right starting from the leftmost set bit i.e. the most significant bit. For example, the binary representation of 77 is 1001101. Bits present on 1st, 3rd, 5th, and 7th positions in the binary representation are 1,0,1,1 respectively.
Python: int_val = 77 binary_val = bin(int_val)[2:] odd_pos_data = [ value for index, value in enumerate(binary_val,1) if index % 2 != 0 ] print(odd_pos_data) Result: ['1', '0', '1', '1'] This is how to do in C++: #include <iostream> #include <bitset> using namespace std; int main() { int num ; cout<<"En...
68,518,567
68,518,902
Different outputs for Java and CPP
I was solving Nth root of M problem and I solved it with Java and here is the solution: public int NthRoot(int n, int m) { // code here int ans = -1; if (m == 0) return ans; if (n == 1 || n == 0) return m; if (m == 1) return 1; ...
As you have probably guessed, the problem is due to the attempt to convert a double value to an int value, when that source is larger than the maximum representable value of an int. More specifically, it relates to the difference between how Java and C++ handle the cast near the start of your while loop: int po = (int)...
68,518,828
68,519,365
compiling cpp files with g++
I am an Ubuntu user and would want to know the difference between g++ file.cpp -o file and g++ -c file.cpp. I know that g++ -c file.cpp creates an object file, file.o But what about g++ file.cpp -o file? I have been using this command for a long time but don't know the file generated as an output (it is just "file"). I...
g++ file.cpp -o file produces an executable file (which normally have no extensions on Linux). -o specifies the output file name. If you do just g++ file.cpp, the file will be named a.out. It's equivalent to g++ -c file.cpp followed by g++ file.o -o file, except that the file.o is not saved anywhere. Note that you can ...
68,519,729
68,519,767
Why socket(AF_INET, SOCK_STREAM, 0) return -1?
I'm writing a socket c++ lib for TCP. I'm compiling with GCC for x86_64-w64-mingw32.7.3.0 on windows 10. When I try to build a socket I fail. listenSocket = socket(AF_INET, SOCK_STREAM, 0); if (listenSocket < 0) { std::cout << "ERROR: OPEN SOCKET" << listenSocket << std::endl; close(listenSocket); return...
If you write any socket based code in Windows, you need to start your application with WSAStartup(). Add it to your program if you have not. In addition, you need to finish your application with WSACleanup(). These 2 functions are windows-specific. Here is a small sample: int main() { WSADATA wsaData; int err =...
68,519,928
68,519,978
What is the 3rd parameter meant to look/be like XInputGetBatteryInformation()
Sorry if I messed up this post or something, my first time ever posting on Stackoverflow, I'd usually ask a discord server for help but they don't do C++, I'm pretty new to C++ and I am trying to develop a Bakkesmod plugin, it uses XInput, the idea is that it updates you when the controller battery level changes, thoug...
You need to create a variable of type XINPUT_BATTERY_INFORMATION and pass a pointer to it. XINPUT_BATTERY_INFORMATION my_battery; XInputGetBatteryInformation(user_index, dev_type, &my_battery); // Now my_battery contains the battery information If you or I were writing this function in a high-level language, we would ...
68,520,457
68,520,750
How to handle mouse clicks in CMainFrame
How can I detect in an "empty" CMainFrame mouse clicks? With empty I mean a MDI which has not yet any document/view. I have tried to detect mouse clicks with: afx_msg void OnLButtonDown(UINT nFlags, CPoint point); BOOL CMainFrame::PreTranslateMessage(MSG* pMsg);
MDI main frame windows have an 'invisible' client window that occupies the client area of the main frame. This window is inaccessible using 'normal' class override techniques but, if that main frame window is derived from either CMDIFrameWnd or CMDIFrameWndEx, you can use its m_hWndMDIClient member (the HWND of that in...
68,520,492
68,528,596
Print histogram with "*" representing relative frequencies in C++
I'm trying to convert an histogram with absolute values to an histogram showing the relative frequency of letters in a string, written by the user. The letters frequency should be represented by *. So, if the letter "A" is 1% of a string, there should be two *. 1% = two *. When trying to calculate the frequency, the ou...
void abs_till_rel(int arr[ANTAL_BOKSTAVER], int langd, double frekArr[ANTAL_BOKSTAVER]){ //Function to calculate the relative frequency of letters in a string. for (int i = 0; i < ANTAL_BOKSTAVER; i++){ frekArr[i] = arr[i]; //Writes over the input from the user to a new array. frekArr[i] = frekArr[i] * 20...
68,520,499
68,520,921
Is there any way to prevent the program from termination if an exception was thrown before a child thread had been joined?
//... try { std::thread someThread(someFunc, someArg); // assume it doesn't throw foo(); // might throw bar(); // might throw someThread.join(); } //... In the above example, if either foo() or bar() throws, someThread's destructor will call the terminate() function because someThread had not been join...
One option would be to simply declare someThread before the try/catch block and use move-assignment in the try clause. Then call to join can then be immediately after the catch clause... std::thread someThread; try { someThread = std::thread(someFunc, someArg); foo(); // might throw bar(); // might throw }...
68,520,775
68,520,838
Is it necessary for endl to flush buffer?
According to the definition of endl, it is used to insert a new-line character and flush the stream. And I remember that if a new line is inserted, then the buffer will be flushed automatically. If so, why do endl still need to flushes the stream after inserting a new line.
if a new line is inserted, then the buffer will be flushed automatically Not necessarily, and not for all streams. It's common for std::cout (and the standard output stream it sends data to) to be line-buffered, but not universal. Some implementations, for example, only line-buffer stdout if output is going to a te...
68,520,802
68,520,845
Undefined symbol in protoc with gcc 11 build
I'm trying to build protocol-buffer by following these instructions. This is what I did. git clone https://github.com/protocolbuffers/protobuf.git cd protobuf git submodule update --init --recursive ./autogen.sh ./configure make -j6 After the successful build, I checked ldd -d src/.libs/protoc It showed a lot of unde...
The Linux loader, ld.so does not, by default, load libraries from the current directory but only from predefined locations. You are attempting to load a library from the current directory that depends on another library in the current directory, hence the load failure. ld.so's manual page explains how to set LD_LIBRARY...
68,521,166
68,521,290
215. Kth Largest Element in an Array C++ Solution Not Working
Given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: nums = [3,2,1,5,6,4], k = 2 Output: 5 My Solution Is Below and I do not understand why it is not working. Maybe I am rea...
Let's go through your function, with your example Input: nums = [3,2,1,5,6,4], k = 2 Output: 5 You do sort in ascending order std::sort(iterator begin, iterator end). That.s good. After that, you have sorted vector: 1, 2, 3, 4, 5, 6 Edit:// I haven't noticed it: (so second point is correct now). Note that it is th...
68,521,191
68,521,441
Implementing std::is_invocable_r with C++ 20 concepts
I am trying to implement std::is_invocable<R, Callable, Args...> using C++ 20's concepts with as little help from STL as possible and without using std::invoke etc. This is my current approach. It causes compile error though (msvc): error C3864: 'is_invocable_r': requires clause is incompatible with the declaration tem...
Two problems. You aren't specializing the template. You are re-declaring it. A partial specialization must be declared with a template-id. I.e. is_invocable_r<...>. A partial specialization should be more constrained than the primary template declaration, not less. And it must be a more specialized case of the primary...