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
70,627,623
70,627,880
Problem with a variable with the same value in different functions (C ++)
Do you know if there is any way to save the value of an assigned variable in one function to use it in another function? In this case, I have a program that asks me to enter the name of the variable nombre in the function registro(); to register a plant. For example, if I enter Maguey de sol, the program prints: ¿Quier...
Not sure about what you're trying to achieve, but to elaborate on Stephen Newell 's comment, here is a modified version of your code. Although your nombre variables have the same name, they are technically different variables, and therefore have different values, in each of their respective scope. Learn more here: http...
70,627,806
70,628,107
Negating expression in if statement inside macro gives odd results
I've run into a somewhat strange issue. It makes me feel like the answer is blaringly obvious and I'm just not seeing something because the code is so simple. I basically have a macro called "ASSERT" that makes sure a value isn't false. If it is, it writes a message to the console and debug breaks. My issue is that whe...
This is the unexpected consequence of the by-design simple stupidity of the preprocessor's macro substitution engine. An expression supplied to the macro is not evaluated as it would be with a function, the text is inserted directly during substitution. Given #define ASSERT(x, msg) {if(!x) { std::cout << "Assertion Fai...
70,628,392
70,628,495
How do I implement an iterable structure?
I want to write a structure through which I can loop. For this I added two methods begin and end which would return begin, end values of an already existing vector. What return type should I specify, and will these two methods be enough to make MATCH structure work in my context? Here's what I've got so far: typedef st...
I think the type you're looking for is std::vector<combo>::iterator. Example: typedef std::pair<std::string, std::string> combo; struct MATCH { std::vector<combo> matches; std::vector<combo>::iterator begin() { return matches.begin(); } std::vector<combo>::iterator end() { return matches.end(); } }; int m...
70,628,435
70,628,679
How to configure cmake to recompile a target when a non .cpp source file is modified
If we look at the minimal example below, cmake_minimum_required(VERSION 3.20) project(example) add_executable(${PROJECT_NAME} main.cpp test.txt) Once the executable target is built, it will only rebuild if main.cpp is modified. If test.txt is modified, it wouldn't rebuild because eventhough test.txt is included as a...
One way is to create a custom target and add a custom command to it that will generate your mylib.metallib cmake_minimum_required(VERSION 3.20) project(custom_file_target VERSION 1.0.0) add_executable(main main.cpp) # main target add_custom_target( custom DEPENDS ${CMAKE_BINARY_DIR}/mylib.metallib ) add_cust...
70,628,471
70,628,558
clang-tidy: `Loop variable is copied but only used as const reference; consider making it a const reference` - does it really matter?
I'm working on code that clang-tidy is flagging all over the place with Loop variable is copied but only used as const reference; consider making it a const reference Current code: for (auto foo : collection) { ... } What clang-tidy suggests I use: for (const auto &foo : collection) { ... } I can certainly s...
Constructors can have side-effects beyond constructing the new object. The semantics of the two versions could therefore differ. Even if that is not the case, the compiler might not be able to determine that during compilation. For example if the copy constructor of the foo type is not defined in the same translation u...
70,628,591
70,629,590
SDL_CreateWindow Error: windows not available
When calling SDL_CreateWindow("Hello World!", 100, 100, 640, 480, SDL_WINDOW_SHOWN); the window is not created and calling SDL_GetError returns an error that reads exactly as shown in the title. I had set my SDL_VIDEODRIVER to 'windows' at one point, but changing this, rebuilding my application, and attempting to run a...
The answer is very simple, you are not running the test with the X server running from mintty: $ g++ prova.cc -o prova -lSDL2 -I/usr/include/SDL2 $ ./prova.exe SDL_Init Error: No available video device now we start the X server $ startxwin Welcome to the XWin X Server Vendor: The Cygwin/X Project Release: 1.21.1.2 ....
70,628,865
70,629,051
Can't access private member in templated overloaded operator
In this code, why is it not possible to access the private field of my class in the operator overload ? (Note that this is only a MRE, not the full code) template <typename T> class Frac template <typename T, typename U> Frac<T> operator+ (Frac<T> lhs,const Frac<U>& rhs); template <typename T, typename U> bool operat...
To make each instance of template <typename T, typename U> bool operator==(const Frac<T>& lhs, const Frac<U>& rhs); a friend, you need to be just as verbose in your friend declaration. Copy this declaration and stick "friend" in it. There are two quirks. First, template has to come before friend, so you'll be adding t...
70,628,926
70,629,021
Usage of for range in Vectors in order to add elements
A lot of questions related to for range has been asked around here, but I cannot find the version I need. So, I was reading this book called C Primer 5th edition, and while reading about Vectors I read a line which stated, we cannot use a range for if the body of the loop adds elements to the vector. But just before th...
The reason that (amongst other things) a range-based for loop shouldn't append elements is because behind the curtains, a range-based for loop is just a loop that iterates over the container's iterators from begin to end. And std::vector::push_back will invalidate all iterators: If the new size() is greater than capac...
70,628,987
70,629,018
01 number input for date not giving output on system
I can't enter 01 into my c++ input, it will return with empty result but when i type other date such as 12 and 11 it does show in the system. string month; cin.ignore(1, '\n'); cout << "Please Enter Month For Example 01 for January:"; getline(cin, month); string search_query = "SELECT DATE(OrderDate), S...
The problem is that you are using the LIKE operator in MySQL, which checks to see if the pattern specified on the right occurs in the string specified on the left. The pattern "01" probably doesn't occur in the value on the left, since the string on the left should be "1" for January orders, and that doesn't have a "0...
70,629,120
70,647,297
Windows __try/__except doesn't catch raised exceptions
So I was trying to write something that dereferences an unknown pointer and returns the status of the operation, like this: int n; __try { n = *(int*)(addr); // The unknown address. } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { printf("Ex...
As @Hans Passant said, the process's debugger can catch the exception prior to a frame-based exception handler(I checked). The RaiseException lists an exception handler sequence. The system first attempts to notify the process's debugger, if any. If the process is not being debugged, or if the associated debugger doe...
70,629,277
70,629,296
Calling constructor with :: operator fails
I am implementing a class using singleton for logging purposes. Log *Log::getInstance(){ if(!Log::log) Log::log = new Log::Log(); return Log::log; } Here, Log::log is a pointer to an object of Log class. This snnipet of code generates the error "expected type-specifier" on new Log::Log(), but if I ommit ...
Log is the class type. Log::Log is a syntax construct that in certain contexts refers to Log's constructor. However it doesn't generally name it as in the names of other functions (e.g. for the purpose of address-taking). new expects a type name. That is simply the syntax. Log(...) in a new-expression like new Log(...)...
70,629,382
70,629,418
Using return vs no return in recursion?
Here is code to reverse an array using recursion Using return rev(arr,++start,--end); #include <iostream> using namespace std; void rev(int arr[],int start,int end) { if(start >= end) { return; } int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; return rev(arr,++start,-...
There is no difference. From 9.6.3 [stmt.return]: A return statement with no operand shall be used only in a function whose return type is cv void, a constructor (15.1), or a destructor (15.4). A return statement with an operand of type void shall be used only in a function whose return type is cv void. [...] Flowing...
70,629,518
70,629,541
Pass a vector as a range to std::sort - C++17
I wrote this code in order to simplify the use of std::for_each when I need to go through an entire collection: namespace ranges { template<typename Range, typename Function> Function for_each(Range &range, Function f) { return std::for_each(std::begin(range), std::end(range), f); } } So that I can...
Your implementation of for_each works, because the definition of std::for_each you're using is defined as follows: namespace std { template <class Iterator, class Function> Function for_each(Iterator begin, Iterator end, Function f); }; However, std::sort as invoked is defined as follows: namespace std { t...
70,629,559
70,629,581
For loop should not execute
In this code std::vector<int> vec; for (int i = 0; i < vec.size() - 1; i++) { std::cout << "Print" << std::endl; } Though vec has no input members so the for loop should not execute at all since i will be more than the condition for execution which is vec.size() - 1. But still the loop is executi...
vec.size() returns an unsigned type. Now vec.size() is 0, but vec.size() - 1 will cause an wrap around, so that's why you see std::cout << "Print" << std::endl; executed
70,630,371
70,630,632
What type is used by std::allocate_shared to allocate memory?
From https://en.cppreference.com/w/cpp/memory/shared_ptr/allocate_shared: template< class T, class Alloc, class... Args > shared_ptr<T> allocate_shared( const Alloc& alloc, Args&&... args ); The storage is typically larger than sizeof(T) in order to use one allocation for both the control block of the shared pointer ...
The actual type used depends on the implementation. By Allocator requirements and with the help of std::allocator_traits traits class template, any allocator can be rebinded to another type via std::allocator_traits<A>::rebind_alloc<T> mechanism. Suppose you have an allocator template<class T> class MyAlloc { ... }; I...
70,630,463
70,687,323
Using fstream::getline in VS2019 Is Giving Me Different Results Than Using It With VSCode
So I've been learning about steams and have been experimenting on my own. I was attempting to write a simple program to read the first line of a file only. But I've noticed an issue in Visual Studio 2019. Below is the code snippet. #include <iostream> #include <fstream> #include <string> int main() { std::ifstream...
You are opening your input file in binary mode. This means that getline will read the following bytes (it will discard the newline character): 54 68 69 73 0D This corresponds to the following string: "This\r" The last character is the carriage-return character. In the comments section of the question, you stated that...
70,630,968
70,631,185
Pointer initialization with new keyword and without it
When I try to declare in another way a pointer I try to use the new keyword and give it a try: #include<iostream> using std::cin; using std::cout; using std::endl; int main () { int *p = new int; *p = 5; cout << *p << endl; return 0; } but when I try to declare the same pointer but without the new ke...
You should know the differences. int *p; Here, p is just a variable on the stack. It hasn't been initialized so it does not point to a specific location on the memory. Thus when you dereference it and assign a value to the underlying location you are invoking some undefined behavior. In other words, you haven't yet al...
70,631,149
70,634,898
Can I allocate a series of variables on the stack based on template arguments?
In a piece of code I'm writing, I receive packets as uint8_t * and std::size_t combination. I can register functions to call with these two parameters, based on which file descriptor the packet was received from. I use an std::map<int, std::function<void(const uint8_t *, std::size_t)> > handlers to keep track of which ...
This answer is very similar to the first one, but it leverages the use of CTAD and std::function to figure out the function signature. Creates a tuple based on the function signature, and passes both the argument types and the elements from the tuple on to unpack. #include <iostream> #include <tuple> #include <type_tra...
70,631,288
70,631,385
Is int arr[ ] valid C++?
I am trying to understand if writing int arr[]; is valid in C++. So take for example: int a[]; //is this valid? extern int b[];//is this valid? int (*ptrB)[]; //is this valid? struct Name { int k[]; //is this valid? }; void func() { ptrB++; //is this valid? } int a[10]; int b[10]; void bar() { ptrB = &b;//...
Let us look at each of the cases. Case 1 Here we have the statement int a[]; //this is a definition so size must be known This is not valid. Case 2 Here we have the statement: extern int b[];//this is a declaration that is not a definition This is valid. Here the type of b is incomplete. Also, b has external linkage....
70,631,823
70,632,330
Botan library - fastest digital signature verification
I am looking for the fastest algorithm, where I can verify a digital signature of a blob. The algorithm shouldn't necessarily be cryptographically secure, just make sure that it's not trivially fakable. Signing time neither counts in my case. Any suggestions? Also if possible, can you tell me what modules of botan do I...
I've just found out that botan library has a cli. If you target this via --build-targets="static,cli" you can measure speed of different algorithms on your machine. Of course it will be specific to your computer, but for me this information was enough. You can check out different options of the botan cli at: https://bo...
70,631,878
70,658,383
Capturing a specific window using C++ returns old data
I'm currently working on a project that requires to take a screenshot a specific window. That's what I got so far: Main function int main() { LPCSTR windowname = "Calculator"; HWND handle = FindWindowA(NULL, windowname); while (!handle) { std::cout << "Process not found..." << std::endl; ...
When you call SelectObject you must save the previous-selected handle (available from the return value) and you MUST select it back before deleting or releasing the device context. Right now you are breaking a bunch of rules. Deleting a bitmap which is selected into a device context. Deleting a DC gotten from GetDC. C...
70,632,282
70,635,371
Install prebuilt static library dependency with the parent library
My project structure looks like this: Parent/ CMakeLists.txt file.cpp third_party/ dependency/ CMakeLists.txt lib/ dependency.lib Note that dependency.lib is a precompiled/prebuilt library: I don't even have sources for it. When I install Parent, I want it to...
Is this the right way of doing this? I could never find a good reference on how to package dependency static libraries alongside your project, and CMake doesn't seem to do this "on its own" too eagerly (I even had to manually copy the .lib there as you can see); I think what you're doing is fine. If it were me, I wou...
70,632,495
70,634,303
How to build Apple's Metal-cpp example using CMake?
Recently, Apple has released a library to use Metal directly using C++. The example that I've found online (https://github.com/moritzhof/metal-cpp-examples), works if I copy the source code and follow the steps outlined by Apple (https://developer.apple.com/metal/cpp/) in Xcode. I don't use the included Xcode project f...
All .metal files in an Xcode project that builds an application are compiled and built into a single default library. _device->newDefaultLibrary() return a new library object that contains the functions from the default library. This method returns nil if the default library cannot be found. Since you are not using Xco...
70,632,532
70,633,380
How do I clear a stream in C++ for a nanoPB protocol buffer to use?
I'm using nanopb in a project on ESP32, in platformIO. It's an arduino flavored C++ codebase. I'm using some protobufs to encode data for transfer. And I've set up the memory that the protobufs will use at the root level to avoid re-allocating the memory every time a message is sent. // variables to store the buffer/st...
To reset the stream, simply re-create it. Now you have this: pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); You can recreate it by assigning again: stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); Though you can also move the initial stream declaration to inside encodeABCounts() to crea...
70,632,731
70,633,654
Add a QTreeView in QML
I would like to register a QTreeView c++ object to QML. I tried to register it like this: main.cpp: qmlRegisterType<QTreeView>("com.MyApp.QTreeView", 1, 0, "QTreeView"); relevant code in main.qml import com.MyApp.QTreeView 1.0 QWindow { QTreeView{ headerHidden: true } } Result: it compiles. headerHid...
QWidgets are not directly compatible with QML such that they can be embedded in a QML view. They are two different UI technologies and cannot be used together in that fashion. You can however embed a QML view inside of a QWidget hierarchy: https://www.ics.com/blog/combining-qt-widgets-and-qml-qwidgetcreatewindowcontain...
70,632,917
70,633,001
c++ pass parameters to thread as reference not working
I wrote a code that create thread and send to him parameters as reference, but I get an red underline under the function name like I cant call it. Someone know what went wrong in my code my code: #include "getPrimes.h" void getPrimes(const int& begin, const int& end, std::vector<int>& primes) { int i = 0, j = 0; ...
Since getPrimes is overloaded, you'll need to help the compiler with the overload resolution. Example: std::vector<int> getPrimes(const int& begin, const int& end) { std::vector<int> vector; std::thread thread( // see static_cast below: static_cast<void(*)(const int&, const int&, std::vector<int>&)...
70,632,986
70,638,172
Store float with exactly 2 decimal places in C++
I would like to take a decimal or non-decimal value and store it as a string with exactly 2 decimal places in C++. I want to do this to show it as a monetary value, so it is always $10.50 or $10.00 rather than $10.5 or $10. I don't just want to print this, I want to store it, so I don't believe setprecision will work h...
Your decision to store monetary amounts as integer number of cents is a wise one, because floating-point data types (such as float or double) are generally deemed unsuitable for dealing with money. Also, you were almost there by finding std::setprecision. However, it needs to be combined with std::fixed to have the exp...
70,633,075
70,641,425
Get pointer to overloaded function that would be called
Please refer to the following: struct functorOverloaded { void operator()(const int& in_, ...) const {} void operator()(short in_) {} }; // helper to resolve pointer to overloaded function template <typename C, typename... OverloadArgs> auto resolve_overload( std::invoke_result_t<C, OverloadArgs...> (C::* ...
There is no way to get the function of an overload-set which would be called with the given arguments, unless you already know its signature. And if you know, what's the point? The problem is that for any given arguments, taking into account implicit conversions, references, cv-qualifiers, noexcept, old-style vararg, d...
70,633,179
70,633,232
Shorthand for using multiple names from the same C++ namespace
I'm writing a chess program and I've defined the classes I've created under the chess namespace. To shorten the code in files that use those classes, I preface it with using chess::Point, chess::Board, chess::Piece and so on. Is there a way to specify that I'm bringing in scope multiple elements from the same namespace...
No. But you can bring them all at once, using: using namespace chess; // then use Point instead of chess::Point, Board instead of chess::Board, etc
70,633,339
70,633,381
Why std::equal crashes if second vector empty
I am using std::equals defined in <algorithm> to check if two vectors are equal. It crashes when second vector is empty. I could avoid crash by checking if second vector is empty, but is there a reason to not include the check in equal function itself ? Sample code: std::vector<int> a; for (int i = 0; i < 3; ++i) a.emp...
You call std::equal with 3 arguments, which in https://en.cppreference.com/w/cpp/algorithm/equal says: Returns true if the range [first1, last1) is equal to the range [first2, first2 + (last1 - first1)), and false otherwise which will cause undefined behavior in you case Use std::equal with 4 arguments instead: std::...
70,634,034
70,635,514
Libcurl - CURLSHOPT_LOCKFUNC - how to use it?
Please tell me the nuances of using the option CURLSHOPT_LOCKFUNC ? I found an example here. I can't quite understand, is there an array of mutexes used to block access to data? --Here is this part of the code from the example: static pthread_mutex_t lockarray[NUM_LOCKS]; Is it an array of mutexes ? //..... static voi...
Yes, the code is using an array of mutexes. curl_lock_data is an enum that is defined in curl.h and specifies the different types of data that curl uses locks for: /* Different data locks for a single share */ typedef enum { CURL_LOCK_DATA_NONE = 0, /* CURL_LOCK_DATA_SHARE is used internaly to say that * the l...
70,635,056
70,635,296
C++: Is accessing values in pairs so much more efficient than accessing array elements?
Suppose we have an array of doubles x and an array of indices y, and we want to sort these indices by the respective values in x (so, sort [i in y] by x[i] as key). We can then create an array of pairs, with one component being the key value and one being the index, and for example do something like this: boost::sort::...
Not an expert, but here is what I think is going on: Jumping around in memory is a costly operation, no matter the programming language. This has to do with the caching architecture of your CPU. In pairs the data is stored interleaved in memory. There is no class boundary or anything like that. It looks like this: valu...
70,635,531
70,635,779
How to print the remaining set of numbers in C++?
Say there is a set U = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} and I created a C++ program and I, using some logic printed the numbers { 1, 3, 6, 7, 9} (let's call it set A), so the remaining numbers are {2, 4, 5, 8, 1} (let's call it set B) and U = A + B Is there a direct way to print out set B numbers (B = U - A)? (Without ...
Anytime you hear "find the missing elements" or "find the duplicate elements" type problem, you should immediately think "hash table". Do an internet search for Hash Table, but the wikipedia article has the basics. std::unordered_map and std::unordered_set are collection classes in C++ that are traditionally based on ...
70,635,676
70,635,967
How to use range projection in a sorting algorithm?
I'm trying to wrap my bonehead around the ranges. So decided to implement some basic sort procedures as a range algorithm and like in the std::ranges::sort(). I peeked its implementation but didn't understand how to make use of projection: #include <iterator> #include <functional> #include <ranges> namespace sort { n...
The point of the projection in sort is to change the comparison being used. For example: std::vector<std::string> words = {"a", "quick", "brown", "fox"}; // sorts by normal lexicographic order, so you get [a, brown, fox, quick] std::ranges::sort(words); // same, but reversed, so [quick, fox, brown, a] std::ranges::s...
70,635,683
70,635,809
What should `foo.template bar()` do when there's both a template and a non-template overload?
A coworker shared this code with me: run on gcc.godbolt.org #include <iostream> struct A { void foo() {std::cout << "1\n";} template <typename T = int> void foo() {std::cout << "2\n";} }; int main() { A x; x.template foo(); } GCC prints 1, Clang prints 2, and MSVC complains about missing tem...
[temp.names]/5 says that a name prefixed by template must be a template-id, meaning that it must have a template argument list. (Or it can refer to a class/alias template without template argument list, but this is deprecated in the current draft as a result of P1787R6 authored by @DavisHerring.) There is even an examp...
70,636,347
70,637,145
c++ beginner needs help inputing & outputing data! what am i doing wrong?
so this code is for a car garage, filling info of the accepted cars to be repaired everyday. and print the result for each car in a line. i have two problems with my code. first is, starting the second time the "do...while... " loop runs, i cant have an input for "enter car name" second is the final output, i want it i...
Here is the fixed code you're looking for: #include <iostream> #include <string> #include <array> int main( ) { std::size_t idx { }; // counting cars constexpr std::size_t maxCarCount { 20 }; constexpr std::size_t carAttributesCount { 7 }; std::array< std::array<std::string, carAttributesCount>, maxCa...
70,636,358
70,637,734
can't change Skeletal Mesh in UE4
Actually, I was trying to change the skeletal mesh of car in UE4, in the wheeled vehicle demo project which comes in ue4 c++ API. Firstly I inherited blueprint from ue4 wheeled vehicle c++ class. Then I opened blueprint editor and replaced default skeletal mesh to my skeletal mesh. I assigned bone names correctly. Then...
The animation blueprint is also tied to a specific Skeleton. If your new skeletal mesh uses a different skeleton than the one currently assigned to your skeletal mesh component, then you will need to create a new corresponding animation blueprint to use with it.
70,636,962
70,637,034
Multiplying and adding float numbers
I have a task to convert some c++ code to asm and I wonder if what I am thinking makes any sense. First I would convert integers to floats. I would like to get array data to sse register, but here is problem, because I want only 3 not 4 integers, is there way to overcome that? Then I would convert those integers to flo...
You can't easily horizontally add 3 numbers together; Fastest way to do horizontal SSE vector sum (or other reduction) What you can efficiently do is map 4 pixels in parallel, with vectors of 4 reds, 4 greens, and 4 blues. (Which you'd want to load from planar, not interleaved, pixel data. struct of arrays, not array...
70,637,008
70,637,105
memory leak and I don't know why
My first question is that the object A(v) that added the the map, it should be deleted automatically when exit the scope? My second question is what would happen to the object added into the map, when program exits? I believe when I do a_[name] = A(v);, a copy is stored to the map. Also, do I need to provide a copy con...
==xxxx== in use at exit: 72 bytes in 1 blocks ==xxxx== still reachable: 72 bytes in 1 blocks These only mean that when the program exited there was still live memory for which you still had references. The memory wasn't lost completely, which is what normally is referred to as memory leak in the strict sense a...
70,637,984
70,654,919
Forbid an alignment of consecutive comments in VSCode auto formating for C++
VSCode auto formatting in C++ programs produces this code by aligning consecutive comments: if (true) { // if begin // if inner part int x = 3; int a = 1; // some inner calculations } // if end // some outer calculations int b = 1; How can I...
The Microsoft C/C++ extension for VS Code uses clang-format by default as the formatting tool. clang-tidy is a static analysis tool, and is also good to use in its own right, but it's not the tool that answers this question. clang-format style options: https://clang.llvm.org/docs/ClangFormatStyleOptions.html The option...
70,638,231
70,638,305
Why does this code snippet print 10 infinitely in c++11?
Why does the following C++ code snippet keep printing 10 indefinitely? int num = 10; while (num >= 1) cout << num << " "; num--;
Your snippet is the equivalent of this when using braces: int num = 10; while (num >= 1) { cout << num << " "; } num--; Meaning only the printing statement is part of the loop. What you want is this: int num = 10; while (num >= 1) { cout << num << " "; num--; }
70,638,662
70,656,968
Is it possible to use the standard C++17 <filesystem> facilities with Zig in C++ compiler mode?
I am just getting started with the Zig. I am using Zig 0.9.0 on Windows 10. One of the features that attracts me is using Zig as a C or C++ compiler or cross-compiler. I have used Zig successfully for some toy programs, but my luck ran out when I tried to use C++17's standard library filesystem facilities. Here is a mi...
Should be solved in this PR. Jakub and Spex worked on it immediately after I linked them this question :^) https://github.com/ziglang/zig/pull/10563
70,638,947
70,639,474
Why does my function for inputting a string not work?
#include <iostream> void main() { using namespace std; char sentence[2000]; for (int i = 0; i <= 2000; i++) { char Test; cin >> Test; if (Test != '\r') sentence[i] == Test; else break; } for (int i = 0; i <= 2000; i++) { cout << sentence[i]; } ...
You can change it (here). Try this: #include<iostream> using namespace std; int main(int argc, char * argv[]) { char sentence[2000]; char ch; for (int i = 0; i < 2000; i++) { cin >> noskipws >> ch; if (ch != '\n') sentence[i] = ch; else { sentence[i] = '\0'; ...
70,639,419
70,639,511
How does use of make_unique prevent memory-leak, in C++?
fn(unique_ptr<A>{new A{}},unique_ptr<B>{new B{}}); is troublesome as A or B gets leaked if an exception is thrown there. fn(make_unique<A>(),make_unique<B>()); on the other hand is considered exception-safe. Question: Why? How does use of make_unique prevent memory-leak? What does make_unique do that the default uniq...
How does use of make_unique prevent memory-leak, in C++? std::make_unique doesn't "prevent" memory-leak in the sense that it's still possible to write memory leaks in programs that use std::make_unique. What does std::make_unique is make it easier to write programs that don't have memory leaks. A or B gets leaked i...
70,639,548
70,640,383
C++ linear access to 3 dimensional array
Hello as far as I understand when I allocate 3 dimensional array I truly get linear memory that is just interpreted as 3 dimensional by defining stride. So I want to access using linear index the 3 dimensional array, but how can I get first element using linear index - it should be possible in principle for example gi...
**intsss[1] is the same as **(intsss[1]). If you want to express intsss[0][0][1] in a different way, use (**intsss)[1] (but in my opinion, it's pointless). To address your multidimensional array in a linear way, first get a pointer to the first element: &intsss[0][0][0]. Then use it like a normal pointer: int* p = &int...
70,639,626
70,639,961
How does the compiler know which virtual function to call in this situation?
I'm studying for an exam and I have this code given to me: #include <iostream> #include <string> #include <cmath> using namespace std; class Expression { public: Expression() = default; Expression(const Expression&) = delete; Expression& operator=(const Expression&) = delete; virtual ~Expression() {} ...
There are two topics in your question: How does the compiler know which function to use, given some classes have multiple functions with the same name? Well, they may have the same name, but they don't have the same signature. There is no ambiguity between eval() and eval(x,y) calls, because there is only one eval th...
70,639,977
70,640,433
Insert/get tuple into/from vector of tuples
I'm trying to insert/get a tuple into/from a vector of tuples and came up with the following code snippet. It works fine, but I'm not entirely happy with it. Can anyone think of a more elegant solution? Is it possible to generalize the 'for_each_in_tuple_and_arg' function into a 'for_each_in_tuples' function? PS: I'm s...
As it is quite easy to write such things in current C++, which can be something like: template <typename TUPPLE_T, typename FUNC, typename ... ARGS > void for_each_in_tuple( TUPPLE_T& tu, FUNC fn, ARGS... args ) { std::apply( [&args..., fn]( auto& ... n) { (fn(args..., n),...); }, tu); } int main() { std::tup...
70,640,141
70,640,319
Why am i Getting garbage value when reading a binary file?
For the sake of simplicity I wrote a simple code to reproduce my problem. As you can see on the code i created a struct with two members then I created and array of the struct type then initialized it student newStudent[3] ={{"joseph",20}, {"yonas",30},{"miryam",40}};. I stored all the info from the struct to a binary ...
When you opened the file you only opened it as output ios::out you shoul've also included ios::in so you can access the file. Now you're printing the indeterminate values of an uninitialized array. change this newFile.open("/Users/josephfeleke/Desktop/abeltest/file.bin", ios::out | ios::binary); into newFile.open("/Us...
70,640,210
70,658,146
Chrome not saving Cookies across different subdomains
I've written a very primitive C++ HTTP server and I want to support the JWT token using JWT-CPP. Basically, I have 2 endpoints: If the request is /auth/username, I will generate a JWT token with the username given in the URL. If the request is /verify, I will check the Cookie in the request header and look for a JWT t...
Sorry for the misinterpretation ahead. What I meant was a different path, not different subdomains. In the end, I resolved this by adding the "Path=/" attribute after my Cookie, which allows the cookies to be carried forward across different paths. However, If you have stored the old cookie before, make sure you clear ...
70,640,810
70,713,317
How vector iterator's copy-constructor use SFINAE to allow for iterator to const_iterator conversion?
While studying various std::vector's iterator implementations, I noticed this copy-constructor which uses SFINAE to allow initializing constant iterators from non-constant ones and vice versa: // Allow iterator to const_iterator conversion // ... // N.B. _Container::pointer is not actually in container requiremen...
If I pass a constant iterator, Iter should be const_pointer, won't that fail the enable_if<> check and discard this constructor from the set? Which one will be used then? Yes, that's exactly what happens, because that definition would be an ambiguous overload of the default (implicit) copy constructor. These extra co...
70,640,922
70,640,960
Passing a 2D array as Function Argument
I am trying to pass 2D arrays of arbitrary size to a function. The code that i have tried is as follows: #include <iostream> void func(int (&arr)[5][6]) { std::cout<<"func called"<<std::endl; } int main() { int arr[5][6]; func(arr); return 0; } As you can see the func is correctly called. But i want t...
You could do this using templates. In particular, using nontype template parameters as shown below: #include <iostream> //make func a function template template<std::size_t N, std::size_t M> void func(int (&arr)[N][M]) { std::cout<<"func called with: "<<N<<" rows and "<<M<<" columns"<<std::endl; } int main() { ...
70,641,354
70,641,545
Is a declaration for a non-static data member of a class type also a definition?
I am learning C++. In particular, the difference between declaration and definition. To my current understanding All definitions are declarations but not all declarations are definitions. Here is an example of what I currently know. int x; //definition(as well as declaration according to the above quote) extern int y...
I want to know whether int x; inside the class' definition is a declaration that is not a definition or a definition. The declaration of a non-static data member (such as x) is a definition.
70,641,776
70,641,942
How to access class's virtual method from interrupt service routine?
I am trying to implement PWM using Timer0 for Atmega328P in C++. Indeed, I have achieved this. But, I have another related problem. I have a PWM abstract base class that provides an interface for PWM implementation. // mcal_pwm_base.h #ifndef MCAL_PWM_BASE_H_ #define MCAL_PWM_BASE_H_ namespace mcal { namespace pwm...
It doesn't seem possible to supply user data (like a void*) to the ISR routine so you could make myPwm a global variable: Example: Header file: extern mcal::pwm::pwm_8<UINT8_C(5U)> myPwm; ISR(TIMER0_OVF_vect) { myPwm.pwm_ISR(); } ... and in the .cpp file: mcal::pwm::pwm_8<UINT8_C(5U)> myPwm; You could also hide...
70,641,828
70,641,898
Reversing string input not giving right output
Here's how I'm going about it: int maxIndex = input.length() - 1; for (int index = 0; index <= maxIndex; index++) { char temp = input[index]; input[index] = input[maxIndex - index]; input[maxIndex - index] = input[index]; } The input is taken in a string variable called input. Now ...
There are 2 issues here: the last assignment uses input[index] instead of temp on the right hand side You iterate until the index reaches the end, which means every corresponding pair of indices is swapped twice resulting in the original string after fixing just (1.) if (!input.empty()) { for (size_t index = 0, i...
70,642,138
70,642,159
Why is my simple merge algorithm c++ not working?
I'm trying to merge two sorted vectors into a third one. However, the compiler gives me 0 in the terminal!! Can someone please tell me what I'm doing wrong? Thanks! // merging two sorted vectors std::vector<int> vec1{5}; std::vector<int> vec2{5}; std::vector<int> vec3{10}; for(int i = 0; i < 5; i++){ vec1[i] = 2 ...
All your vectors have .size() == 1, so you're going out of bounds, and the behavior is undefined. Use () instead of {}: std::vector<int> vec1(5); std::vector<int> vec2(5); std::vector<int> vec3(10); You should never use the {...} syntax with containers (as opposed to = {...} or {}), because it has a rather peculiar be...
70,642,172
70,642,194
Is there a way to extract C++ code from a Windows .exe driver or a Mac OS driver?
I have a Freestyle Libre 2 blood sugar meter, and it uses a driver to upload results to the website. Unfortunately this driver is written in C++ and only compiled for Windows and Mac OS. I use Linux and have tried installing in a virtual machine and also using layers such as Wine. I think I am left with only one option...
No. You cannot extract the original source code from a compiled binary. You can reverse engineer it, though.
70,642,263
70,642,482
Comparing unsigned integer with negative literals
I have this simple C program. #include <stdlib.h> #include <stdio.h> #include <stdbool.h> bool foo (unsigned int a) { return (a > -2L); } bool bar (unsigned long a) { return (a > -2L); } int main() { printf("foo returned = %d\n", foo(99)); printf("bar returned = %d\n", bar(99)); return 0; } Outp...
This is covered in C classes and is specified in the documentation. Here is how you use documents to figure this out. In the 2018 C standard, you can look up > or “relational exprssions” in the index to see they are discussed on pages 68-69. On page 68, you will find clause 6.5.8, which covers relational operators, inc...
70,642,333
70,642,461
Where did i go wrong c++ classes
Hi this is my first subject (question) at stack overflow i've tried an project about c++ classes at Code::Blocks but something went wrong #include <iostream> using namespace std; class char1 { public: string charName; float charLength; void printName() { cout<<"char name is"<<charName; ...
Some fixes for your code to show you how to use your class in practice (with some c++ coding tips). #include <string> #include <iostream> // using namespace std; <== don't do this // https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice //class char1 class Character // <== gi...
70,642,401
70,642,543
Can I make a Call with NASL to run a C++ programm?
We are working on a project with Nessus Attack Scripting Language ( NASL ) and we would like to run a programm written in C++. I want to ask, is it even possible to run another Script with NASL? So we would like to run the NASL script, which runs another C++ programm, which works with Zigbee to mqtt.
No. Not according to the manual. In fact it is specifically disallowed. 1.1 What is NASL ? NASL is a scripting language designed for the Nessus security scanner. Its aim is to allow anyone to write a test for a given security hole in a few minutes, to allow people to share their tests without having to worry about th...
70,642,530
70,642,605
Strange problems when creating a float array in c++
Code: #define N 4 float unknowns[N] = {71/129, 539/1461, 1493/8507, 17/33}; for(int i = 0; i < N; i++) { cout << unknowns[i] << " "; } cout << endl << endl; Output: 0 0 0 0 For some reason the program is outputing the numbers in the array as integers and not as floats and I don't know why. How can I fix this? Th...
The problem is, you are doing integer division (e.g., 71/129) and storing the value later in float. The result of integer is division of all your values is 0. Use float division while constructing the array (use 71.0/129.0). The code is: define N 4 float unknowns[N] = {71.0/129.0, 539.0/1461.0, 1493.0/8507.0, 17.0/33.0...
70,642,723
70,642,826
C++ opencv get cv::Point from index
I would like to extract data from a cv::Mat via the index of a pixel. This works fine for the colur e.g. cv::Vec3b, however when attempting to get the point information, it crashes stating: Error: Assertion failed (elemSize() == sizeof(_Tp)) in cv::Mat::at, Here is the code I'm using: cv::Mat src = imread(image_path...
you can't, using Mat::at(). (it is meant to retrieve the pixel content, not the position) the bottom-right point would be either: Point(src.cols-1, src.rows-1); or in your calculation: Point((max_index-1)%src.cols, (max_index-1)/src.cols); (imo, the whole idea of using max_indexis somewhat impractical ...)
70,642,792
70,643,322
What could be a better for condition_variables
I am trying to make a multi threaded function it looks like: namespace { // Anonymous namespace instead of static functions. std::mutex log_mutex; void Background() { while(IsAlive){ std::queue<std::string> log_records; { // Exchange data for minimizing lock time. std::uni...
I would probably think of using a counting semaphore for this: The semaphore would keep a count of the number of messages in the logs (initially zero). Log clients would write a message and increment by one the number of messages by releasing the semaphore. A log server would do an acquire on the semaphore, blocking u...
70,642,910
70,647,246
What C++ type do keycodes from HID Project Use?
Recently I have found myself incredibly frustrated in programming my recently built 9 key macro keyboard I made using an arduino pro micro. The keyboard is fully functional hardware wise, but I am very new to C++ and cannot get it to do exactly what I want. Essentially, I wish to bind the 9 keys to the F13-F21 keys usi...
Those are values of enum type KeyboardKeycode from ImprovedKeylayouts.h. While enum's named value can be casted implicitly to an integral type, opposite requires explicit cast. Not sure what problem you had to diagnose it, compiler diagnostics should have point at the mismatch. After all you also could used a type-agno...
70,643,026
70,643,761
C++20 modules export template instantiation
I'm creating a library and I have a class template inside a C++20 module and I want to add an instantiation in order to reduce compilation time for every project that uses my library. Are these different implementations equivalent, or is there a better way to achieve it? 1) //mod.cpp export module mod; export template...
Modules affect 2 things: the scope of names and the reach-ability of declarations. Both of these only matter if they are within the purview of a module (ie: in an imported module interface TU and not being in the global module fragment). Names declared in the purview of a module can be used outside of that module only ...
70,643,332
70,669,753
error: ‘HAAR_DO_CANNY_PRUNING’ is not a member of ‘cv’
I am upgrading an existing code base that use OpenCV 2 and 3 to be compatible with my Ubuntu 20.04 that uses OpenCV 4. One error I encountered when compiling is: error: ‘HAAR_DO_CANNY_PRUNING’ is not a member of ‘cv’; did you mean ‘CASCADE_DO_CANNY_PRUNING’? Should I accept the change proposed by the compiler and chang...
Should I accept the change proposed by the compiler? Yes. The values of the 4 CASCADE_* symbols match the ones of the old HAAR_* symbols, as @DanMasek commented. You can check the enums in Enumeration Type Documentation and OpenCV-2_2 Reference, page 795.
70,643,366
70,644,143
passing optional arguments to a makefile
I have a program and i have this make file and im trying to run my program with this makefile, and it compiles well the problem is when i run the program i what to run it like this ./user -n tejo.tecnico.ulisboa.pt -p 58011 with this -n tejo.tecnico.ulisboa.pt or this -p 58011 being optional. I saw this post Passing ar...
What you should do is to declare a variable (possibly with default): # Fill in your default here, setting from command line will override USER_OPTIONS ?= run: user ./user $(USER_OPTIONS) Then invoke make setting the option from the command line: make run USER_OPTIONS="-n tejo.tecnico.ulisboa.pt -p 58011"
70,643,705
70,643,831
std::this_thread::sleep_for() freezing the program
I am making a loading type function so what I wanted to do was to halt my program for a few seconds and then resume the execution inside a loop to make it look like a loading process. Looking up on web I found that I can use std::this_thread::sleep_for() to achieve this (I am doing this on linux). The problem I am faci...
This works fine on my machine (Windows 10): #include <iostream> #include <chrono> #include <thread> #include <cstdlib> #include <ctime> int main( ) { std::srand( std::time( 0 ) ); for ( std::size_t i { }; i < 100; ++i ) { std::cout << '\r' << i; std::this_thread::sleep_for( std::chrono::s...
70,643,880
70,647,411
Leaky Meyers Singleton: is it threadsafe?
I implemented a Meyers Singleton, then realized it could be vulnerable to the destructor fiasco problem. As a result, I changed the code to be: Instance *getInstance() { static Instance* singleton = new Instance(); return singleton; } After implementing this, and no apparent bugs occuring, a coworker was imple...
Yes, this is thread-safe: no two threads will ever try to initialize the same variable with static storage duration at the same time. That includes the entirety of evaluating the initializer.
70,644,005
70,644,045
Constructor vs default constructor
I'm an aspiring software engineer and full-time CS student. During the holiday break, I have been working on exercises to be better at my craft (C++). There are topics that I just need some clarity on. I'm working on a Target Heart Rate Calculator. I have spent hours, days, trying to understand the concept of the co...
If you don't define any constructor, you get a constructor that takes no arguments. As soon as you defined a constructor that has arguments, your no-args constructor retired to the North Pole. So now you must write HeartRate("first", "last", 1, 1, 2001) If you don't want to write that, delete the parameter list from yo...
70,644,034
70,644,067
How do I fix "no match for call to" in recursion inside a function? (in a permutation recursion algorithm)
void perm(std::string fixed,std::string perm){ if (perm.length() == 1){ std::cout << fixed + perm << std::endl; }else{ for (int i=0;i<perm.length();i++){ std::string perm2 = perm; std::swap(perm2[0],perm2[i]); perm(fixed + perm[i],perm2.substr(1,perm.length()-...
void perm(std::string fixed,std::string perm){ You have a function called perm, and one of its parameters is also called perm, same name. Danger ahead. perm(fixed + perm[i],perm2.substr(1,perm.length()-1)); According to rules of C++, the first perm here is a std::string object, one of the parameters to this function....
70,644,062
70,644,165
Callback definition is incompatible
I use a library which has these definitions typedef void (*CallbackFunction) (ESPRotary&); void ESPRotary::setChangedHandler(CallbackFunction f) { ... } When I try to use the setChangedHandler function I get an issue that the definition of my callback is wrong. #pragma once #include "ESPRotary.h" class MyUsermod : p...
The callback function needs to be defined statically when defined inside the class: class MyUsermod : public Usermod { private: ESPRotary r = ESPRotary(13, 12); public: /* Callback function "static" defined */ static void rotate(ESPRotary &r) { Serial.println(r.getPosition()); } void setup() { r...
70,644,176
70,644,205
Cannot erase a shared_ptr from set
I am trying to have an object with a set of pointers to another object. when I try to erase on of the set's values I get an error and crash, I really dont know what could be causing it. here is the library and after that the main function: when I try to run it it does everything its supposed to do, and when it gets to ...
shared_ptr<Employee> employee(employee_add); There is only one reason to have a shared_ptr, in the first place; there's only one reason for its existence; it has only one mission in its life, as explained in every C++ textbook: to be able to new an object, and have the shared_ptr automatically take care of deleteing i...
70,644,252
70,644,286
Is there a way to optimise the Collatz conjecture into a branchless algorithm?
I'm trying to create an algorithm that will compute the collatz conjecture, this is the code so far: while (n > 1) { n % 2 == 0 ? n /= 2 : n = n * 3 + 1; } I was wondering if there was a way to optimize this any further since efficiency and speed is crucial for this, and I've heard about branchless programming but ...
Sure. You need the loop, of course, but the work inside can be done like this: n /= (n&-n); // remove all trailing 0s while(n > 1) { n = 3*n+1; n /= (n&-n); // remove all trailing 0s } It also helps that this technique does all the divisions by 2 at once, instead of requiring a separate iteration for each of...
70,644,411
70,644,626
Aliasing - what is the clang optimizer afraid of?
Take this toy code (godbolt link): int somefunc(const int&); void nothing(); int f(int i) { i = somefunc(i); i++; nothing(); i++; nothing(); i++; return i; } As can be seen in the disassembly at the link, the compiler reloads i from the stack 3 times, increments and stores back. If somefun...
As mentioned in a comment, using const_cast to remove the constness of a reference to an object that was defined as non-const is well-defined. In fact, that's its only real use. As for __attribute__((pure)): Who knows. The nothing() calls are necessary to reproduce the situation; if those are marked pure then proper op...
70,644,482
70,645,311
system("cls") command closes the input terminal
The problem is located under the Draw function, where I use the system() command. #include <iostream> #include <conio.h> #include <stdlib.h> using namespace std; bool gameover; const int width = 60; const int height = 30; int x, y, FruitX, FruitY; enum edirection { Stop = 0, Left, Right, Up, Down, }; edirection dir; ...
I improved your code and now it works to some degree. However, I can't write the whole game for you since I have no info on how it should be written. Take a look: #include <iostream> #include <cstdlib> #include <ctime> #include <conio.h> struct GameStatus { static constexpr std::size_t width { 60 }; static co...
70,644,798
70,644,827
Is it possible to intialize array filled with zeros in member initializer list?
I need to define an empty constructor of class Array, which has one argument that contains value of parameter m. It needs to allocate memory for m elements in an array and initialize it with zeros. class Array{ protected: int* data; int m; public: Array(int m); }; Is it possible to initialize it with zeros in memb...
You may write either Array::Array(int m): m( m ), data( new int[m]() ) { } or Array::Array(int m): m( m ), data( new int[m]{} ) { } It is better to declare the data member m as having the type size_t instead of the type int.
70,645,211
70,645,283
Why is it allowed for the C++ compiler to opmimize out memory allocations with side effects?
Another question discusses the legitimacy for the optimizer to remove calls to new: Is the compiler allowed to optimize out heap memory allocations?. I have read the question, the answers, and N3664. From my understanding, the compiler is allowed to remove or merge dynamic allocations under the "as-if" rule, i.e. if th...
Allocation elision is an optimization that is outside of and in addition to the as-if rule. Another optimization with the same properties is copy elision (not to be confused with mandatory elision, since C++17): Is it legal to elide a non-trivial copy/move constructor in initialization?.
70,645,649
70,645,697
C++ overload of swap function not working
I'm writing a custom class for which I want to use the std::swap function. As I read in this post How to overload std::swap() , I have to overload it in the same namespace of the object I'm trying to swap and there's an example. I (thing) I'm replicating the example, but the function that gets called when using std::sw...
You have to uses std::ranges::swap, or find it via ADL if you aren't using C++20: myname::Grid<int> grid1(10, 10); myname::Grid<int> grid2(10, 10); std::ranges::swap(grid1, grid2); // Or with ADL using std::swap; swap(grid1, grid2); "Swapping" does not exactly mean std::swap, but this form of "using std::swap; swap(...
70,645,885
70,646,403
How to properly generically forward a parameter pack into a lambda?
I'm trying to forward a generic parameter pack from a base function, but trouble doing so, particularly if there are non-literal non-reference types in the type list Considering the following example: #include <utility> #include <iostream> #include <future> #include <vector> template < typename... Args > class BaseTem...
The problem is not with std::forward calls; the program exhibits undefined behavior before it gets to them. call takes some parameters by value, but the lambda inside always captures them by reference. Thus, it ends up holding references to local variables, which are destroyed as soon as call returns - but the lambda i...
70,645,895
70,646,813
Weird characters appear at the end of file when encrypting it
I never thought I would have to turn to SO to solve this. Alright so for more insight I am making my own encryption program. I'm not trying to make it good or anything it's just a personal project. What this program is doing is that it's flipping certain bits in every single byte of the character making it unreadable. ...
The problem is that you are measuring the length of the file in bytes, which, for text files, is not the same as the length in characters. But you are then reading it as characters, so you end up reading too many characters and then writing extra garbage after then end in the output file. Since you are getting one ext...
70,645,945
70,646,004
What are the use cases of class member functions marked &&?
I don't know which C++ standard presented this feature, but I cannot think of any use cases of this. A member functions with && modifier will only be considered by overload resolution if the object is rvalue struct Foo { auto func() && {...} }; auto a = Foo{}; a.func(); // Does not compile, 'a' is no...
Ref-qualification was added in c++11. In general, propagation of the value-category is incredibly useful for generic programming! Semantically, ref-qualifications on functions help to convey the intent; acting on lvalue references or rvalues -- which is analogous to const or volatile qualifications of functions. These ...
70,646,081
70,656,303
(0xc0210000) Error while trying to Connect PostgreSQL via C++
Background I'm trying to establish a basic connection to a Postgresql Database via C++. For that i'm using Visual Studio 2019. I'm following the instructions that can be found in http://www.tutorialspoint.com/postgresql/postgresql_c_cpp.htm The paths to the additional libpqxx and PostgreSQL includes, libraries and depe...
For those running into similar issue, following the latest instructions in the libpqxx Gitub page would solve the issue.
70,646,126
70,646,346
OpenGL mix fix pipeline and shader program (Qt)
I'm working on a old code that used fixed function pipeline, the scene is a bit complex but works fine. For the sake of simplicity, I replaced it with one blue triangle : void RenduOpenGL::paintGL() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glViewport(0, 0, this->width()...
Short (with code) answer: The VBO and the prog.enableAttributeArray and prog.setAttributeBuffer should be in the VAO. Something along the lines: float vertices[] = { 0.6, 0.6, 0.0, -0.6, 0.6, 0.0, 0.0, -0.6, 0.0, }; prog.bind(); // glUseProgram(shader_program); vao.create(); // glGenVertexArrays(...) va...
70,646,188
70,646,228
Why does it display the sum if numbers aren't between the 2 values?
I want it to not display the result of the sum if the numbers are lower or equal to 1 or 1000. I don't know if using if is the best way, but that's what I tried using, and I don't really understand why it doesn't work. I also tried writing conditions with || and &&, but those don't work either. #include <cmath> #includ...
The expression in this if statement if ( 1 <= a, b, c <= 1000) is an expression with the comma operator. It is equivalent to if ( ( 1 <= a ), ( b ), ( c <= 1000 ) ) and the value of the expression is the value of its last operand. That is this if statement is equivalent to if ( ( c <= 1000 ) ) It seems you mean if (...
70,646,201
70,646,252
What does array index operator do on an object if not overloaded?
I'm writting Matrix class and got to the point where I need to create an array of Array objects, but Array can't have constructor with no arguments ( it need m argument to allocate memory for it ). I searched and haven't found the solution, people only sugest doing it with Vector object, but I am not allowed to do it w...
You have this definition: int* data. So by default, given a pointer operand, data[x] is translated into *(data + x) by the C++ compiler.
70,646,265
70,655,931
OpenACC: How to force copy data from host to device even if already present?
I am trying to build some time metrics for an OpenACC code. One of the most time consuming tasks is copying a big array from the host to the device. I am running the same code multiple times in order to take an average and get a more accurate value. However, I ran into the problem that this big array is only copied onc...
Assuming that these variables are not in another data region, they wouldn't be present so would be copied. But if you want to be sure, you can use "create" in the data region and then use the "update" directive to explicitly copy the arrays. #pragma acc data create(data[0:N*4], grid[0:n*n], cell_ij) { #pragma acc up...
70,646,384
70,646,572
Call a function that takes in a pointer to the current class from inside the class
I am trying to call a method outside of the Entity class that takes in an entity pointer as a parameter, and I am getting this compiler error: C3861: 'PrintEntity': Identifier not found My code looks like this: #include <iostream> class Entity { public: int x, y; Entity() { this->x = 0; this...
One solution is to forward declare Entity and PrintEntity before the class definition and implement PrintEntity after the class definition: class Entity; void PrintEntity(Entity*); class Entity { // ... }; void PrintEntity(Entity* e) { std::cout << e->x << ", " << e->y << std::endl; } Demo (Note that GetX d...
70,646,389
70,646,481
is it safe to call delete inside a remove_if predicate?
I have a vector std::vector<Object*> objects; And a method that removes an object if it's found: void Remove(Object *o) { objects.erase( std::remove_if( objects.begin(), objects.end(), [&o](Object *_object) { if (o == _object) { de...
Would this invalidate the iterator or leak memory? Memory doesn't get leaked by individual bits of code; it gets leaked by complete programs. Someone has to be responsible for deallocation, but just because it doesn't happen here, doesn't mean it won't happen at all. Not calling delete here would also not "leak memor...
70,646,523
70,648,797
How to check whether two array or list are identical?
In python, one can easily determine whether arr1 is identical to arr2, for example: [1,2,3] == [1,2,3] {1,2,3} == {3,1,2} (1,2,3) == (1,2,3) How do you do this in C++? //#include <bits/stdc++.h> using namespace std; int main() { // if ({1, 2}== {1, 2}) // cout<<" {1, 2}== {1, 2}"; if ((1, 2)== (2, 2)) ...
In python, one can easily determine whether arr1 is identical to arr2, for example: [1,2,3] == [1,2,3] In Python the square brackets are enough to denote a list. In C++, which a statically typed language, you can't do this. You have to declare the arrays or vectors using their types: std::vector<int> vec1 = {1, 2, 3...
70,647,024
70,649,680
Qt GUI hanging with worker in a QThread
I have a worker which needs to complete an arbitrary blocking task class Worker : public QObject { Q_OBJECT; public: using QObject::QObject; public slots: void start() { for (int i = 0; i < 10; i++) { qDebug("I'm doing work..."); Sleep(1000); } } }; ...
The problem is that the worker is actually not moved to thread (Isn't a warning written to console? I bet it is.), because its parent, i.e. MainWindow instance is still in the GUI thread. When moving to thread, you can only move the whole hierarchy of objects by moving the very top parent. You cannot have parent in dif...
70,647,429
70,648,147
Makefile Selecting type of compilation
How can I make it so that I can use the commands like make debug or make release, such that they both invoke the set of rules below but with different compilation flags (e.g. -g for debug and -DNDEBUG for release)? # Object Files OBJECTS := $(addprefix $(BUILDDIR)/,$(SOURCEFILES:.cpp=.o)) compile: $(OUTPUT) $(...
It's not difficult, just use target-specific variable values: debug: CXXFLAGS += -g -whatever release: CXXFLAGS += -DNDEBUG -otherstuff debug release: $(OBJECTS) link things... But there's a problem with your design. You build an object foo.o with either the debug flags or the release flags, but either way you ...
70,647,441
70,647,627
How to determine the offset of an element of a tuple at compile time?
I need to determine the offset of a certain indexed element of a tuple at compile time. I tried this function, copied from https://stackoverflow.com/a/55071840/225186 (near the end), template <std::size_t I, typename Tuple> constexpr std::ptrdiff_t element_offset() { Tuple p; return (char*)(&std::get...
You can use this: template <std::size_t I, typename Tuple> constexpr std::size_t element_offset() { using element_t = std::tuple_element_t<I, Tuple>; static_assert(!std::is_reference_v<element_t>); union { char a[sizeof(Tuple)]; Tuple t{}; }; auto* p = std::addressof(std::get<I>(t));...
70,647,584
70,647,882
C++ class function pointer
I have a request for function pointer by C++. below is the sample what I need: in API file: class MyClass { public: void function1(); void function2(); void function3(); void function4(); }; in main file: MyClass globalglass; void global_function_call(???)// <---- how to do declara...
To do what you are asking for, you can use a pointer-to-member-method, eg: MyClass globalglass; void global_function_call(void (MyClass::*method)()) { (globalglass.*method)(); } int main() { global_function_call(&MyClass::function1); global_function_call(&MyClass::function2); global_function_call(&My...
70,647,706
70,647,822
Exporting an inline struct in c++
I was programming in c++ and I came across an issue. I had a struct for the player in a header file and wanted to use the struct in two different files. struct { float x; float y; } player; I tried many things and I did much research but it always resulted in errors or the variables not updating throughout a...
am wondering if this is a known syntax Yes. The syntax of variable and class definition is known. In this case, you define an inline variable named player which is of a class type named EXPORT. There is no "exporting" involved here.
70,647,738
70,654,396
How does QIODevice::readLine(qint64 maxSize = 0) works?
The documentation of this method states: QByteArray QIODevice::readLine(qint64 maxSize = 0) This is an overloaded function. Reads a line from the device, but no more than maxSize characters, and returns the result as a byte array. However, I notice that even if we pass maxSize = 0, viz. don't pass anything, the readL...
It's not mentioned in the Qt API documentation, but passing in a value of 0 as the maxSize argument is treated as having a special meaning of "as many bytes as possible". Evidence of that intent can be seen at line 1466 of the qiodevice.cpp source file in Qt: if (maxSize == 0) maxSize = MaxByteArraySize - 1;
70,649,326
70,649,393
generateKey cpp function
Hello i have a problem with one of my functions generateKey() that returns char*. Its generate the key normal but when i print it i can see something weird. char* aesStartup::generateKey() { const char alphanum[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; char newKey[32]; srand(time...
You have two serious problems: First of all you seem to have forgotten that strings in C++ are really called null-terminated strings. For an array of characters to be a "string" it needs to be terminated with the '\0' character. Which also means a 32-character string needs to have 33 elements. The second problem is t...
70,649,378
70,649,575
How do I suppress deprecation warnings for function parameters?
I previously used such pragmas, which I seem to recall worked both with GCC (ubuntu) and clang (macos). They seem to be effective to suppress warning from header #includes. // test.cpp struct [[deprecated]] Foo {}; #pragma clang push #pragma clang ignored "-Wdeprecated-declarations" int main() { auto foo_fun = [](c...
You are missing a diagnostic keyword in your pragma declarations: #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" ... #pragma clang diagnostic pop
70,649,490
70,649,622
I have a variable b in parent class and when i try to access variable b from sum3 class it shows ambiguous b error
I have a variable b in the parent class and when I try to access variable b from sum3 class it shows an ambiguous b error. And if I remove the sum from inheritance it will give "clas.cpp|25|error: 'int sum::b' is inaccessible within this context| " error what to do? #include<iostream> using namespace std; class sum { ...
this is because you are inheriting from both sum2 and sum classes but sum2 is inheriting from sum so it inherits the variable b also so when you intend to use the variable b inside of the class sum3 the compiler doesn't know which variable you want because there is one in class sum2 and one in class sum with the same n...
70,649,825
70,661,182
Topological Sorting using Kahn's Algorithm
I wanted to know ,what does the following part of code mean , I understood the whole function but the for loop at the end is making me confused and not able to understand. So please tell me what it is doing there? void topologicalSort(vector<int> adj[], int V) { vector<int> in_degree(V, 0); for (int u = ...
Kahn's algoritm (which has nothing to do with BFS): Find all the vertexes with in-degree 0 and put them in a queue (q in your code). Pick a vertex from the queue, output it, and delete it from the graph. Deleting the vertex will reduce the in-degree of all its neighbors. Some of these could reach in-degree 0 -- put t...
70,650,470
70,651,141
How to avoid shared pointers in C++ caused by try/catch?
I use shared pointers because of variable can only live in block where it was created. int main(void) { std::shared_ptr<project::log::Log> log; try { log = make_shared<annmu::log::Log>("error.log"); // can throw eception } catch(std::exception &e) { std::cout << "Error\n\n"; re...
It is always good practice to avoid using shared pointers, unless you are actually sharing the pointer. You could use a unique_ptr as a drop in replacement. It is not a bad idea to have a non-throwing constructor, which constructs the object into a valid-empty state. Handling exceptions in construction is always more c...