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
65,654,874
65,654,996
C++ Compilation Error Fixed Itself (Trying to figure out why)
I created a new directory & file using cmd (I don't think this has anything to do with it but I'm listing my steps) so I can start learning C++, I then opened the file in vscode and tested out this basic function: #include <iostream> using namespace std; int main(){ cout << "test << endl; return 0; } When I trie...
Thanks to the two comments I realize what happened. The errors were caused because of the space in my file name; therefore, the errors were quite straight-forward. "C++" and "Tutorial" as separate parameters do not exist in the path, and changing the file name to "test.cpp" worked because the file name was treated as a...
65,655,119
65,655,197
Difference between const char *p = "some_string" and const char[] = "some_string" in terms of memory allocation
const char *fun1() { const char *a = "hello"; return a; } const char *fun2() { const char a[] = "hello"; return a; } int main(int argc, char *argv[]) { printf("%s\n", fun1()); printf("%s\n", fun2()); return 0; } Output: cpp:12:12: warning: address of local variable 'a' returned [-Wreturn-...
In your case the bytes of the string in fun1() live in static memory. in the other function the bytes are copied from the static memory into a buffer on the stack on initialization. It is undefined to access the returned string that is returned from fun2() because the array on the stack does not exist anymore. fun1() c...
65,655,329
65,655,874
How to iterate through a csv file and then split each column into a vector
So I have a CSV with 2 columns - One for A song and one for the artist of that song. For example The Pretender,Foo Fighters In Bloom,Nivana Champagne Supernova,Oasis Starlight,Muse Will We Talk?,Sam Fender I am converting a python program that I wrote a while back into c++. In that program it uses the csv library to r...
According to your CSV file, you could have a solution like this : #include <sstream> #include <string> #include <fstream> #include <iostream> #include <vector> int main() { std::vector<std::pair<std::string, std::string>> result; std::string line; std::string first, second; std::ifstream ifs("Songs.csv...
65,656,311
65,656,671
print digits separately and print number n for n times in front of it
I wanna have digits of an integer separately and print digit n for n times in front of that digit Like: 4: 4444 3: 333 I've got this so far but it prints 4: 3: and I dunno how to make it to what I want : #include <cstdlib> #include <iostream> #include <math.h> #include <stack> int countDigitsInInteger(int n) { int...
You could use std::to_string to convert your integer to a std::string and then loop over the chars in that string. Example: #include <iostream> #include <string> int main() { int number = 43; // or read it from std::cin std::string snumber = std::to_string(number); for(auto ch : snumber) { // a range...
65,656,677
65,656,854
How to bind reference to stack allocated class in class constructor?
I have this class class HumanA { public: HumanA(std::string name, Weapon weapon); ~HumanA(void); inline void attack(void) { std::cout << _name << " attacks with his " << _weapon.getType(); } private: std::string _name; Weapon &_weapon; }; and this const...
Think: What is the scope and "time of living" of Weapon weapon object? What is the answer to the same question for the member Weapon &_weapon? The answer to the first question is this: weapon exists as long as the constructor is executing. This is a stack-allocated variable that ceases to exist the moment the constr...
65,656,920
65,656,971
non default constructible parameters within lambdas in fold expressions
I'm trying to see if it's possible to use a parameter that is not default constructible within a lambda as part of a fold expression. Following code works if T is default constructible. template <typename ...T> struct X { void foo() { ([](const T&) { if (sizeof(T) < 4) { std::cout ...
The lambda doesn't need a parameter: ([]{ if (sizeof(T) < 4) { std::cout << "Small block size: " << sizeof(T) << std::endl; } }(), ...);
65,657,137
65,657,603
How to know the format of the parameter inside a function C++
I have been trying to make a Convert.To command like in C# in C++ but I dont want to do it like "IntToString" Instead I want to make it like "ToString" just like in C#. I was wondering how can I know the format of the parameter given inside the function? Or is there any other way to do this? #include <iostream> #inclu...
When you say - Format of the parameter given inside the function, do you mean, how do you know the data type of the parameter. If that's the case, you will have to write functions for all the data types for which you want to support conversion, inside your Converting class with same function name, this is called functi...
65,657,668
65,694,327
SDL2 installing on xCode
I have downloaded SDL2.frameworks from https://www.libsdl.org and installed it into /Libraries/Frameworks/. Then I have pointed xcode a path of frameworks and headers in 'Build Settings', in 'General' 'Frameworks and Libraries' pointed at framework file libSDL2-2.0.0.dylib . The I type #include <SDL2/SDL.h> and try to...
I have figured it out. I have installed homebrew from https://brew.sh I typed in terminal brew install sdl2 Then I have showed the path of framework (in xCode select project file >> build settings >> header search paths) and using cmd+shift+g type /usr/local/include In General Frameworks & Libraries put libSDL2-2.0.0....
65,658,277
65,658,354
C++ remove function moving characters to the left
I recently tried a code mentioned somewhere on this site to remove blank spaces in a string. The answer suggested the function remove from the algorithm library (amazingly explained here: https://www.geeksforgeeks.org/stdremove-stdremove_if-c/) but it gives an unexpected output. It replaces all the blank spaces with so...
Interesting thing about std::remove is that it does not actually remove anything. =) You will need to erase the character by yourself like this: #include <iostream> #include <algorithm> using namespace std; int main() { string a; int b; getline(cin, a); a.erase(remove(a.begin(), a.end(), ' '), a.end()...
65,658,534
65,658,584
c++ primer - value of variables
I started reading C++ Primer, 5th Edition and I'm having troubles understanding one thing when it comes to std::cin. The following is the code they present as their example. The idea behind it is that a bookstore is recording its transactions and the program should be able to sum back-to-back transactions as long as th...
I agree, the comments appear to be swapped. They should be: Sales_item total; // variable to hold the running sum Sales_item trans; // variable to hold data for the next transaction
65,658,816
65,672,551
xsd.exe does not seem to work for C++ with newer versions of Visual Studio
I am trying to use the xsd.exe tool to generate C++ classes from XML schema files. According to this post I should simply be able to use the tool from a Visual Studio developer command prompt, but it doesn't seem to work for C++ in newer versions of Visual Studio (2017 or 2019) When I try to execute the command I get t...
xsd.exe was deprecated in VS 2017, with a note under XSD Task reading: Starting in Visual Studio 2017, C++ project support for xsd.exe is deprecated. You can still use the Microsoft.VisualC.CppCodeProvider APIs by manually adding CppCodeProvider.dll to the GAC. This was confirmed in Microsoft sanctioned comments unde...
65,659,048
65,659,142
Fast algorithm to allocate and release integer-like handles in C++
I need a class that can allocate a unique integer (handle) and assign it to something object. And then release it in order to be used later. This algorithm should be fast. What data structure should I use? vector is fast to access data but long to erase or add(but it also important), list is long to access data. Maybe ...
I would simply use 64-bit integers. For allocation, I'd use a simple counter. To deallocate...well, I'd simply ignore the request to free a handle. You can ignore deallocation, because with 64-bit handles, you can quite literally allocate handles for decades at a time without even coming close to running out of fresh h...
65,659,233
65,663,307
CreateRemoteThread + LoadLibraryA doesn't do anything despite succeeding
Despite the fact that memory allocation/write, finding LoadLibraryA address and creating a remote thread return valid (not NULL) results, absolutely nothing happens after that (mainly, the DllMain of the loaded DLL doesn't seem to get called). #define PROC_NAME L"TestConsole.exe" #define DLL_NAME "TestLib.dll\0" HANDL...
The entry.th32ParentProcessID is the identifier of the process that created this process (its parent process). which means you did inject into the parent process of the target process (explorer.exe in my test). You should use entry.th32ProcessID instead. In addition, the open permission PROCESS_ALL_ACCESS used in OpenP...
65,659,486
65,660,163
Is there a way to declare a member in a way that will make it static in all derived classes?
I have several abstract classes that need to manage static vectors containing pointers to every instance of themselves. Here's a simplified example of how one of those classes looks: class AbstractBase1 { public: AbstractBase1() { allInstances_.push_back(this); } AbstractBase1(const AbstractBase...
You might use template: template <typename Tag> class AbstractBaseT { public: AbstractBaseT() { allInstances_.push_back(this); } AbstractBaseT(const AbstractBase1& source) : AbstractBaseT() { //Copy data from source } AbstractBaseT(AbstractBaseT&& source) : AbstractBase1() { //Mo...
65,659,509
65,659,613
Is it possible to copy wchar_t* strings to vector as a new string of characters?
What I am trying to do is to save multiple different pointers to unique wchar_t strings into a vector. My current code is this: std::vector<wchar_t*> vectorOfStrings; wchar_t* bufferForStrings; for (i = 0, i > some_source.length; i++) { // copy some string to the buffer... vectorOfStrings.push_back(bufferForS...
The simplest way is to use std:wstring, provided by the STL, as the type for your vector's elements. You can use the constructor that class provides to implicitly copy the contents of your wchar_t*-pointed buffer to the vector (in the push_back() call). Here's a short demo: #include <string> #include <vector> #include ...
65,659,757
66,226,963
Anonymous Types in IDL C++11 for OpenDDS
I am using a DDS and need to be able to send data received from various devices. I have files from an IDL file using RTI DDS. However, it seems like these IDLs are different as OpenDDS using C++11 IDL mapping. The struct struct ddsServicerDynamicsData { ddsVector3_dbl rpos_eci; //position relative to Ear...
Use a typedef to create a type with the array size you would like, then declare your variable with the new type. Example: typedef float AntennaStateType[3]; @topic struct ddsServicerDynamicsData { AntennaStateType armState0; AntennaStateType armState1; };
65,659,802
65,659,829
Using c++ 20 Concept to check if a function returns a const value
I'm trying to use concepts in order to be able to detect if a given type's begin function returns an iterator to "const T&" or just to "T&". But I'm not sure how one would best go about it, I have tried the following: #include <iostream> #include <concepts> #include <vector> #include <set> template <typename T> concep...
The direct issue here is that decltype((*t.begin())) for std::set<int> gives you the type int const&, and the type trait std::is_const<T> checks if T is some type U const. A reference is not const. You need to strip the reference first: template <typename T> concept IsConst = std::is_const_v<std::remove_reference_t<T>>...
65,660,538
65,660,989
C/C++ read binary files (flaot numbers) at one time
I was wondering is there a way to speed up fread in C or C++? For example, if I want to read a binary file containing 100 4-byte float numbers. I do: float *data=(float*)calloc(sizeof(float), 100); float datatmp=0.0; f=fopen("datafilename","rb"); for(int i=0;i<100;i++){ fread(&datatmp,4,1,f); data[i]=datatm; } fl...
you can read all one time. fread(data,sizeof(float)*100,1,f);
65,661,151
65,661,826
What is the difference between `void operator=(T&&)` and `T& operator=(T&&)`?
class base { public: base(const base&) = delete; base() { cout << "construct" << endl; } ~base() { cout << "destruct" << endl; } int a; int b; /* The difference explanation I desired is here */ void operator=(base&& other) // base& operator=(base&& o...
In one case, a=b=c works. In the other, it does not. That is it. Traditionally, a=b=c does b=c then assigns the result to a. If your operator= returns void, it instead fails to compile.
65,661,258
65,661,326
Type deduction of reference_wrappers with Args
I have a template function: template<class... Args> void foo(Args&&... args) { boo<std::decay_t<Args>...>(std::forward<Args>(args)...); } Now what I want to do is to call foo function several times like this: int value = 123; const int& cr_value = value; foo(value ); foo(std::cref(value )); In first case I call b...
You might do something like: template <typename T> struct unwrap { using type = T; }; template <typename T> struct unwrap<std::reference_wrapper<T>> { using type = T&; }; template <typename T> using unwrap_t = typename unwrap<T>::type; template<class... Args> void foo(Args&&... args) { boo<unwrap_t<std::d...
65,661,552
65,664,822
Getting an out of range error iterating through a 2d vector in C++
EDITED For some reason when I run this on Repl.it, I get an out_of_range error All I am trying to do is iterate through a 2d vector vertically, and do some other implementations. This is the code: #include <iostream> #include <vector> using namespace std; void matrixElementsSum(vector<vector<int>> matrix) { int ...
If each vector has the same length, it's enough to just save the size, assuming there is at least one element. void blabla(vector<vector<int>> matrix) { if (matrix.size() == 0) return; const size_t jmax = matrix.front().size(); for (size_t j = 0; j < jmax; j++) for(size_t i = 0; i < matrix.size(); i++...
65,661,972
65,662,047
What does it mean that mmap doesn't work 'when a large chunk becomes “locked” in between smaller ones'?
I was reading the GNU C library document for the GNU memory allocator. https://www.gnu.org/software/libc/manual/html_node/The-GNU-Allocator.html In the paragraph about using mmap to allocate big chunks of memory, it says The other way of memory allocation is for very large blocks, i.e. much larger than a page. These r...
Consider a long-running logical function of a program that allocates lots and lots of memory. And at the same time that logical function is running, other bits of code allocate very small chunks of memory. Later on, that long-running function may finish and the massive amount of memory it allocated is all freed. But lo...
65,662,707
65,663,717
windows - how to link against API sets (*ms-win*) instead kernel32.dll, ntdll.dll etc.?
How do I specify explicitly to MSVC compiler / linker to link against API sets (*ms-win* pattern matcing dlls) instead kernel32.dll, ntdll.dll etc.? For example, I've created a simple dll, which just calls a few basic WinAPIs. When examining it's IAT (via CFF Explorer, python pefile library etc.) there's only kernel32....
API sets are used internally, meaning even the 'legacy' system DLLs on Windows 7, 8 or 10 use them. Hence there's no reason you need to use them directly. That said, there are a number of 'umbrella' libraries you can use instead of linking against classic KERNEL32.DLL, etc.: onecore.lib onecoreuap.lib onecore_apiset.l...
65,662,843
65,663,061
IShellFolder::GetDisplayNameOf return gibberish
I'm new to winapi and c/c++ and I try to print out the names of the icons on the desktop using IShellFolder::GetDisplayNameOf but for some reason I'm getting gibberish. Here is my code: int main() { HRESULT hr; IShellFolder* deskFolder; hr = SHGetDesktopFolder(&deskFolder); IEnumIDList* listilist; ...
According to the document: uType Type: UINT A value that specifies the desired format of the string. This can be one of the following values. STRRET_CSTR The string is returned in the cStr member. STRRET_OFFSET The uOffset member value indicates the number of bytes from the beginning of the item identifier list where ...
65,664,025
65,664,108
Map::operator[] always requires a default constructor
#include <iostream> #include <string> #include <map> using namespace std; class x{ public: string s; //x(){cout<<"default"<<endl;} x(string s=""):s(s){cout<<"mine"<<endl;} }; int main() { map<int,x> m; m.insert(pair<int,x>(1,x("me"))); cout<<m[1].s<<endl; } I understand that map::operator[] requires de...
I understand that map::operator[] requires default cst for when element is not present, [...] That's not quite correct. map::operator[] always requires a default constructor because the element might not be present. Whether it actually is present is not that relevant, because whether a map<T> has a operator[] is deci...
65,664,139
65,664,182
recieve object type by argument
I'm trying to pass object type by argument, and i couldn't find any way to do that. this is what i've tried so far: I'm trying to do a generic function for multiple classes (int, double etc.) void changeObject(class this) { static_cast<this&>(object[0][0]).foo() } but I couldn't make it work, this is not for H\W, ...
The only way to do this is to make changeObject() be a template function, eg: template<typename T> void changeObject() { static_cast<T&>(object[0][0]).foo(); } You can then call it like this: changeObject<DesiredTypeHere>();
65,664,452
65,664,932
How to generate every possible Adjacency Matrix for graphs with N nodes?
I'm currently working on a small project for a course related to Graph Theory. The current task I've ran into trouble with is generating every non-isomorphic graph with N nodes (where N <= 4). More specifically, I'm not sure how to achieve a certain 'step' of my algorithm. The idea is to generate every possible graph w...
This code will generate all 2^(N*N) adjacency matrices for size N: #include <iostream> #include <vector> unsigned int pow(unsigned int b, unsigned int e) { if (e == 0) return 1; if (e == 1) return b; if (e % 2 == 0) { return pow(b, e/2) * pow(b, e/2); } return b * pow(b, e - 1); } void gen...
65,664,503
65,665,404
create c++ binary with make for iOS
I am trying to create a binary using a makefile with iOS as target platform. However, I have only seen the option to use a makefile for macOS as target platform. Is there a way to this also for iOS? Background: I am trying to embed Google's OR tools (optimization solver) to an iOS app. Those OR tools are written in C++...
Make allows you to do whatever you want, provided you can describe it in the makefile. Note that make doesn't help you get around the low-level details of the task (build C++ code for iOS), you have to figure it all out yourself. Make merely automates the repetitive tasks. So the tricky part is setting up your developm...
65,664,672
65,738,300
How to create a constexpr array with a sequence of string_views at compile time?
I would like to create a constexpr std::array<std::string_view, ConstexprNumber>. It should for example contain constexpr std::strings_view's like this: "text0", "text1", "text2", ..... "textn" I came up with the following initial solution: #include <iostream> #include <array> #include <utility> #include <string> #incl...
I now found a solution that finally satisfies my needs. Because of many good answers by SO users and additional answers to my question here, I will now use the following code. #include <iostream> #include <algorithm> #include <iterator> #include <array> #include <string> // Specification for the output that we want to...
65,665,439
65,665,536
Is it possible to make static C++ library self contained?
If my library has external dependencies is it possible to include those libraries to my own static library, that users of my library wouldn't need to link to those dependencies? Or should I make it dynamic library? library.h #ifndef AMAZING_CPP_LIBRARY_H #define AMAZING_CPP_LIBRARY_H #ifdef __cplusplus extern "C" { #e...
Is it possible to make static C++ library self contained? This is implementation specific, and could be sometimes illegal. Notice that most C++ standards (read e.g. n3337) don't even mention libraries (in particular, related to your compiler, e.g. GCC and to its standard C++ library libstdc++) But your C++ library wo...
65,665,664
65,667,979
handle HPDF_FAILD_TO_ALLOC_MEM during creation of pdf file
I am using libharu library for creating pdf and getting following into system hPDF error error_no=4117, detail_no=0 which HPDF_FAILD_TO_ALLOC_MEM My query may I know the reason behind this error. and application got crash. is there way to handle this error as I am not able generate pdf **Error: hPDF error error_no=41...
The only time I've seen this error was when the PDF became so large it consumed all available memory. In my case, I was creating images using the PDF primitives (like a filled rectangle). You really haven't given enough information to help diagnose the problem. Version of libHaru, 32 or 64 bit, generally what you are t...
65,665,766
65,665,972
Iterate in reverse order through the parameter-pack of a variadic template function
I'm trying to iterate in reverse order through the parameter-pack of a variadic template function. My idea was to use tail recursion and a specialized "empty" template function to stop the recursion: #include <iostream> template<> void f() {} template<int H, int... T> void f() { f<T...>(); std::cout << H << s...
Because you should provide, well, template declaration before specializations: #include <iostream> template<typename...> void f(); template<> void f() {} template<int H, int... T> void f() { f<T...>(); std::cout << H << std::endl; } int main() { f<1,2,3,42,5>(); return 0; } Here we go: https://id...
65,665,935
65,669,207
Transform the type of a thrust vector
I am somewhat new to CUDA and thrust and I am currently struggeling with the following problem: I have 2 structs carrying data. struct S1 { unsigned long A, B, C; } struct S2 { double A, B, C; } At the start of the program I have a vector of the first struct and I want to use the GPU as well as a special func...
As already pointed out in the comments I misread the documentation (see here). The solution is to use a unary functor and another way of calling the thrust::transform. // this functor converts values of S1 to S1 by multiplying them with .5 // in the actual scenario this method does perform much more useful operations s...
65,666,277
65,666,345
Calling class constructor later in another class method in C++
I'm writing Class A, and it has a constructor that initializes values. I'm creating an instance of Class A in another Class B like so: #include <iostream> class A { public: int value; A(int value) { this->value = value; } void print_string() { std::cout << "talking..."; } }; clas...
There is no default constructor for A. You should use a member initializer lists B(int b_value): new_a(b_value) { } Your constructor B(int b_value) { new_a = A(b_value); } tries to default initialize new_a and then to assign A(b_value) to it. But default initialization is not possible without ...
65,666,393
65,666,479
Cant seem to work a second for loop with a pointer for an array
I have a simple program that calculates for mpg using arrays and pointers When I input miles, it works perfectly but when i input gallons I can only input until 5th. any advice? At first when it was still a for loop it was until 3rd only but when i used try and catch it was until 5th I tried changing ctr value after th...
galPtr = &gallons[size]; milPtr = &miles[size]; Since size is 10, this: Sets galPtr to point to the 11th element of gallons. Set milPtr to point to the 11th element of miles. That's what the above code means in C++. Of course, both arrays have only ten values, and attempting to obtain a pointer and using the point...
65,666,628
65,898,185
Compiled C++ build doesn't output nor provide error
I'm using cmake and mingw32-make to build my C++ SDL2 project called Something. After I did cmake . it generated few folders and files, where I went inside the build folder. It had a make file, so I used make in that directory. Then it generated my executable which should be something.exe. It did, but when I try to run...
Must not forget to put the .dll(dynamic link libraries) in the same directory as the executable in order for the executable to work
65,666,637
65,666,787
How to reduce for loops in C++
How can I reduce the following program to 2 for loops and 1 print statement: for (int i = 1; i <= iter; i++) { for (int j= 1; j <= row; j++) { printf("*"); for (int k = 1; k <= col; k++) { printf("_"); } printf("*\n"); ...
You can merge any count of loops, using multiplication and rest from division (just the multiplication has not to overflow). void f(int iter, int row, int col) { for (int i = 0; i < iter * row * col; i++) { printf("%s%s%s%s", i % col == 0 ? "*" : "", "_", i % col == col - 1 ? "*\...
65,666,863
65,682,380
OpenMP offloading in a dynamic library fails to compile
I want to compile C code with OpenMP offloading and create a dynamic library libtest.so. When I use the following command: gcc -fPIC -shared -fopenmp -foffload=nvptx-none="-fPIC" test.c -o libtest.so I get this error: /usr/bin/ld: /tmp/ccWnqb5o.target.o: relocation R_X86_64_32 against `.rodata' can not be used when m...
I spoke to the GCC developers and it seems to be a bug. They seem to have it resolved for GCC 11, but the fix was not backported. See https://gcc.gnu.org/g:a8b522311beef5e02de15427e924752ea02def2a for more information.
65,667,346
65,667,466
Is using std::tuple to implement operator<, = etc. efficient and correct?
I find that I am recently often using std::tuple to implement ordering, equality operators, like in below example. Is this a correct and efficient approach? Its especially usefull when multiple variables should be compared in such operators. #include <iostream> #include <unordered_map> #include <unordered_set> #include...
It's correct, but it's not efficient, because the constructor of std::tuple will copy all the values. This also means you can't use it to compare non-copyable types. Instead you could use std::tie, which needs a bit less code and doesn't copy the values, but creates a tuple of references. Your operator< would then beco...
65,667,425
65,667,553
How to return to the beginning of the console in printing in C++?
if I have this code : using namespace std; int main() { int count = 0; while (true) { cout << "here: " << count++ << " again\r"; } return 0; } After it finishes, it will go back to the beginning of the line with carriage return. Now assume I have more than one line like so : using nam...
Positioning of text in a terminal is outside the scope of the C++ standard. You can use portable ncurses library for positioning of text on terminal/console.
65,667,907
65,668,818
CRTP with full template specialization
Why is the following code is not correct? template <typename T> class B { public: auto foo() -> decltype(static_cast<T*>(this)->foo()) { return static_cast<T*>(this)->foo(); } }; template <typename X> class A: public B<A<X>> { public: X foo(); }; template <> class A<int>: public B<A<int>> ...
Issue with CRTP, is that derived is incomplete from CRTP. So -> decltype(static_cast<T*>(this)->foo()) is problematic for 2 reasons, as T is incomplete: it is not yet derived class of B<T>, std::declval<T>().foo() might solve that issue. T::foo is not yet declared. Possible solution is to get rid of explicit return ...
65,668,283
65,668,339
c++ process finished with exit code
I'm new to C++ and working on a function that first prompts the user to enter number of chair, surface area, color of the chair and then prompts the user to enter the type of wood - m for mahogany, o for oak, or p for pine and ideally any other entry should be rejected. After entering the chair color I'm getting "Proce...
Your program invokes undefined behavior by falling at end of non-void functions without executing return statement. You have to add return statements or change the return types of functions to void. Your return type of the function takeTypeOfWood is already void, so it seems you should use void for the return types of ...
65,668,445
65,668,640
mmap() cannot allocate memory when repeatedly mapping and unmapping one single page
I have read many SO (and other) questions, but I couldn't find one that helped me. I want to mmap two files at once and copy their content byte-by-byte (I know this seems ridiculous, but this is my minimal reproducibly example). Therefore I loop through every byte, copy it, and after the size of one page in my files, I...
The very first iteration of the loop attempts to unmap something that was never mapped, and passes a completely uninitialized pointer to munmap. Not once, but twice. Finally, munmap expects a pointer to the mmap-ed memory, and not a pointer to a pointer to the mmap-ed memory. The shown code fails to check the return st...
65,668,464
65,674,118
Virtual key to character conversion depending on the locale
I can't translate a character according to the set keyboard layout.Tried several variants, but it doesn't work. I enter the Russian character "Л" and the output is getting the English character "K". There is no translation. The input should be "Л" and the output should be "Л". First version: std::wstring StandardKeyToS...
Virtual key to character conversion depending on the locale: std::wstring StandardKeyToStringW(DWORD VKey) { static WCHAR name[32] = L""; static BYTE kbState[256] = { 0 }; DWORD idThread; idThread = GetWindowThreadProcessId(GetForegroundWindow(), nullptr); long code = MapVirtualKeyExW(VKey, MAPVK_VK...
65,668,961
65,680,136
Qt auto test changes only effective after "rebuild" not after "build"
I added an auto test project to my C++ Qt project (QT 5.15.1, MSVC 2019, host and target: Windows 10). But changes in the test source files do only take effect if I rebuild and run the test project, but not if I just build and run, which usually works fine for my main app project. I guess I miss an important setting in...
I solved this myself, by the following steps (after making the above changes): close Qt Creator delete the project.pro.user file in the project root directory re-open the Project in Qt Creator (probably this was not necessary) execute qmake at project.pro Now a simple build does update files in the build directory pa...
65,669,053
65,669,135
How do I implement a while loop to this function
I am working on a school project where we will make a contact book. In one of the functions, it must find contacts using the first name. The error that occurs is that it only shows one contact in the vector. I want all contacts with the same name to be displayed. How do I implement a loop or counter (i++) so that it in...
One way is adding a parameter to determine which element to start from. int findTargetFirstName(vector<Kontaktbok>& bok, string target, int start = 0) { for (int i = start; i < bok.size(); i++) if (bok[i].fnamn == target) return i; return -1; } void search(vector<Kontaktbok>& bok) { if(bok.size() ...
65,669,299
65,669,716
Initializing a string with a single character
I want to initialize a std::string with a single character. The following code doesn't work: int main() { string s = 'c'; cout<<s; return 0; } Error: error: conversion from ‘char’ to non-scalar type ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ requested string s = 'c'; But the following...
When you do string s = 'c'; you are basically invoking constructor initialisation rather than an assignment operation. But there isn’t any constructor for std::string that takes only a single char as input. There is however one std::string(n, c), where n is the number of characters c in the string. When you do s = 'c'...
65,669,754
65,670,900
C++ - How to remember if a file has already been moved?
Right now I have a program that moves files automatically from one folder to another only once. So if that file gets into that folder again, it shouldn't be moved.The application is being executed every 30 minutes. So right now what I have is if LastWriteTime is older than 30 minutes, don't move it. It works, but using...
If there are only two locations like you mention in your example (ie: a /main/ and a /main/failed/), then you really only need to know the file name, and how many times before you've moved it. So you could store a file in /tmp/ like: file_1.txt 1 file_7.txt 2 another_file.txt 1 ... Then in pseudo code, your program co...
65,670,165
65,670,216
Is length and this->length are same in this code in c++?
I have an overloaded operator: rectangletype rectangletype::operator+(const rectangletype& rect) const { rectangletype temprect; temprect.length = length + rect.length; return temprect; } And this is the main: int main() { rectangletype r1(23); rectangletype r2(27); rectangletype r3 = r1 + r2; ...
When you override an operator, the this keyword refers to the object on the left side of the operator in the statement. In the overload function, you can explicitly use this->, but it is implied and therefore not necessary.
65,670,435
65,671,602
Reading .txt file into a c++ stream, some strings are consist of two separate words
I have to read a subway network described in a .txt file into a graph consisting of nodes and edges for a university project, so far I've been able to read the file and automatically check for strings, doubles or ints. Now the problem is that some station names consist of two separate words and my code will jump furthe...
Crude code to show you the principle. Input file, train.txt: U1 Warschauer Str -> Schlesisches Tor: 0,8 2 U1 Schlesisches Tor -> Gourlitzer Bahnhof: 0,9 2 U2 Pankow -> Vinetastrasse: 0,5 1 Outputs: Station1=U1 Warschauer Str , Station2=Schlesisches Tor Station1=U1 Schlesisches Tor , Station2=Gourlitzer Bahnhof Station...
65,670,462
65,670,732
Elegant way to ensure a std::map has a concrete size in compilation time
I was trying to ensure that a std::map has the same size as an enum class at compile time. Avoiding the use of macros, if possible. I tried with static_assert, but reading Stack Overflow I concluded that it can't be done because std::map is "constructed" at runtime. Or at least it's what I understood. So I get this "ex...
You can store the data in a datatype that can be inspected at compile time, such as an array. static const std::map<EventTypes, std::string>::value_type kEventTypesNamesData[] = { // Note "value_type", here ^^^^^^^^^^ { EventTypes::InitSuccessfull, "InitSuccessfull" }, { EventTypes::KeyPressed...
65,670,569
65,670,654
auto return type for a C++ member function of a template class
For the sake of readability I will simplify my problem into a nice toy example: Let's say I have a template class Box which can hold a finite collection of objects of a given type (initialised as Box<double, 10>). The class has a member function called expand(n) which should modify the box such that the capacity is hi...
Parameters of template must be decided in compilation time, so you cannot use function arguments, which is decided in run time. You should add the parameter as template argument instead. template <typename T, const unsigned int size> struct Box { template<const unsigned int newsize> Box<T, newsize> expand() con...
65,670,835
65,672,986
How could use Template Class for a container of container?
I want to use my class with the template. in main: int main(void) { HexAdapter<vector> foo; // maybe? // HexAdapter<vector<Cell>> foo; return 0; } I tried something like this template <typename T> class HexAdapter { public: HexAdapter(); private: T<T<Cell>> hexCells; }; For the reason of this,...
You can achieve the HexAdapter<std::vector> syntax by relying on a template template parameter, i.e., a template parameter which is, in turn, a class template (or an alias template): struct Cell { /* ... */ }; template<template<typename...> class Cont> class HexAdapter { Cont<Cont<Cell>> hexCells; /* ... */ }; ...
65,670,851
65,670,895
How to cast one struct to another type with identical members?
If I'm given a struct variable like: struct Quaternion { float x; float y; float z; float w; } But I need to call a function expecting a struct Vector { float x; float y; float z; float w; } Is there a way in C++ to cast a variable of type Quaternion to type Vec...
You can write a converting constructor: struct Quaternion { float x; float y; float z; float w; explicit Quaternion(const Vector& vec) : x(vec.x),y(vec.y),z(vec.z),w(vec.w) {} } And similar for the other way. In case you are looking for a way that does not require to copy the member...
65,670,896
65,671,056
C++ Jump to case label error while doing windows.h
I was programming C++ and came across an error that said "Jump to case label" that i could not fix.I searched the internet and found no solution that worked. How do i fix this error? #include<iostream> #include<windows.h> using namespace std; LRESULT CALLBACK WindowProcessMessages(HWND hwnd, UINT msg, WPARAM param, LPA...
Here, you are creating variables that exist in the same scope as other cases, but whose initialization is skipped by those cases. That's what the error is telling you. case ID_BUTTON2: int len = GetWindowTextLength(hwndTextbox) + 1; static char title[500]; GetWindowText(hwndTextbox, title, len); SetWind...
65,671,078
65,671,149
Does C++ include all headers a included header file includes?
In this example code, I have 3 files: testHeader.h: void hello() { } file1.h: #include "testHeader.h" #include <iostream> void sayHi() { std::cout << "hi" << std::endl; } file2.h: #include "file1.h" void sayHello() { std::cout << "hello" << std::endl; } If file1.h includes testHeader.h and file2.h includes file1.h...
Unless protected by preprocessor guards in weird ways, yes, you get them all. #include is largely a preprocessor trick, roughly equivalent to dumping the text of the include into the source code, and it's transitive; if you #include <a.h>, you get the expanded form of a.h, including the preprocessor expanded form of al...
65,671,155
65,671,827
Calculate the grades of Subject In c++
#include <iostream> using namespace std; int main() { int PF, ICT, ENG; float avergemarks; cout << "enter the PF marks:"; cin >> PF; cout << "enter the ICT marks:"; cin >> ICT; cout << "enter the ENG marks:"; cin >> ENG; avergemarks = (PF + ICT + ENG) / 3; cout << "the avergem...
You've combined the conditions when checking the boundaries so that the boundary checks will always be false. avergemarks >= 80 && avergemarks <= 75 - No avergemarks can be greater than or equal to 80 and 75 or less at the same time. This type of filter can be simplified by just checking one condition. If the previous ...
65,671,173
65,671,365
Non-overloaded function yields unresolved overloaded error when used as default argument for concept
Background As per [temp.arg.template]/1, A template-argument for a template template-parameter shall be the name of a class template or an alias template, expressed as id-expression. which means that it is not possible to pass a function template as a default template template argument. As expected, the following cod...
Is this derived from the error in Background but showing a different message? No, it's totally unrelated. The background error is trying to pass in a type as a default argument for a parameter expecting a template: it's just the wrong kind of argument. If not, how come it shows an error related to an overloaded f...
65,671,590
65,671,638
Runtime Error in my recursive program while printing 1 to n numbers
#include <iostream> using namespace std; #define N 100 int print(int n) { if (n <= 0) return 0; print(n-1); cout<< n << " "; } // main function int main() { print(N); return 0; } //runtime error in this code while trying to run it please help and explain error is coming.
Your print function can invoke undefined behavior because it may reach the end of function body without executing return statement. The return type should be void if you won't use return value. #include <iostream> using namespace std; #define N 100 void print(int n) // change to void { if (n <= 0) return;...
65,672,169
65,672,738
cvtColor ignores dstCn argument OpenCV
I am trying to create a program which imports an RGB image and converts it to grayscale. I would like the output image to consist of 3 channels. To achieve that I use cv::cvtColor function with dstCn parameter set to 3: cv::Mat mat = cv::imread("lena.bmp"); std::cout << CV_MAT_CN(mat.type()) << "\n"; // prints "3", OK ...
The answer can be found in the OpenCV source code. Let's have a look at cvtColor function in imageproc/src/color.cpp file. There is a very long switch-case, so I only post here the most interesting part: void cvtColor( InputArray _src, OutputArray _dst, int code, int dcn ) { ... switch( code ) { ... ...
65,672,243
65,672,732
Clang++ Fails To Detect Use of Uninitialized Member Variable
Using clang++ version 11 and C++ 17 with the compiler flag -Wall, clang will normally complain if you use a variable before it is initialized. However, it does not detect the following case: struct Bar { bool b1; }; class Foo { public: Foo() : b2(Bar{b2}.b1) // We are using b2 here before it is initialized, bu...
It is not possible to detect if you used a member variable before it is initialized in the general case. Doing so for general programs violates Rice's theorem. Compilers do not try. Instead, they have some simple and cheap heuristics that catch common cases. You cannot rely on your compiler to detect every case where ...
65,672,471
65,672,559
Using erase for removing an element in an array of class objects
I want to remove a particular student object for a given roll no. from a students list using erase operation in STL. Following are my class designs. But the compiler shows the following error message at place where I used the erase function. no instance of overloaded function "std::vector<_Tp, _Alloc>::erase [with _Tp...
std::vector::erase() takes an iterator as input, not a Student object, eg: void remove_student() { int roll; cout << "Enter roll no. of the student to be removed : "; cin >> roll; for(int i = 0; i < Student_array.size(); ++i) { if (roll == Student_array[i].ret_roll()) { S...
65,672,706
65,672,766
Overriding member variables in C++
Consider the below code : #include <iostream> using namespace std; class A { public : int i; int j; void print() { cout << i << "\t" << j << endl; } }; class B : public A { public: int f; int g; int i; void print() { A::print(); cout << f << "\t" << g<<endl...
You printed i via A's (the parent class's) print function. Your class has two is, and A's print only knows where to find one of them (the one from A). If you want to print B's i, it has to be done in a B method (that knows where to find it). You could make a virtual accessor method on A that provides access to i, and h...
65,672,894
66,063,767
In what situation do we get nan in c++?
I read some article about nan, but sites didn't mentioned all situations. For example I compiled this code and received nan. Why doesn't it give inf ? #include <iostream> using namespace std; int main() { double input,counter,pow= 1, sum = 0, sign = 1.0; cin >> input; for (counter = 1; pow / cou...
With input of “2”, your program adds two infinities of opposite signs, which generates a NaN. This occurs because repeatedly multiplying pow by two causes it to become infinity, and the alternating sign results in a positive infinity being added to a negative infinity in sum from the previous iteration or vice-versa. H...
65,673,243
65,675,285
Include a *.cpp file
Currently, I try to bazelize a library. Let's call this library lib_foo. The setup is similar to this minimal example. My main application tries to use a function form lib_foo. main.cpp: #include "lib_foo/header.h" #include <iostream> int main() { std::cout << foo<2>() << std::endl; } lib_foo/header.h: #pragma o...
The normal workaround is to put includable cpp files in the textual_hdrs attribute of cc_library.
65,673,268
65,673,457
Could someone explain how pointers an references work with pthreads?
I'm trying to do a simple program that prints values using threads to test POSIX pthreads because I haven't used them before. The thing is that I know in a general way what's happening and how treads work, but I'm completely clueless about them working with pointers and references. This is my program: #include <cstdio>...
Your immediate issue lies in these lines: pthread_join(t2, reinterpret_cast<void**>(n)); pthread_join(t1, reinterpret_cast<void**>(n)); The pthreads library will dereference the pointer you pass to pthread_join and modify the pointed-to pointer to point to the thread function's return value. n doesn't point to a poin...
65,673,565
65,673,792
Can I apply downcast to an iterator?
I need to know if I am sending a template class the right type of containers by applying downcast. // C++ program to demonstrate input iterator #include <iostream> #include <vector> #include <iterator> using namespace std; int main() { vector<int> v1 = { 1, 2, 3, 4, 5 }; // Declaring an iterator vector<int...
Looks like you have completely misunderstood iterators in standard library. First and foremost, if you ever find yourself doing dynamic_cast with any standard library type (a notable exception - he-he, pun - is std::exception, and perhaps a couple of other types I am not thinking of right now) you are doing something w...
65,673,659
65,717,829
Excel C API xlfGetCell with Range
I'm writing an Excel add-in using c++ and Excel C API, "Excel XLL SDK 2010", and I need to retrieve a range of cells, inside of a command function. Using the xlfGetCell command I can only get the top-left value of the range in an xltypeStr XLOPER. Is there a way to get an xltypeMulti XLOPER that would contain the whole...
Use xlCoerce: XLOPER12 xRef, xAddress, xResult; xAddress.val.str = L"\5A1:C4"; xAddress.xltype = xltypeStr; Excel12f(xlfIndirect, &xRef, 1, &xAddress); Excel12f(xlCoerce, &xResult, 1, &xRef); Then xRef will contain an xlRef which points to the range A1:C4 on the currently active sheet and xResult will contain the xlty...
65,673,813
65,675,424
Cassandra session data corruption from multithreaded read
I am having an issue with the cassandra api and select queries. In a single threaded context it works just fine. However, when multiple threads use the same object and call the function, even with just two threads, cassandra is returning it's futures with bad data(sometimes appears to be overwritten with data from othe...
It looks like you're freeing the results before a copy is made from the value pointers into the byteBuf. In single-threaded version, you may be getting lucky that the dereferenced memory is still intact. Multithreaded, you're likely to overwrite.
65,673,904
65,984,141
UE4, setting relative angular velocity of object
Context I have been attempting to set the angular velocity of a frisbee in UE4. This is easy. However, UE4 adds an angular velocity through the center of mass of an object relative to the 'world-axis' and not relative to the axis of the frisbee. Below the 'World' axis is red, and the relative axis is green, and the fri...
You need to transform the axis from local space to world space. Something along these lines:
65,674,090
65,674,276
How can i create push_back function of dynamic array?
Im trying to create this and add push back functionality. How can i do it? I came up with this code but im very confused for 2 days because it gives this output - | -842150451 | -842150451 | -842150451 | -842150451 | -842150451 | -842150451 | -842150451 | -842150451 I will be thankful if someone can tell me how this fu...
First, create() should be changed into an actual constructor. And you are missing a destructor to free the array, as well as copy/move constructors and copy/move assignment operators to manage the array (per the Rule of 3/5/0). Second, you should be using new[] instead of malloc(). Third, regarding your push_back(), i...
65,674,282
65,694,515
can't compile struct with std::atomic member with explicit instantiation
I am exploring the use of std::atomic in a struct across translation units and have run into a constructor compile problem. When I try to use explicit instantiation, the compiler says they don't match. How do I match up the explicit instantiation and the A constructor? #include <string> #include <atomic> #include <map>...
The immediate problem is that struct A is non-copyable and non-movable: its auto-generated copy and move ctors are deleted because std::atomic is non-copyable and non-movable. A map with a non-movable value type can be created, but many operations on it are disabled, including the construction from the initializer list...
65,674,373
65,674,544
Is using an uninitialized unsigned type object Undefined Behavior?
I know that using (accessing the value) an uninitialized non-static and non-global object of type built-in integral type is Undefined behavior. int x; // x is defined inside a function scope for example main ++x;// UB signed char c = 127; // max positive value for char on my machine c++; // UB overflowing a signed ch...
Is using an uninitialized unsigned type object Undefined Behavior? Yes. but I think it doesn't cause any harm. You might be right. But since it's UB you might also be wrong. You can never be sure. One sneaky thing compilers do is detect your Undefined Behavior and "optimize" your program by outright removing code...
65,674,434
65,674,492
Error using SHFileOperation() to copy a folder
I am trying to use SHFileOperation() to copy a folder, but get this error: a value of type "const char *" cannot be assigned to an entity of type "PCZZWSTR" for both s.pTo and s.pFrom. The code I'm using is: SHFILEOPSTRUCT s = { 0 }; s.hwnd = hWnd; s.wFunc = FO_COPY; s.fFlags = FOF_SILENT; s.pTo = "C:\\Users\\styler\...
The compiler is telling you that you are trying to assign char string literals to wchar_t string pointers (PCZZWSTR = CONST WCHAR *). That means you must be compiling with UNICODE defined, where SHFileOperation() maps to SHFileOperationW() which expects wchar_t* string pointers instead of char* string pointers. So, yo...
65,674,671
65,674,985
Get ordinal number of C++ variadic template parameter
I want to retrieve index of each parameter from variadic template parameters, currently I am using this approach: From third party library: struct statement { template <typename T> void bind(int, T t) { // .... } }; My code: template <unsigned Index, typename T> void bind(statement& stmt, T t) { stmt.bind(In...
With simple expansion (could use a fold expression in C++17) struct statement { template<class T> void bind(int index, T&& arg) { // magic } }; template<class... Args> void BindAll(statement& stmt, Args&&... args) { using swallow = int[]; int idx = 0; (void)swallow{0, (void (stmt.bin...
65,675,066
65,675,164
C++ Merge Sort using iterators
Currently, I am trying to create a simple C++ Merge Sort Program. using namespace std; using Iterator = std::vector<int>::iterator; using CIterator = std::vector<int>::const_iterator; std::vector<int> merge(CIterator left_begin, CIterator left_end, CIterator right_begin, CIterator right_end) { std::vector<int> res...
The problem is that the type signature for merge_sort assumes an in-place algorithm: void merge_sort(Iterator begin, Iterator end); But your merge procedure isn't in-place but returns a merged copy of the arrays. You either need to change merge to be in-place, or you need to change merge_sort to return the sorted arra...
65,675,102
65,675,899
How do I create a constructor for a custom array class that can take in any amount of arguments up until the size of the array?
I'm 16 years old and decided to start learning c++ a week ago. I would consider myself knowledgeable in other programming languages such as Python, C#, and Javascript. I've noticed that c++ has a lot of features that allows you to create intricate classes and programs. So I decided that I wanted to try to create a cust...
What you are attempting to do can be done with a variadic template, but that is not what you really need. Use std::initializer_list instead, eg: #include <initializer_list> #include <algorithm> Array(std::initializer_list<T> args) { std::copy_n(args.begin(), std::min(args.size(), S), std::begin(m_Data)); if (...
65,675,393
65,685,920
Is calling a "noexcept function" through a "function" lvalue undefined?
[expr.call]/6: Calling a function through an expression whose function type is different from the function type of the called function's definition results in undefined behavior. void f() noexcept {}; // function type is "noexcept function" void (*pf)() = f; // variable type is "pointer to function"; initialized by r...
C++14 had a weaker requirement, from [expr.call]/6: [...] Calling a function through an expression whose function type has a language linkage that is different from the language linkage of the function type of the called function's definition is undefined ([dcl.link]). [...] However [expr.reinterpret.cast]/6 containe...
65,675,412
65,694,450
bazel build cannot find shared library
I have this simple directory structure: . ├── main │   ├── BUILD │   └── future.cpp └── WORKSPACE where the BUILD file is as follow: package(default_visibility = ["//visibility:public"]) cc_binary( name = "future", srcs = [ "future.cpp" ], copts = [ "-std=c++1z" ], linkopts = [...
Bazel likes to use the gold linker instead of GNU ld by default. gold, unlike GNU ld, doesn't put /usr/local/lib on the default library search path. This can be remediated by passing --linkopt=-L/usr/local/lib to Bazel.
65,675,702
65,689,566
pcap_dispatch stuck with network filter set
When I run my program with the loopback device "lo" and some filter is applied, it hangs in a poll call (see gdb below). It doesn't happen if the pcap_compile() and pcap_setfilter() calls are skipped and this doesn't occur with other network devices either. pcap_dispatch is called in a loop. The program calls these lib...
This seems to be an issue in versions before 1.10.0. As of 1.10.0, issuing pcap_breakloop() will force the poll() call to end and cause pcap_dispatch to return with PCAP_ERROR_BREAK. If using an older version, a quick solution is to call pcap_setnonblock() after pcap_activate() and then sleep between pcap_dispatch() ca...
65,675,997
65,676,038
Removing Struct object from list using remove method in C++
I am trying to use remove method from list on struct object to remove it. This is my struct: typedef struct pair{ int x; int y; } PAIR; And this is code where i use it and where the error occurs: list<PAIR> openSet; PAIR pair; pair.x = xStart; pair.y = yStart; openSet.push_front(pair); PAIR current; for(PAIR p : ...
To use std::list::remove(), elements have to be comparable for equality. Implement an operator== for your struct, eg: typedef struct pair{ int x; int y; bool operator==(const pair &rhs) const { return x == rhs.x && y == rhs.y; } } PAIR; Otherwise, use std::find_if() and std::list::erase(): auto iter = st...
65,676,338
65,676,426
Writing a C++20 range to standard output
I can take several ints from a vector putting them to standard output with an iterator: std::vector<int> v{0,1,2,3,4,5}; std::copy_n(v.begin(), 3, std::ostream_iterator<int>(std::cout, ":")); I can use the new C++20 ranges to take several ints from a vector putting them to standard output with | operator in a ...
The specific thing you're looking for is using the new ranges algorithms: std::ranges::copy(v | std::views::take(4), std::ostream_iterator<int>(std::cout, " ")); You don't need to use views::all directly, the above is sufficient. You can also use fmtlib, either directly: // with <fmt/ranges.h> // this prints {...
65,676,648
65,677,103
Is there a faster way of implementing this 'ranking' algorithm?
Lets Suppose I have an array of arrays, where each sub array represents a ranking i.e std::array<std::array<std::string, 4>, 3> rankings = { { "A", "C", "B", "D" }, { "C", "D", "B", "A" }, { "B", "A", "D", "C" } }; where in this case we have three 'rankings', with the first ranking being: A 1st, C 2nd, B 3rd, ...
First of all we can make your code significantly shorter: auto weights = std::vector<int> { 8, 6, 4 }; std::map<std::string, size_t> results; for( const auto& ranking : rankings) for(auto i = 0U; i < ranking.size(); ++i) results[ ranking[i] ] += i < weights.size() ? weights[i] : 0; Now we not only made i...
65,676,785
65,677,147
How can i create generic dynamic array?
Hello i have this IntArray i want to convert to accept generic types: class IntArray { private: int* first_cell = nullptr; int size = 0; // currently occupied elements int capacity = 8; // size of the allocated memory public: IntArray() { first_cell = new int[capacity]; // Declare the array in...
I figured it out; template<class T> class List { private: T* first_cell = nullptr; int size = 0; // currently occupied elements int capacity = 8; // size of the allocated memory public: List() { first_cell = new T[capacity]; // Declare the array in memory } List(const List& src) ...
65,677,264
65,678,052
Wrapping a C++ class method in a try catch block with added functionality
Coming from mostly interpreted and dynamically typed languages, I'm a little stuck on how to approach this problem in C++. I have a class Child which inherits from Parent and adds some functionality. I would like class Parent to implement a function (perhaps trycatch) that would wrap a function from class Child in a tr...
I have no comments on your design. Here is how to make it work. void trycatch(std::function<void()> f){ // setup try{ f(); } catch( blah ) { // cleanup } // finish } at call site: trycatch([&]{ someMethod(); }); and done.
65,677,292
65,755,942
How to accurately display and store and use data exactly up to certain number of decimal places in C++?
If I have a double variable, I want to store its value in a file to two decimal places with the standard rules of rounding off. I don't just want to store and display data up to two decimal places but I also want to do arithmetic using this data, when I reopen the file, exactly up to two decimal places. In other words ...
What you have described is a fixed point representation. Trying to use a floating point representation for fixed point values often leads to issues, as you have discovered and as described in Is floating point math broken? See Fixed point vs Floating point number for a more detailed comparison of the representations. A...
65,677,429
65,678,760
How can I `nlohmann::json::get<std::shared_ptr<const T>>`?
I've defined the following serializer stack: namespace discordpp { using Snowflake = uint64_t; } namespace nlohmann { template <> struct adl_serializer<discordpp::Snowflake> { static void to_json(json &j, const discordpp::Snowflake sf) { j = std::to_string(sf); } static void from_json(const jso...
The std::shared_ptr<const T> synthesizer is not needed. In the from_json methods of both std::shared_ptr sythesizers the json parameter wasn't static.
65,677,469
65,677,514
std::function::target with template parameter pack gives "error: expected primary-expression"
When I attempt to call the method target on a std::function object using a template parameter pack, the compiler throws an error, but it works fine if the template parameters are specified explicitly in a proxy variable. Example, modified from cppreference.com: #include <functional> #include <iostream> int f(int, int)...
arg.template target<int(*)(Args...)>( You need to disambiguate when the std function type is dependent on template args. C++ doesn't know arg.target is a template when parsing your template function prior to the function being called. And it has to parse it before it is called; this isn't a macro. So whenever you nam...
65,677,478
65,694,770
how to link libraries in vcpkg to my library using cmake?
I am trying to use cmake and vcpkg to write a project in vs2019 recently. I want to link the dynamic library in vcpkg to my own dynamic library, but I have encountered some troubles. I hope someone can help me correct the mistake. My project structure: project -engine -Engine.h -Engine.cpp -Window.h -Window.cpp -I...
target_link_libraries(engine PRIVATE GLEW::GLEW) target_link_libraries(engine PRIVATE glfw) are wrong! it should be: target_link_libraries(engine PUBLIC GLEW::GLEW) target_link_libraries(engine PUBLIC glfw)
65,677,593
65,677,701
Why are these pointers the same, while referring to different instances of an object?
I am debugging a copy constructor I created for a binary search tree, I'm doing this by monitoring the memory addresses of the nodes in the original tree as well as in the newly created copy. A node consists of a pointer to a Comparable item (which contains only a single char), a count of occurrences of that char, and ...
&root is the address of the variable root. The variable root is a pointer, but that pointer exists on the stack. So a pointer is like a piece of paper with a street address on it. root is a piece of paper with the address of *root on it. &root is where that piece of paper is. The stack is like a special road where y...
65,678,086
65,678,148
While traversing the link list to read data my function prints up to penultimate node only, Suggest a way to print the whole list
I made a linked list in C++. For in which I have a function named: ListTraverse(). Which accepts a Node type pointer variable, where Node is my class. Please suggest me a method where it prints up to the last node. Here is function call: ListTraverse(&head); And here is the function definition: void ListTraverse(Node*...
You should re-phrase your question. It seems that my function prints up to penultimate node only is the problem. you wanted to print the whole list, not penultimate. And the fix is void ListTraverse(Node* node) { //Prints upto the last node while (node) { cout << "\nNode details:\t" << node->read_dat...
65,678,248
65,681,111
Getting display name of a DirectShow filter without a category
I want to get the display name of VMR-7 filter (CLSID_VideoMixingRenderer, {B87BEB7B-8D29-423f-AE4D-6582C10175AC}). Normally, I would use CoCreateInstance (CLSID_SystemDeviceEnum) + CreateClassEnumerator (CLSID_ActiveMovieCategories), then use moniker enumeration to find a moniker for the filter and use the moniker's G...
DirectShow filter is a COM object without requirement or assumption to implement any self-descriptive interfaces. There is no DisplayName attached, promised or documented, so you don't have a method to retrieve it. DisplayName is a string associated with registration information, and if a filter is not registered as in...
65,678,848
65,680,390
why two different compilers are giving two different results?
Problem is to find the last digit of the number (1358)^n. I've used the same method in c++ with two different compilers but the results are different in both the compilers on codeforces. Compilers: clang c++17 Diagnostics(code accepted) but with GNU G++17 verdict is wrong_answer. I'm not getting where the problem is, a...
I can't reproduce your problem but it is likely due to floating point rounding errors (see Is floating point math broken?). There is no need to use floating point to solve this problem. You seem to have realised that the last digit follows the repeating pattern of 8, 4, 2, 6. To find which element of this pattern you a...
65,678,942
65,679,142
How to print symbol "↑" using AfxMessageBox?
How can I print this symbol "↑" using AfxMessageBox()? I try to code it like this: AfxMessageBox("↑"); After compiling, I got a strange symbol: Does AfxMessageBox() not support this symbol?
Your source file is likely saved as UTF-8. To work with MBCS string literals, your source file needs to be saved in the same charset that your OS user locale is set to. Unfortunately, not many charsets support this particular character, I think. Otherwise, you have to switch to Unicode. If you can’t switch the whole a...
65,679,280
65,679,712
Cannot write keystroke to Notepad in C++
(C++ 17) I am writing a keylogger that writes the keystrokes onto a notepad but I am having trouble writing to the notepad. I created a function that gets called in a while true loop with a 175ms delay. std::ofstream keyLogs; keyLogs.open("C:\\Users\\smart\\Desktop\\Text Files\\Key Log.txt"); char toChar; if (capital)...
If you only look at the error in the code, because the file stream of keyLogs in the loop has been closed when the function is executed for the first time. So your key information will not be written into the file later, you can define keyLogs as a global variable. This is the modified code, you can refer to: #include ...
65,680,367
65,680,874
Using pointer as a template parameter
In C++ I can do something like this: template <typename T, T* Ptr> class MyClass {}; I have two questions: Where can I get a pointer other than nullptr in compile time? How can I use this language feature? Of course, it would be interesting for practical cases, but it seems that this is a rather specific possibility...
You can get a pointer to anything with static storage duration and linkage at compile time: static const int values[] = {4, 8, 15, 16, 23, 42}; MyClass <const int, values> myClass; static char magic = '*'; MyClass <char, &magic> myClass2; Demo
65,680,489
65,681,978
Why is vectorization not beneficial in this for loop?
I am trying to vectorize this for loop. After using the Rpass flag, I am getting the following remark for it: int someOuterVariable = 0; for (unsigned int i = 7; i != -1; i--) { array[someOuterVariable + i] -= 0.3 * anotherArray[i]; } Remark: The cost-model indicates that vectorization is not beneficial the cost-mo...
It's hard to answer without more details about your types. But in general, starting a loop incurs some costs and vectorising also implies some costs (such as moving data to/from SIMD registers, ensuring proper alignment of data) I'm guessing here that the compiler tells you that the vectorisation cost here is bigger th...
65,680,490
65,681,509
VS 2019 (Visual studio) Linux makefile project - 'No such file or directory' when compiling from windows
I have a makefile projects on Linux (CentOS). The projects are compiled fine when compile from the Linux terminal. I added those projects to visual studio 2019. The connection is fine (files are copied to linux). I defined the remote working folder and project folder, and type of project (Makefile- static library). But...
Thanks for another different case which suggested to look at the command sent to the linux. I saw that the problem was actually that I missed replacing some of the '' with '/' in some of the paths. (This is difference between windows and Linux). i.e: in windows path: C: \Folder1\Folder2\Folder3 ------> /home/user/F...
65,681,159
65,681,423
Error when trying to link to a shared library I created using LD_PRELOAD
I'm trying to test if I can override the glibc's malloc interface by linking a shared library on Linux. I don't have the details for the malloc functions yet. So I created a nullmalloc.cpp that has the required replacements for malloc, but all returns null. The code looks like this: # include <cstddef> void* malloc(si...
I do not know how to add compiler flag, but you can make it works as follows. Compile test as usual: g++ -Wall -g test.cpp -o test -std=c++11 Invoke it like this: LD_PRELOAD=/home/nullmalloc/nullmalloc.so ./test
65,681,582
65,681,703
Exception doesn't continue loop correctly
I'm currently learning about exceptions, so this might seem trivial but I'm learning. So, a user is asked if he wants to enter an integer or a string, if he selects an integer and types a string anyway, I want an error to occur. Here is part of the code I'm working on: #include <iostream> using namespace std; templat...
Bad input sets the failbit but doesn't throw exception by default. you might use basic_ios::exceptions to have exception: std::cin.exceptions(std::ifstream::failbit); int numItems; try { std::cout << "How many items to store?" << std::endl; std::cin >> numItems; if(numItems<0) throw "Invalid Number...