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,786,374
70,786,414
the result in c flipped to negative number
unsigned int x; unsigned int y; x = 0x66; y = 0x39; unsigned z; z = ~x | ~y; printf("%d\n",z); my code is like this, and I would like to compute ~x | ~y, I define z as unsigned, but the z is still the negative number. why? and is this the problem in ~x, so what is the ~x operation in computer. thank you
You are telling printf to print a signed input, so it will interpret its input accordingly. Try printf("%u\n", z);.
70,786,406
70,786,525
A C++ Program which works fine in online compilers and linux operating systems, but not on Windows
While compiling a problem: Geeks For Geeks: First Repeating Element on a Windows operating system I noticed that I was not getting any output for my solution. But when I compiled the same code on a Linux operating system and on online compilers, it worked absolutely fine without producing any errors. Code: #include <bi...
#include <bits/stdc++.h> is not standard C++, hence you should not expect it to be portable. int arr[n]; is not standard C++. Some compilers offer variable length arrays as extension, but it isnt portable. Same goes for int A[size];. Sadly most of the C++ code presented on that site is not proper C++ code but some dial...
70,787,229
70,787,312
Accessing pointers inside class
i am trying to use a pointer variable in a class but instead it gave me an error Car.cpp:15:16: error: right hand operand to ->* has non-pointer-to-member type 'int *' return this->*tires; here is my program main.cpp #include <iostream> #include "Car.h" using namespace std; int main(){ int x = 5; Car honda("h...
The entire variable is called this->tires, the this referring to the current object and the tires referring to the member itself. As such, you need to dereference the variable and not 'a part of it`. Either use: int Car::getTires(){ return *tires; } which works, because the this is implied automatically by the com...
70,787,335
70,790,145
Optimize member function selection at runtime on CPU/GPU
I have the following piece of code that needs to optimized (and be later ported to the GPU through SYCL or ArrayFire): struct Item { float value; int f; float Func(float); float Func1(float); float Func2(float); float Func3(float); }; float Item::Func(float v) { value = v; switch(f) { ...
There is a blog post about how to implement an alternative to function pointers using SYCL on this website. The solution uses the template feature and function objects instead. I believe the history of this is that most hardware doesn't support jumping to computed addresses.
70,787,594
70,788,140
Assertion failed in imread() function
I'm trying to do a simple template matching with openCV-python, but right in the beginning getting an error. I've run the following code: import cv2 as cv import numpy as np haystackImg = cv.imread('fullImage.png', cv.IMREAD_UNCHANGED) needleImg = cv.imread('diamond.png', cv.IMREAD_UNCHANGED) result = cv.matchTempla...
The problem was, that my source path contained non ASCII characters such as á and é... Created a new location without any non ASCII characters and white-spaces, and it works fine now.
70,787,871
70,788,350
The best way to implement cloneable c++ classes?
I have seen solutions (including in this site) to the problem of having to implement a clone method in a class, so it returns a heap-allocated clone of itself even if we only have the Baseclass. The problem come up when you have to implement in a lot of classes the same method again and again, and I remember a way of d...
You could use the Curious Recurring Template Pattern where a derived class actually derives from an instanciation of it base class depending on itself. Demo: #include <iostream> template<typename T> class Clonable { public: T* clone() { return new T { * static_cast<T *>(this)}; } }; template<class T> ...
70,788,168
70,788,451
How to make an object take and store an Array of arbitrary, but compile-time known size?
Background For an embedded project, I want a class that takes a list of structs. This list is known at compile-time, so I shouldn't have to resort to dynamic memory allocation for this. However, how do I make a struct/class that encapsulates this array without having to use its size as a template parameter? Templates M...
Is there a way to 'hide' the size of the array in Profile or Runner? Yes. The solution is indirection. Instead of storing the object directly, you can point to it. You don't need to know the size of what you're pointing at. A convenient solution is to point into dynamic storage (for example std::vector) because it al...
70,788,173
71,668,088
Eigen static lib memory align
I am using C++17, GCC 7.4.0, Eigen 3.3.4 This is my minimal example. I have 2 classes: B and C. C is in a static library. The program crashes with Segmentation Fault when trying to create an instance of B. Static library is built with optimizations (Build Type: Release). If built without optimizations, the program does...
Judging from your comments at your other post, you might be using different architecture options while compiling the library and the executable (-m... flags for gcc)? At least, I could reproduce the crash using Eigen 3.3.4 when I compiled the static library in gcc-7.5.0 with the flags -O0 -DNDEBUG -g -std=c++17 -mavx, ...
70,788,208
70,788,825
Ending a loop on time expiration
I have a long computation in a loop, which I need to end prematurely if allowed compute time expires (and return a partially computed result). I plan to do it via SIGALARM handler and a timer: // Alarm handler will set it to true. bool expired = false; int compute () { int result; // Computation loop: for...
If you aren't using multiple threads, you don't need an atomic operation. Just set the global variable expired = true in the signal handler. EDIT: as @Frank demonstrated below, the compiler might optimize it out. You can avoid this by declaring expired as volatile bool expired = false;
70,788,244
70,788,927
Do I need to/How to free wstring, wstringstream, vector
Here is my working code. Do I need to clear or free wstring, wstringstream, vector in the func()? If so, how? I see there is a .clear() function for the vector and wstring and wstream. This sample program is to show the code. I use the wstringstream, wstring, and vector where I have a delimited-string and I need to ext...
Most containers in C++ have two quantities. A size (how much it holds) and capacity (how much it already has allocated). vector::resize for example, changes the size, but will not alter the capacity unless required. vector::reserve changes the capacity, but the size. By convention, all C++ objects free resources, inclu...
70,788,871
70,789,245
boost::pfr with customized member
I'm trying to use boost::pfr for basic reflection, and it fails to compile when one of the member is customized type, like a class or struct, why is this? What's the way to fix it? I'm using C++17. // this works: struct S1 { int n; std::string name; }; S1 o1{1, "foobar"}; std::cout << boost::pfr::io(o1) << '\n'...
You need to provide operator<< for S1, as boost::pfr::io relies on it existing: std::ostream& operator<<(std::ostream& os, const S1& x) { return os << boost::pfr::io_fields(x); } live example on godbolt.org
70,789,279
70,789,414
create vector of array of string and void function pointer in c++
how to create an array or vetor like this in python: this program in python: a = [["foo",foofunc]["bar",barfunk]] an array (or any thing) with another multi type array in,
I think you're looking for a vector of pair<std::string, void (*)() as shown below: #include <iostream> #include <utility> #include <string> #include <vector> void foofunc() { std::cout<<"foofunc called"<<std::endl; //do something here } void barfunc() { std::cout<<"barfunc called"<<std::endl; //do so...
70,789,891
70,832,078
C++ bit field member variable initialization value (UE4 example)
I'm wondering what value a bit-field class member variable will have if it is not explicitly initialized. Using an example from unreal engine 4.27: //member variable of UPrimitiveComponent //there are other uint8 bitfields declared above and below this UPROPERTY(...some UE4 macro stuff...) uint8 bCastHiddenShadow:1; I...
Dug a little bit deeper, so I'll try to answer this myself. I believe that for a normal C++ class it would be undefined behaviour as I cannot find any info suggesting otherwise for bit-fields specifically. For the UE4 example, most objects in the engine including the cited UPrimitiveComponent example are derived from U...
70,790,295
70,791,947
Is there a way in gmock to return modified input arg without invoke?
I want to do something like this: EXPECT_CALL(*mock, method(5)).WillOnce(Return(arg1 * 2)); where arg1 should be equal to first arg of called method. Is there a way to do that without testing::Invoke?
Method 1: You can use a custom matcher, as the other answer mentioned, however, notice that the preferred way of using custom matchers is by using functors, not the ACTION macro (See here). Here is an example: // Define a functor first: struct Double { template <typename T> T operator()(T arg) { return 2 * (arg...
70,790,551
70,790,939
Clip Space in OpenGL and DirectX 12
I am implementing a custom mathematics library to create model, view and projection matrices in OpenGL and DirectX. I am doing this, to improve my understanding in the mathematics behind 3D applications. At first I took a look at right-handed and left-handed coordinate systems. I realized, that if I create my view matr...
However, in OpenGL the scene renders correctly no matter if I use a projection matrix for clipping between -1.0 and 1.0 or 0.0 and 1.0. In DirectX only the projection matrix for clipping between 0.0 and 1.0 works OpenGL renders because [0.0, 1.0] falls within the range [-1.0, 1.0], but DirectX does not because [-1.0,...
70,790,637
70,805,372
MFGetService doesnt get IMFSimpleAudioVolume on first try
I am playing a mp3 file with windows media foundation and try to set the volume but when i try to get IMFSimpleAudioVolume interface it takes a seemingly random amount of tries to do so. I have got 1 through 200ish tries. I tried using IMFAudioStreamVolume but the results are the same Here is the main.cpp #include <ios...
IMFMediaSession::SetTopology is asynchronous, so you'd want to sync before asking for service. This method is asynchronous. If the method returns S_OK, the Media Session sends an MESessionTopologySet event when the operation completes. mediaSession->SetTopology(NULL, topology.get()); // INSERT BEGIN // ...
70,791,122
70,791,157
How do C++ compilers handle malloc failures during new operator?
C++ compilers implement new Obj as a wrapper to malloc(sizeof(Obj)). But malloc can fail! What code do C++ compilers insert to handle the failures, and what does it do?
C++ standard says about the behaviour: [basic.stc.dynamic.allocation] An allocation function that has a non-throwing exception specification ([except.spec]) indicates failure by returning a null pointer value. Any other allocation function never returns a null pointer value and indicates failure only by throwing an ex...
70,791,164
70,791,390
Why was it nessesury to allow std::move accept reference to lvalue besides reference to rvalue in Uref embodiment for both?
Considering that rvalue-ness and lvalue-ness are not a features of objects but of expressions. Why isn't std::move implemented only for lvalue reference argument, but for universal one? Whereas it is useful only for retrieving rvalue reference from an lvalue? When rvalue is rvalue already and it does not need std::move...
Why isn't std::move implemented only for lvalue reference argument, but for universal one? Because lvalue references to non-const cannot be bound to xvalues. When rvalue is rvalue already and it does not need std::move functionality. We want std::move(some_expression) to work whether some_expression is an rvalue ex...
70,791,675
70,792,331
Append bin folder to PATH environement variable after installation
I have done a C++ program for Windows and an NSIS installer using CPack. I want that after the installation, the user can call my program from the terminal without giving the whole path of the exe. Sometimes some installers even add an Add useful environment variables checkbox at the end of the installation to give the...
As always, check the documentation... https://cmake.org/cmake/help/latest/cpack_gen/nsis.html CPACK_NSIS_MODIFY_PATH    Modify PATH toggle. If this is set to ON, then an extra page will appear in the installer that will allow the user to choose whether the program directory should be added to the system PATH variable....
70,792,064
70,792,210
What is the purpose of 'flag' in a prime number program?
I saw this code from a website and there wasn't any explanation behind or specifically the purpose of the flag line. #include <iostream> using namespace std; int main() { int n, i, m = 0, flag = 0; cout << "Input a number: "; cin >> n; m = n / 2; for(i = 2; i <= m; i++) { if(n % i == 0) ...
Since that loop can exit for 2 reasons the number is not prime (there is a break statement) once i reaches m (the for loop terminates) the code after the loop needs to know which exit happened so that it can say that the number is prime if it exited for the second reason. A more canonical way to do it is for(i = 2; ...
70,792,489
70,793,147
What is the last parameter in VirtualProtect used for?
I want to use both VirtualAlloc and VirtualProtect to inject a shellcode into the local process but I can't figure out what is the last argument (lpflOldProtect) and how do I declare it. void fun() { size_t dwSize = 511; // size of shellcode LPVOID base_add = VirtualAlloc(NULL , dwSize , MEM_RESERVE, PAGE_NOAC...
The fourth (last) argument to the VirtualProtect function should be the address of a DWORD variable in which to receive the value of the previous protection flags for the memory block (or, to be exact, the first page of that block). You can use this, should you desire, to 'reset' that protection level when you're done ...
70,792,553
70,792,888
Exe not working properly outside of visual studio?
My program runs fine in the IDE (Visual Studio 2022), in debug and release modes. When I make a build and want to start the .exe from Explorer, it starts and runs, but... well, have a look: This is how it should be: This is what it looks like outside of VS: So far, I have tried to set the Runtime Library to Multi-thr...
See https://en.wikipedia.org/wiki/ANSI_escape_code, specifically: In 2016, Microsoft released the Windows 10 version 1511 update which unexpectedly implemented support for ANSI escape sequences, over two decades after the debut of Windows NT.[13] This was done alongside Windows Subsystem for Linux, allowing Unix-like ...
70,792,678
70,792,679
Can C++ coroutines contain plain `return` statements?
I am writing a C++ coroutine for a UWP control using C++/WinRT: winrt::fire_and_forget MyControl::DoSomething() { if (/* some condition */) { // Why does this work?! return; } co_await winrt::resume_foreground(Dispatcher()); // Do some stuff co_return; } This is compiling ...
This seems to be a legacy implementation for MSVSC. MSVSC implemented coroutines before the standard was formally complete, so there are two implementations of async (/async and /async:strict). I seem to have the old, non–standard-compliant version turned on. The standard is clear that you cannot use plain return state...
70,792,911
70,792,996
Generalize integral template parameters
Is there a way to generalize an integral template parameter so that it supports e.g. int and std::size_t. Here is non-compiling example of what I have in mind. Is there a way to implement the function f without adding a copy of it that takes std::size_t as a parameter? #include <cstddef> #include <iostream> template <...
Since c++17 you can use auto for non-type template parameters. template <template<auto> typename T, auto N> ...
70,793,143
70,793,297
Return with aggregate initialization without type name
In C++ 20, for a type like this: struct Person { std::string name; int age; }; We can return it from a function using aggregate initialization, with or without writing out the type name: Person getJohn() { // With type name return Person { .name = "John", .age = 42, }; // Without type name retur...
They should always be equivalent. A return statement performs copy-initialization ([stmt.return]/2). A copy-initialization from a designated-initializer-list performs aggregate initialization ([dcl.init.list]/3.1). If the operand is simply the designated-initializer-list itself, we are done. The return object has been ...
70,793,440
70,849,917
An auto-scaled on-off background image in a QLineEdit
I have a couple of QLineEdit widgets that need to have their backgrounds appear and disappear upon certain code changes, and need those backgrounds to also rescale when widget size changes. I am getting quite lost in all the stackoverflow and documentation on the Qt website. My main point of confusion is how I register...
Solved my own problem. Ended up doing it entirely in stylesheets. I don't know what my philosophical opposition was to using image instead of background-image, aside from the worry that it would interact poorly with text that is inputted into the QLineEdit. Thankfully that is not a concern, and text receives the most Z...
70,793,544
70,793,736
Why in order to use default constructor in Derived Class, we need a default constructor in the Base Class
As you have seen in the title i need to find the error in the code bellow, Here is what i know: I know that in order to use default constructor in B, we need a default constructor in A What i don't know is: Why? I guess it's because B inherits A but i need to know exactly why exactly Here is the code: #include <ios...
I think your title is misleading, but the question is valid. In order to construct B, A needs to be constructed as well (that you know) but how can A be constructed without knowing the value of int i in its constructor? But you could use the parameter-less constructor of B to provide value for i: struct B : public A { ...
70,794,146
70,794,264
String name of template function
I know you can use the preprocessor to get the textual name of a standard function at compile time via __func__ My question is, is there any way to get the textual name of a template function including its specific implementation details (mangled is better than nothing)? For example, template <typename T> void myFuncti...
For use with g++ you can use __PRETTY_FUNCTION__. So for #include <iostream> template<typename T> void myFunction() { std::cout << __PRETTY_FUNCTION__ << '\n'; }; int main() { myFunction<int>(); myFunction<char>(); } I get void myFunction() [with T = int] void myFunction() [with T = char]
70,794,769
70,795,265
What is the official Rust guidance for interoperability with C++, in particular passing and returning structs as arguments?
I'm trying to adapt some layers of existing C++ code to be used by Rust and apparently the way is through a C API. For example, one function might return a struct as an object #pragma pack(push,4) struct Result { char ch; int32_t sum1; int32_t sum2; }; #pragma pack(pop) extern "C" Result muladd(int32_t a, ...
extern "C" on both sides + #[repr(C)] on the Rust side + only using C-compatible types for interfacing between C++ and Rust, should work. Alternatively, see cxx and autocxx.
70,795,082
70,795,121
can someone help me with the #include being nested to deeply error before i go insane? thx
//main.cpp #include <iostream> #include <array> #include <iomanip> #include "Board.h" #include "Game.h" //Player.h #include <array> #include <string.h> #include <random> #include "Property.h" #include "Game.h" #ifndef Player_h #define Player_h //Property.h #include "Space.h" //#include nested too deeply error #ifndef...
Player.h includes Game.h and Game.h includes Player.h. This is an infinite loop. There might be more, but that's just the first one I saw. You should remove at least one of those includes to break the infinite loop. If you get errors when you do that, you might be able to fix them using a forward declaration that lo...
70,795,458
70,799,685
Is there a clean way to convert runtime values to compile time values?
I'd like to create a type with non-type parameters based on run-time values, the make_fruit function: struct IFruit { // interface }; enum Species { Apple, Orange, Peach, }; enum Color { Red, Green, Blue, Yellow, }; template <Species S, Color C> struct Fruit : public IFruit { // i...
You can avoid to write the combinatory yourself thanks to std::visit of std::variant (both C++17): using SpeciesVariant = std::variant< std::integral_constant<Species, Species::Apple>, std::integral_constant<Species, Species::Orange>, std::integral_constant<Species, Species::Peach> >; using...
70,795,472
70,795,499
Issues reading floats from .txt file
I am trying to read a .txt file with some floats into my code. I wrote a sample code just to tackle the issue outside my main code and I am using the following floats to test it: 10.8f 100.8f -10.8f The issue I am running into is that the code only reads in the first float properly and displays it but all the other ...
The f suffix is valid in C++ code, but not in input text parsed by istream. It's useful in code to distinguish between float and double constants, but user input doesn't control variable data types.
70,795,510
70,796,435
Create grid of images with increasing grey scale values
I'm trying to write some C++ to create a 1048x1048x8 bit matrix of 256x256 squares. The first should have a grey scale value of 0 while the last should be 255. This is what I've tried so far. Any feedback is appreciated. First image is my result. Second is the desired. [1]: https://i.stack.imgur.com/BmGOZ.png [2]: http...
So each row of pixels (from left to right) spans 4 different colored squares (4 columns using x), and each square is 256 pixels wide: for (int x = 0; x < 4; x++) { for (int j = 0; j < 256; j++) { // write one pixel here } } Each column of pixels (from top to bottom) also spans 4 different colored squar...
70,795,807
70,796,103
STL vector implementation header size
Is there a requirement in C++ that sizeof(std::vector<T>) == sizeof(std::vector<S>) where S and T are arbitrary copy-assignable and copy-constructible types? For example, on my 64-bit Windows laptop with GCC we have sizeof(std::vector<int>) == sizeof(std::vector<std::tuple<std::vector<double>, int, std::map<...
No, there is no requirement that the size of all std::vector specializations be the same. The compiler is allowed to have different layouts and sizes for different specializations if it wants to. In practice, one example is vector<bool> which happens to give a different result in at least one instance: std::cout << siz...
70,796,490
70,796,619
Valgrind thinks my std::ranges of raw pointers are leaking, even after they've been copied to unique pointers
I'm trying to load all true-type fonts in a directory using C++20 ranges and functional-style programming. However, since fonts are a resource, I'm allocating memory within the ranges interface. I think this is why valgrind thinks I have a leak. I have a few std::views of freshly allocated raw pointers that eventually ...
views::transform is lazy - the transform function isn't called until an element of the view is accessed. But that also means that the transform function is called every time an element of the view is accessed. So every time you iterate through fonts - first for the transform, then for the any_of, and finally for the co...
70,796,803
70,798,203
How to properly increment this 'half-diamond' shape?
I am trying to get the slashes to form a half-diamond type of shape, but I cannot seem to get the incrementation correct. I currently have: else if (menuOption == 2) { int numberOfDolls = 0; cout << "Number of dolls -> "; cin >> numberOfDolls; for (int i = 1; i <= numberOfDolls; i...
int numberOfDolls = 0; int deltaIndent = 0; cout << "Number of dolls -> "; cin >> numberOfDolls; for (int i = 1; i <= numberOfDolls; i++) { deltaIndent = numberOfDolls - i; for (int j = i; j > 0 ;j--) cout << setw(j + deltaIndent) << '/' << endl; for (int j =...
70,797,019
70,797,617
Is (int)(unsigned)-1 == -1 undefined behavior
I am trying to understand the meaning of the statement: (int)(unsigned)-1 == -1; To my current understanding the following things happen: -1 is a signed int and is casted to unsigned int. The result of this is that due to wrap-around behavior we get the maximum value that can be represented by the unsigned type. Nex...
Cast to unsigned int wraps around, this part is legal. Out-of-range cast to int is legal starting from C++20, and was implementation-defined before (but worked correctly in practice anyway). There's no UB here. The two casts cancel each other out (again, guaranteed in C++20, implementation-defined before, but worked in...
70,797,182
70,797,345
Question About a Probability Model Using C++
I am trying to solve a probability question theoretically and then modeling it on C++ but my code outputs a different probability from the theoretical one. Question: A balanced coin is tossed three times. Calculate the probability that exactly two of the three tosses result in heads. Answer: Sample space: {(H,H,H), (H,...
As n. 1.8e9-where's-my-share m. correctly pointed out, You are calling TossCoin() twice. This is your modified code that fixes the problem: #include <stdlib.h> #include <time.h> #include <iostream> bool TossCoinXNumber(int x); int TossCoin(); void CalcProbability(int x); using namespace std; int main() { srand(...
70,797,294
70,801,189
How to read file having different line ending in C++
I have two files "linuxUTF8.srt" and "macANSI.srt". I am reading these files using getline(). as macANSI.srt has '\r' as line ending I am reading the whole file rather than a single line. I know I have to pass '\r' as delimiter but how do I know what type of line ending character I am dealing with.
As Sebastian said, we will need to read the block and then find out the appropriate line-ending. So, we will need to open the file in binary mode and read the last characters. #include<iostream> #include<fstream> #include<string> using namespace std; void SetLineEnding(char *filename, std::string &newline, char &delimi...
70,797,356
70,797,719
Cannot produce any output on increasing size of arr of vectors
I m using minGW compiler along with VScode on windows 10 Problem I m facing is provided below : here I can see output while using an arr of vectors of size 1500 Hello World Execution works . . . But on declaring an arr of vectors of large size I cannot receive any output in terminal How will I be able o work with an...
You blew up the stack. Every std::vector object occupies 24 bytes on the stack (in GCC's implementation). Now 150000 * 24 = 3.6 MB which may easily cause a problem for you. Instead, try this (one of the easiest ways): std::vector< std::vector<int> > v( 150'000 ); or maybe this: std::vector< std::vector<int> > v( 150'0...
70,797,699
70,798,073
Getting An Exception When Compiling The Win32 Console Project In My Code With Unicode (C++ Mingw64 VSCODE)
I am using mingw64 compiler with VSCode. I wrote some code following a tutorial to print something to the console using <Windows.h>. I then modified my code to work with UNICODE characters. I have used WriteConsoleOutputCharacter*( ) to do so. But I get a runtime exception when I run the program. Segmentation Fault in ...
You have to declare DWORD variable not LPDWORD, and pass the variable's memory. DWORD numberOfCharsWritten = 0; WriteConsoleOutputCharacter(hOut, screenBuffer, screenWidth * screenHeight, { 0, 0 }, &numberOfCharsWritten);
70,798,468
70,799,082
GDB: Debug two instances of the same application simultaneous
I am trying to debug two instances of the same application. Therefore I setup as followed: (gdb) set target-async on (gdb) set non-stop on (gdb) attach pid1 (gdb) set scheduler-locking off (gdb) add-inferior (gdb) inferior 2 (gdb) attach pid2 (gdb) set scheduler-locking off (gdb) b hello-world.cpp:8 Breakpoint 1 at 0x5...
To continue all attached processes you have to set the scheduler mode in gdb. set scheduler-locking off A continue now let all threads continue. For a detailed description of scheduler mode take a look here As you ask in the comments what the complete procedure was: (gdb) attach <pid 1> (gdb) add-inferior (gdb) infer...
70,798,928
70,799,265
using a function to print basic student information in c++
I want to print in c++ some general information about students by using a function with parameters void generalities(string fname,string lname,string email,int phone, int age) {\ cout << fname << lname<<" email: "<<email << " Phone: "<<phone<< " Age "<<age;\ } int main() {\ std::cout << "Team generalities";\ generaliti...
The answer @digito_evo gave was a nice improvement. I would go further and overload the operator<< for the struct. #include <iostream> #include <string> struct Generalities { std::string fname; std::string lname; std::string email; std::string phone; std::string age; friend std::ostream& oper...
70,798,937
70,799,080
Whether an implicit type conversion occurs between decimal literals and float types
In C++,the type of floating-point literals is double by default; auto dval = 3.14; // dval is a double So,in the statement float fval = 3.14 , 3.14 -> float means double -> float? Another similar question: float fval = ival + 3.14; what type conversion is happening here
Yes. In the declaration float fval = 3.14 the initialiser is implicitly converted from double to float.
70,799,056
71,975,198
Cython: Assign pointer values, not the pointer itself
C/C++ allows assigning values of a pointer to another pointer of the same type: #include <iostream> using namespace std; int main() { int* a = new int(); int* b = new int(); *a = 999; *b = *a; // Can't do in Cython this? cout <<"Different pointers, same value:" <<endl; cout <<a <<" " <<b <<e...
Using b[0] = a[0] seems to do the trick. Indexing is another way to dereference the pointer. Here's some example code and its output. # distutils: language=c++ cdef cppclass foo: int value cdef foo* a = new foo() cdef foo* b = new foo() a.value = 999 b.value = 777 print('initial values', a.value, b.value) pri...
70,799,228
70,799,661
How to cast a double into std::chrono::milliseconds
I am using boost::asio::steady_timer m_timer and if I am not mistaken, in order to call m_timer.expires_after(expiration_time_ms);, expiration_time_ms should be a std::chrono::milleseconds variable. Nevertheless, in my case, I have the expiration time as a double. I would like to know if it is possible to cast a double...
m_timer.expires_after will accept any duration which is convertible to boost::asio::steady_timer::duration it doesn't need to be std::chrono::milliseconds (and if you don't want to discard the fractional milliseconds from your duration you shouldn't be converting to std::chrono::milliseconds). You can convert your doub...
70,800,927
70,801,960
AllocConsole() doesnt show up
I'm trying to inject a dll into a testprogam and use AllocConsole() for debugging. AllocConsole(); However, the console wont show up and I realized that the program I was trying to inject is running under SYSTEM and I was using an administrator account so the console wont show up on my desktop. Only the conhost proces...
The program is running as SYSTEM so likely it's a service running in the services session (session 0). It's not possible to allocate a console and show it in another session (e.g. the console session). It's not possible for a process to have a window (or console) that is visible in all sessions or even on multiple desk...
70,801,160
71,016,160
Teechart set num of decimals on Axis and hide Axis labels for further series
hope you can help me. In Builder C++ create a new "Windows VCL Application". Add a "Tchart" from "Palette". Right click on the chart -> Edit Chart -> Click on Series -> Add... -> Line -> Ok to create Series1 and repeat to create Series2. Close In Unit1.cpp copy my following sample: //-----------------------------------...
You are adding points to the Line series with the AddY method, passing the x values as the second parameter, which is the label. Doing so, the bottom axis labels indeed overlap. Instead, I'd use the AddXY method, passing the x values as the first parameter and the y values as the second: for (unsigned i = 0; i < x1.siz...
70,801,246
70,805,436
how does one convert std::u16string -> std::wstring using <codecvt>?
I found a bunch of questions on a similar topic, but nothing regarding wide to wide conversion with <codecvt>, which is supposed to be the correct choice in the modern code. The std::codecvt_utf16<wchar_t> seems to be a logical choice to perform the conversion. However std::wstring_convert seem to expect std::string at...
The std::wstring_convert and std::codecvt... classes are deprecated in C++17 onward. There is no longer a standard way to convert between the various string classes. If your compiler still supports the classes, you can certainly use them. However, you cannot convert directly from std::u16string to std::wstring (and vi...
70,801,835
70,805,679
How can I include OpenBLAS and LAPACK manually in xeus-cling binder?
I'm trying to create a C++ Jupyter Notebook using xeus-cling and mybinder. I wanted to include the library armadillo and I was able to do that locally in a Jupyter Notebook as follows: #pragma cling add_library_path("armadillo-10.7.5") #pragma cling add_include_path("armadillo-10.7.5/include/") #pragma cling load("arma...
I suspect you can add an apt.txt configuration file to your repo with the following contents based on here: libblas-dev liblapack-dev That may not quite be the current ones to list and so you may need to look around more to find the current best ones for installing with apt-get in current linux systems; however, that'...
70,801,992
70,802,615
Are variable templates declared in a header, an ODR violation?
What happens when a header file contains a template variable like the following: template <class T> std::map<T, std::string> errorCodes = /* some initialization logic */; Is this variable safe to use? Doing some research on this I found that: Templates are implicitly extern but that does cause ODR violations Without ...
Templates get an exception from the one-definition rule, [basic.def.odr]/13: There can be more than one definition of a [...] templated entity ([temp.pre]) [...] in a program provided that each definition appears in a different translation unit and the definitions satisfy the following requirements. There's a bunch o...
70,802,060
72,979,198
C++ standards conflict in compile_commads
I'm working on some project which uses C++17 standard with clangd-13.0. Sometime after I decided to add library that used C99 standard in its CMakeLists file and now clangd always does analysis based on a C99 standard even in cpp files. My CMakeLists file looks like this: cmake_minimum_required(VERSION 3.21) project(my...
As @drescherjm stated in comments I had just to do: set_property(TARGET tgt_name PROPERTY CXX_STANDARD 17) set_property(TARGET tgt_name PROPERTY CXX_STANDARD_REQUIRED ON) Or set_target_property(tgt_name PROPERTIES CXX_STANDARD 17 CXX_STANDARD_REQUIRED ON )
70,802,977
70,803,148
the pixel values changed while using imwrite to jpg files in c++
I'm writing a code like this in c++: I wish to have a 100% same copy image of test1.jpg. Unfortunately, I find lots of pixel values change after cv::imwrite. int main() { cv::Mat img1 = cv::imread("./test1.jpg"); cv::imwrite("test2.jpg", img1); cv::Mat img2 = cv::imread("./test2.jpg"); int count = 0; ...
If you want non-lossy compression, you can't use jpg's and have to use a .png (there's .bmp as well but its uncompressed) jpg = cv.imread("../resources/fisheye/1_1.jpg") cv.imwrite("1_1.png", jpg) png = cv.imread("1_1.png") np.sum(np.where(jpg != png, 1, 0)) # number of differing pixels between images Output: 0
70,803,002
70,803,387
Difference between const std::array<T,N> and std::array<const T, N>
Is there any practical difference between std::array<const T, N> and const std::array<T, N>? It looks that non-const array holding const elements is still not able to be swapped; assignment operator is not working either. When should I prefer one over the other one? #include <array> std::array<const int, 5> array_of_c...
Copies of std::array<const T, N> are still "logically const", whereas by default a copy of const std::array<T, N> is mutable. If allowing or preventing that matters to you, one is preferable to the other. There are differences in what templates they match, e.g. the case in Ilya's answer.
70,803,177
70,803,383
Making my own Vector. Whats wrong with it?
i am trying to make my own vector but i cant get it to work as i want. I get a error message on the Move-constructor it says: Exception thrown at 0x00007FF751A77ACC in auto-tests.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF. The first one got solved. But now i got the same error with another pa...
You haven't allocated memory for m_elements - and you shouldn't, since this is a move constructor. Just use std::exchange to "steal" the pointer from other and replace it with the value you desire - that is, nullptr. Example: #include <utility> template<typename T> inline Vector<T>::Vector(Vector&& other) : m_nrOf...
70,803,625
70,803,901
C++ square bracket overloading with and without const/ampersand
I am writing C++ code, and ran into a case where I wish to overload the square bracket operator for my class. From various sources, I find that you usually make two methods to do this, one with the const keyword, and one without the const keyword, but with an ampersand (&) before the method name. An example is given be...
Why do I have two methods, one with the const keyword, and one without it? The const keyword sets a constraint that prevents the function from modifying the object. For example, if you use the const keyword in a setter, you'll get a compiler error. So the first function won't allow any modification on the object and ...
70,804,150
70,804,381
How to assign an object to an inhereted function
how can I assign an inherited method to an object? , can you explain to me what is wrong with my code? I am a newbie, so I would like to know if there is a better way to do it int main(){ CalculateData data; data = data.ReadData(data);//does not let me assign data to the method?? } Rest of the code #include<s...
Frankly, it is hard to help, because the error is just a consequence of a flawed approach. I'll use an example simpler than yours that has most of the same issues: #include <iostream> struct Base { int value; Base read(Base b) { b.value = 42; return b; }; }; struct Derived : Base{ int ...
70,804,419
70,804,452
abnormal behaviour in cout. It is printing twice character array after declaration of another same valued character array
So I was writing the code to print a character array in c++. The normal code is:- #include <iostream> using namespace std; int main() { char X[5] = {'A', 'B', 'C', 'D', 'E'}; cout << X << endl; return 0; } and it's printing:-ABCDE as expected but I tried to create another character array like this #includ...
The behaviour is undefined. std::ostream's overload for a const char* (selected due to pointer decay), doesn't stop outputting until NUL is reached. So including NUL terminators in both arrays is the fix: char X[/*let the compiler do the counting*/] = {'A', 'B', 'C', 'D', 'E', 0}; &c.
70,804,439
70,804,719
How to use `std::function<void()>` as a typename in initializing a map?
I want to use std::function<void()> as a typename in initializing a map: namespace kc { class kcmessage { private: std::string value; void warning() {} void error() { exit(1); } std::map<std::string, std::function<vo...
If you want to access a member function ( non static ) you have to bind the method to the instance of the class. For that you can use std::bind but it is much easier to simply use a lambda for that purpose. #include <functional> #include <map> #include <string> #include <iostream> namespace kc { class kcmessage ...
70,804,496
70,804,671
Why does it show terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_S_construct null not valid
At first, I thought there is an error when I was using the while loop so I've tried using for loop but it still displays the same error. I have tried to look up the reason why this error happened but I am still unable to figure out which line in these codes caused the error. int main() { ifstream patientData; s...
In short: You are trying to initialize your arrays with 0, which is a nullptr. So you are actually trying to initialize your first string in the array with a nullptr. Let's examine string patient_name[NUM_PATIENTS] = { 0 }; It defines an old style C array of NUM_PATIENT strings. It initializes this array with { 0 }. ...
70,804,688
70,805,618
Use member in constructor initializer list
Can I safely use members to initialize others? class Class { public: Class(X argument) : memberA(argument), memberB(memberA) {} A memberA; B memberB; }; Here we use the argument to the constructor to initialize memberA. We then rely on the fact that this happens before the initialization of memberB and initial...
Yes, this is safe as per class.base.init#15 The expression-list or braced-init-list of a mem-initializer is in the function parameter scope of the constructor and can use this to refer to the object being initialized. This Note also has an example with this->i to show that previously initialized class members can be ...
70,804,783
70,804,950
Flip order of std::pair
How can I flip the order of std::pair? Is there an in-build command or I need to create a new pair. Currently I am doing this by creating a new pair. std::pair el_ids(0,1); el_ids = std::make_pair(el_ids.second, el_ids.first);
As long as both types of the pair are the same you can just swap them (like @273k has pointed out in the comments), e.g.: godbolt example std::pair p = {1, 2}; std::swap(p.first, p.second); If the types are different you'd have to write a small utility function for it, since there's no built-in way to do that, e.g.: ...
70,804,944
70,805,068
How to get file date Accessed?
I'm looking for this function from std::filesystem but can't figure it out. How to access this information?
Only write time (Modified in your screenshot) is accessible via standard libraries. You'd need to use platform-specific APIs to get access to the other information. For example, assuming Windows (based on the screen shot), you'd use GetFileTime(); this function is able to retrieve the created, modified, and accessed ti...
70,805,071
70,805,112
is there a way to use an unspecified parameter in c++?
I'm trying to have a simple function that is used for debugging in my program just for easeability and I'm wondering if there is a way to just not specify the kind of variable without instead overloading it for every kind possible. In my case would it be possible to have var be able to be any type of variable? void deb...
Yes, you can make debugPrinter a template. template <typename T> void debugPrinter(std::string name, const T & var ) { std::cout << name << ": " << var << "\n"; } In C++ 20, that can be abbreviated as void debugPrinter(std::string name, const auto & var ) { std::cout << name << ": " << var << "\n"; } I've tak...
70,805,526
70,808,214
C++ parsing ambiguity: Constructor vs. parenthesized declarator
I'm trying to write a yacc (menhir) grammar for parsing a very reduced subset of C++ (no templates, headers only with no function bodies allowed...) and am already running into ambiguities. typedef int B; class A { A(); // (*) B(c)(); // (**) }; Case * is a constructor and case ** is a parenthesized declar...
Parsing C++ is frustrating exercise, because C++ is essentially not context-free. You need to know whether an identifier refers to a template, a type, or something else, and name resolution in C++ is not a simple task either. You might, for example, have to instantiate a template in order to know whether a member of te...
70,805,753
70,806,378
Resolution of built-in operator == overloads
In the following code struct A has two implicit conversion operators to char and int, and an instance of the struct is compared for equality against integer constant 2: struct A { constexpr operator char() { return 1; } constexpr operator int() { return 2; } }; static_assert( A{} == 2 ); The code passed fine i...
This is CWG 507. An example similar to yours was given, and the submitter explained that according to the standard, the overload resolution is ambiguous, even though this result is very counter-intuitive. Translating to your particular example, when comparing operator==(int, int) and operator==(float, int) to determine...
70,806,928
70,807,220
Is there any easy way to read a line from a file, split the first text part into a string, then split the last number part into a float?
I have an issue that I haven't been able to find a good way to solve, mostly because I am relatively new to C++, but not new to programming. I have a file with several lines in it, one of them being: Plain Egg 1.45 I need to be able to read that line and split the first part, "Plain Egg", into a string, and then the l...
Grab the line into a string. Get the position of the last separator. Your text is a substring of the line until the position of the separator. Your number is a substring of the line from the position of the separator. You'll need to convert it to double first (and you should check for errors). [Demo] #include <iostre...
70,807,006
70,807,086
Is accessing to std::array<std::uint8_t, 2> while std::uint16_t is active inside a union well defined behavior?
If I have an union union Bytes { std::uint16_t bytes; std::array<std::uint8_t, 2> split_bytes; }; and I use it like this int main(){ auto bytes = Bytes{0xFF'EE}; // do something with bytes.split_bytes[0] and bytes.split_bytes[1] } Assuming the target machine is little endian, is my usage well-defined behavior...
Is accessing to std::array<std::uint8_t, 2> while std::uint16_t is active inside a union well defined behavior? Reading an inactive union member is undefined behaviour. Assigning an inactive trivial union member activates it. Since the target of your attempted type punning is std::uint8_t which is unsigned char, you ...
70,807,171
70,808,717
Time complexity/performance of edge and vertex properties in Boost Graph
Consider: typedef adjacency_list< listS, //out edges stored as std::list listS, //verteices stored as std::list directedS, property<vertex_name_t, std::string>, property<edge_weight_t, double> > user_graph; Storage of edges and vertices as std::list precludes random access via [index]. Consider fur...
is it guaranteed that access to the name of a vertex and weight of an edge are efficient and fast under random access like so: Yes. The properties are actually stored inline with the vertex/edge node. A descriptor is effectively a type erased pointer to that node. name_map[*vi] ends up inlining to something like get<...
70,807,246
70,807,351
Is there any possibility that std::unordered_map collides?
I seen a post in here that you could "meet with the Birthday problem." while using std::unordered_map When should I use unordered_map and not std::map Which really surprises me, that is the same that saying std::unordered_map is unsafe to use. Is that true? If i'm not explaining myself, let me show you an example: unor...
Is there any possibility that std::unordered_map collides? It isn't the container that has collisions, but the hash function that you provide for the container. And yes, all hash functions - when their output range is smaller than the input domain - have collisions. is there any possibility that it prints ERROR!? N...
70,807,458
70,808,543
What am I doing wrong trying to change QPushButton text at runtime?
I'm new to coding with QTCreator, and Linux Graphical Development in general. What is the, probably trivial, thing I am doing wrong here? I could write this code and make it work easily without using the form method, but I'd really prefer to use the graphical interface, as it should be faster (once I know what compiler...
If you put the button in the form designer, and called the button btnStopGo, then it ends up compiled into the ui_mainwindow.h and .cc files. Your MainWindow class, which you wrote yourself, doesn't have a (member) variable called btnStopGo. It does have a variable ui, which points to the user interface which was gener...
70,807,911
70,808,559
Is there a reason this is wrong?
#include <iostream> #include <bits/stdc++.h> #include <numeric> using namespace std; int gcd (int a, int b) { if (a == 0) return b; return gcd (b % a, a); } int phi (unsigned int n) { unsigned int result = 1; for (int i = 2; i < n; i++) if (gcd (i, n) == 1) result++; return result; } int gen...
The decrypt (and encrypt) function is broken in that it (a) is exceeding platform representation of int, and (b) is unnecessarily using pow to do it in the first place. In your trivial example you should be utilizing a technique called modulo chaining . The crux of this is the following. (a * b) % n == ((a % n) * (b % ...
70,808,072
70,808,468
c++ not getting inputs when looping
#include <iostream> using namespace std; int main(){ char opp; double num1,num2; bool cont=true; while (true){ cout<<"Enter first number"<<endl; cin>>num1; cout<<"Enter operator"<<endl; cin>>opp; cout<<"Enter second number"<<endl; cin>>num2; if (op...
You can get the input and store it in std::string and then convert it to anything that is needed (like double, char, etc). Also, it's better to use a switch statement instead of that if-else if-else chain. With a bit of refactoring (and keeping things as simple as possible): #include <iostream> #include <string> #inclu...
70,808,153
70,808,185
output and misunderstanding in C++
I want to know why the output is (1), and why In the second assignment to variable b, the expression (i+=2) does not get evaluated. finally how does this program execute step by step? I am still a beginner. ` int i = 0; bool t = true; bool f = false, b; b = (t && ((i++) == 0)); b = (f && (i += 2 > 0)); cout << i ...
Because the && operator short-circuits and f is false, 1 += 2 is not being evaluated. Since the entire expression can only be true if both operands to && are true, there is no need to evaluate (i += 2 > 0) to determine that the value of the entire expression is false. Given the lack of need to evaluate the second opera...
70,808,433
70,810,764
Make a range from Iterated function application
If I have a function std::array<unsigned,2> fib(std::array<unsigned,2> p) { return {p[1],p[1]+p[0]}; } I'd like to have a way to elegantly generate the infinite range [x,fib(x),fib(fib(x)),fib(fib(fib(x))),...] This comes up frequently enough that I need to find what's the best way to do this?
I found that the generator from this repo works well: template<typename F, typename Arg> tl::generator<Arg> iterated_application(F fn, Arg x) { while (true) { co_yield x; x = fn(x); } } Which can be used as int main() { auto fib = [](auto a) {return std::array{ a[1],a[1] + a[0] }; }; f...
70,808,560
70,808,706
How to detect when a process doesnt exist anymore?
Trying to find a way to get notified when a process doesn't exist anymore, other way than constantly checking for something like"if process exist". Which options do i have?
You can open a process with OpenProcess and use WaitForSingleObject on that process. The function WaitForSingleObject will return as soon as the target process no longer exists. However, you will have to have one thread in a constant wait state if you want your program to be immediately notified when the target process...
70,808,565
74,495,558
Trying to implement NTP Client using Managed C++ but getting date from 1899 using time.windows.com
I am trying to implement a code to get time from time.windows.com but it returns a weird date (year of the date I get is 1899). Since the same servers work for my unmanaged C++ code using WinSock, I can imagine that something must be wrong with my code itself. Can someone look at my code below and tell me what I am doi...
David Yaw pushed me in the right direction. Big thanks to him, I finally got my code to work. There was a lot of incorrectness associated with different statements throughout the method. I have fixed them and posting the new code below. ref class SNTP { public: static DateTime GetNetworkTime() { System::String^ ntp...
70,808,793
70,809,116
Can CUDA Kernels Modify Host Memory?
Is there any way to get a kernel to modify an integer via passing a pointer to that integer to the kernel? It seems the pointer is pointing to an address in device memory, so the kernel does not affect the host. Here's a simplified example with the behavior I've noticed. #include "cuda_runtime.h" #include "device_launc...
Yes, you have a misunderstanding. cudaMallocManaged is an allocator like, for example, malloc or new. It returns a pointer that points to a new allocation, of the size requested. It is not some method to allow your host stack based variable to be accessed from device code. However, the allocated area pointed to by th...
70,808,916
70,808,972
C++ "Exception has occurred" during assignment statement to a double array
I am relatively new to C++, and I'm trying to write a simple code to solve a partial differential equation. The solution code is repeated a number of times with a different value of a time increment dt. During the fifth iteration (j=4), my IDE throws an error: Exception has occurred. EXC_BAD_ACCESS (code=2, address=0x7...
When j is 4, your numTimes[k] should be 100001. You're allocating 2 arrays of double at that size on your stack. That puts it at 1.6MB approx. That may exceed your stack size in some environments. It's going to get worse for higher values of j. I suggest to not use variable length arrays that are allocated on stack. Us...
70,809,087
70,809,194
How can I solve this problem with chain inheritance c++?
Basically I'm studying about Chain Inheritance in my college and I'm expected to build a program with this, the problem I have is in this part: template <class NUM_TYPE> class FilterPositiveNumber: public Filtro<NUM_TYPE> { bool dadoValido(NUM_TYPE& d) const override { // TODO: Implemente este metodo. if (d >...
template <class NUM_TYPE> class FilterPositiveNumber: public Filtro<NUM_TYPE> { ... }; defines a class template, a blueprint for a potential family of classes. To use it you must tell the compiler, or the compiler must be able to infer, what type the template is to be specialized on in order to become a class. class F...
70,809,151
70,809,538
Default move constructor failing when used in a constexpr context,
I have an issue with the default move constructor in Visual Studio 2022 (/std:c++latest) in a constexpr context. I do not see the issue in Visual Studio 2019. I have two questions: Is it my code or Visual Studio 2022 that is incorrect? If my code is incorrect then why? Are similar issues are seen in gcc or clang? (I d...
You should use: constexpr Container(Container&&) = default;. The default implementation is already noexcept in most cases. From cppreference: default constructors, copy constructors, move constructors that are implicitly-declared or defaulted on their first declaration unless: a constructor for a base or member that ...
70,809,242
70,809,274
Is it possible for an address of an std::array member to be null in C++?
Is it possible to modify a to make the if-statement fail? std::array<int,4> a = {{1,2,3,4}}; for (int i=0;i<a.size();i++) { auto ptr = &a[i]; if (ptr != nullptr) { printf("value at %d is %d\n",i,a[i]); } else { printf("Invalid array\n"); } }
The address of an element in a standard library container can't be null, as long as you are using the container's API properly. This is because, assuming you meet all preconditions of the API, the container guarantees that all of its elements are valid objects, and a valid object never has a null address. As soon as yo...
70,809,725
70,809,853
How do I make my header, function and main file work together, I always get: error: Id returned 1 exit status
I made a very simple C++ program where the goal is to use functions in different files. The function justs prints out a certain message passed in a parameter. After some research, I read that for such project, I need 3 files: the main, the header and the function (apparently I shouldn't put the function code in the hea...
I was use visual studio 2019 to compile your code. First compile error output:"Error C2065 'cout': undeclared identifier message". When I add #include<iostream> in simple.h and change simple.cpp message function the cout to std::cout, the program output "Hello world!" simple.h #ifndef SIMPLE_H_INCLUDED #defin...
70,810,035
70,810,108
Restarting a loop in C++?
I am in need of assistance with my program. I have to code a three-round word scramble program using 10 keywords that will appear scrambled to the user for them to guess it. My problem is that after one word the code just simply exits the loop. My intention is for the loop to be used again for a second and third time b...
#include <cstdlib> #include <ctime> #include <iostream> #include <string> using namespace std; int main() { while (true) { enum fields { KEY, HINT, Locked }; const int NUM_WORDS = 10; const string WORDS[NUM_WORDS][Locked] = { {"MITCHELL", "NICKNAME IS MITCH,SO WHAT IS MY NAME?"...
70,810,045
70,815,845
How to generate a list of unknown number of items without using a loop
Is it possible to generate a list of items if I don't know how many there are in the list, without using a loop? Here's an example (using a loop): vector<int> bits(int N) { vector<int> v; while (N != 0) { v.push_back(N & 1); N >>= 1; } return v; } In this example, I don't know how man...
Something along these lines perhaps, if you absolutely insist on going out of your way to get STL to run loops for you: class BitIterator { public: using value_type = int; using difference_type = std::size_t; using pointer = int*; using reference = int&; using iterator_category = std::input_iterator_tag; ...
70,810,602
70,811,958
C++ Container of Pointers/References to Existing Objects
I have an existing container filled with automatically allocated struct objects like so: std::vector<Object> objectList {obj1, obj2, obj3}; I'm trying to create a new container useObjectList that consists of pointers/references that point to those existing objects so that I am able to access and modify the object memb...
To use a "C++ Container of Pointers/References to Existing Objects", or pretty much anything else, you should understand the concept of ownership. Summary: ownership is responsibility for cleanup. You should think which entity should delete your objects. Often, you should rethink this whenever you change your code or a...
70,810,746
70,810,771
how to call overloaded function in the same version of another in c++
Greetings I have a class with overloaded functions I do not want to re type whole thing again and again so I created function(s) with different parameters see below example and I get compilation errors please help consider below snippet class A { public: inline A(); inline ~A(); QString insert(QString& ...
You have to be in the scope of the class A when defining the member functions outside the class. This can be done using A:: as shown below. class A { public: inline A(); inline ~A(); QString insert(QString& id, QString& name, QString& email_id, QString& contact_id, QString& reg_num, Address addr, QUrl& ...
70,810,775
70,810,809
The solution is executed with error 'out of bounds' on the line 7
I have received this bound error though the sample input and output match. I tried several ways to solve this error, but I couldn't. Please help me to overcome this problem. And also please, explain why? what is the main reason for this error?. My code as follows: #include <iostream> using namespace std; int main(){ ...
Array indexes start at 0 so a[4] is out of bounds in your case.\ Since we're here I recommend to not use C arrays. Use std::array or std::vector instead. Also it's better to use the range for.
70,811,081
70,811,174
Coufused about using cpp to achieve selection sort
I tried to implement selection sorting in C++,when i encapsulate the swap function, the output shows a lot of zeros.But at beginning of array codes still work.When I replace swap function with the code in the comment, the output is correct. I am so confused by this result, who can help me to solve it. #include <iostrea...
Problem is that your swap function do not work if a and b refer to same variable. When for example swap(array[i], array[i]) is called. Note in such case, this lines: b = a - b; will set b to zero since a and b are same variable. This happens when by a chance i array element is already in place. offtopic: Learn to split...
70,811,249
70,815,468
Boost Kruskal minimum spanning tree algorithm -- undirected vs directed graph documentation
Per the documentation, the minimum spanning tree algorithm implemented in boost should work only on undirected graphs. Yet, the following code that provides a directed graph as input to the algorithm seems to work just fine: (while building on MSVC Visual Studio 2019, there are no warnings related to boost) #include <b...
I'd simplify the code Live #include <boost/graph/adjacency_list.hpp> #include <boost/graph/kruskal_min_spanning_tree.hpp> #include <iostream> using Graph = boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property, boost::property<boost::ed...
70,812,077
70,816,363
How can I correctly create a C++ vector in Python3 by swig?
I try to test swig library 'std_vector.i', but I can't create a vector in Python3 like official demo, Here is some information. swig_test.i %module swig_test %{ #include <vector> void worker(std::vector<int> &v) { v.push_back(123); } %} %include <std_vector.i> %template(MyVector) std::vector<int>; void worker(st...
The problem here is how you're importing and using the module you've built. When you ran SWIG as well as generating some C++ code it also generated some Python too. Rather than directly access the native module you want to access it via the generated python instead, e.g. import swig_test # Note no leading _ v = swig_te...
70,812,129
70,812,651
Building multiple binaries in CMake from Zephyr RTOS project, each with different device address
I have a project that consists of nodes in a mesh, that will communicate between each other wirelessly and will identify each other with a use of addresses. Nodes will be equivalent in their responsibilities so the source code for each them will be identical, except for address which I would like to be specific and uni...
Create a custom ELF section in your project with the address. Use compiler specific syntax. This is for GCC compiler: // volatile, so that optimizer does not bite us __attribute__((__section__("myaddress"))) __attribute__((__used__)) volatile const uint8_t _address[20] = {0}; # external API - fetch the address # remov...
70,812,204
70,812,241
Is it possibile to call virtual methods with shared pointers?
class Base { public: virtual void f() const { std::cout << "Base::f()" << std::endl; } }; class Derived : public Base { public: void f() const { std::cout << "Derived::f()" << std::endl; } }; int main() { Base* obj = new Derived; std::shared_ptr<Base> sp = std::make_shared<Base>(*obj); sp->f(); /...
sp points to an instance of type Base, not Derived. You can't clone derived classes using a pointer to base like this. std::shared_ptr<Base> sp = std::make_shared<Derived>(); would work. ... =std::make_shared<Derived>(std::dynamic_cast<Derived&>(*obj)) would also work;
70,812,278
70,812,391
reference_wrapper: Is this UB?
I'm curious if this code is UB. https://wandbox.org/permlink/nU0iPLCrPXwQ7Kor The code does not crash (in both GCC and Clang, with or without optimization), which makes me more and more baffled.. #include <list> #include <vector> #include <iostream> #include <utility> #include <queue> using namespace std; int main() ...
The reason why your code does not crash is because you get lucky with regards to implementation details of deque. A deque allocates memory in blocks of 512 byte. The first and last block in a deque can be partially filled at their front or back, respectively. Pointers mark these locations. A pop_front simply moves that...
70,812,322
70,812,494
When using function calls to template functions, I am faced with an unexpected matching template function for my call
For the following code, why is the compiler matching my function calls with (an unexpected) template function: First of all here are the function templates available: // First function template template <typename T, typename U> auto sub(T x, U y) { return x - y; } // Second function template template <typename T> ...
You can supply a partial list of template parameters. For example, if you have template <typename A, typename B, typename C> void foo(A, B, C); then these calls foo(1,2,3); foo<int>(1,2,3); foo<int, double>(1,2,3); foo<int, double, float>(1,2,3); are all good. So sub<double>(2.3, 234.2f); still matches both the first...
70,812,345
70,818,052
C++ print a structure with cout
I have been trying to find a simple way to return 2 values from a function and found online that creating a structure to store the values was the easiest method of doing so. Now I have written the structure and the function I can not figure out how to actually print the structure. I have seen many other posts about thi...
There are at least three ways to do this. Method 1: Get the struct result and print it This is the simplest solution. int main() { values vs = quadratic(1, 2, -1); std::cout << vs.value1 << ", " << vs.value2 << "\n"; } Method 2: Use automatic structured bindings This requires C++17 minimum (I think, you should...
70,812,376
70,812,572
How std::atomic wait operation works?
Starting C++20, std::atomic has wait() and notify_one()/notify_all() operations. But I didn't get exactly how they are supposed to work. cppreference says: Performs atomic waiting operations. Behaves as if it repeatedly performs the following steps: Compare the value representation of this->load(order) with that of o...
Yes, that is exactly it. notify_one/all simply provide the waiting thread a chance to check the value for change. If it remains the same, e.g. because a different thread has set the value back to its original value, the thread will remain blocking. Note: A valid implementation for this code is to use a global array of ...
70,812,427
70,812,782
Should warnings about missing typename supressed in c++20?
Warning messages like: missing 'typename' prior to dependent type name ... [-Wtypename-missing] and template argument for template type parameter must be a type; omitted 'typename' is a Microsoft extension [-Wmicrosoft-template] If I understand right c++20 relaxed the need for typename. Does this mean that these warnin...
No, the warning is useful. Fix your code. C++20 relaxed the typename rules a little bit. But it's unrelated to this warning. MSVC considers typename to be (almost?) completely optional, and is non-conforming in this regard. Clang apparently can do that too, for compatibility with MSVC. The warning says that your code i...
70,812,439
70,812,699
C++: What is the evaluation order of the user-defined comma operator?
I was reading the "C++ 17 Completed Guide" by Nicolai Josuttis and came across the following expression: foo(arg1), (foo(arg2), foo(arg3)); The author claims that the evaluation order will be left to right for the built-in comma operators, but it can be changed by overloading them. However, I saw the "Order of evaluat...
Evaluation order was a mess prior to C++17. C++17 made sweeping changes to evaluation order, this is most likely just a mistake by the author. Prior to C++17, overloaded operators are complete syntax sugar. With any binary operator @, a@b is equivalent to one of operator@(a, b) a.operator@(b) depending on whether it i...
70,812,481
70,813,480
container iterators - should they be nested?
Should the custom iterator for a customer container be a nested class or a free(for a lack of better word) class? I have seen it both ways, especially in books and online, so not sure if one approach has advantage over other. The two books I am using both have the iterators defined as free classes where as online first...
The fact is that an iterator, it is built and used for a specific class, so there is no need for it to be defined outside. Since you only use it in coordination with your container. Different thing if your iterator it is used by different classes, but I can't really find an example of where it could be useful. Edit. Fi...