question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
63,465,068
63,465,567
Create a 2 dimensional matrix from array in OpenCV
I am completely new to OpenCV and I have troubles creating a matrix. I read the docs, browsed similar questions on stackoverflow and for the love of me I cannot figure out what I'm doing wrong. I'm using Visual Studio 2017 and OpenCV version 4.4.0 I'm trying to create an 8x8 matrix and fill it from an array. The dimens...
You tried to use CV_64FC4 pixel type that has 4 channels, so it expects 4 double values per element. To create n x m cv::Mat with single value per element, use CV_64F type: cv::Mat M(n, m, CV_64F, data);
63,465,107
63,465,129
Returning Pointer to Bidimensional Array [C++]
I don't know why but it doesn't return the bidimensional array I declare in the function. char** canvas() { char canvas[18][8]; fill(canvas[0], canvas[0] + 18 * 8, 'O'); return canvas; }
canvas is a local variable, its lifetime will expire as the function goes out of scope, accessing this variable through a pointer after that will invoke undefined behavior. The return type of the function is also incompatible with the object you're trying to return. If you must use C-style arrays (inferred from your co...
63,465,397
63,465,662
C++ implementation of Binet's matrices for Fibonacci series
For the following code, I am getting this error: no known conversion from 'int' to 'const std::vector<std::vector<int, std::allocator >, std::allocator<std::vector<int, std::allocator > > >' for 1st argument. Can someone please point out the mistake? class Solution { public: int climbStairs(int n) { vector<...
You are returning the wrong type from mult. You should be returning std::vector<std::vector<int>>, not int. #include <vector> class Solution { public: int climbStairs(int n) { std::vector<std::vector<int>>B{{1, 1}, {1, 0}}; for(int i = 1; i < n; i++){ B = mult(B); } retu...
63,465,589
66,258,164
Running C++ executable from python script
we are currently working on robot Pepper, more specific we are trying to prepare Pepper as welcome manager. So when robot gets input from human to go to a certain location, he should start specific dialog for that location and moving to that location. We did the navigation part in ROS and human-interaction part in Pyth...
Relaying M.A's answer here: subprocess, e.g. subprocess.run(["your_exe", "first_arg"]). You can also do things like capture stdout/stderr from the subprocess, check return code, wait for subprocess to complete.
63,465,877
63,466,760
Why can't I call my struct Semaphore methods?
I am trying to input lowercase char and to add it to in.buffer, the other thread should read from in.buffer and make it lowercase and send to out.buffer, and the last one should read from out.buffer and print it. I am getting error: expected identifier before numeric constant Semaphore m_free(10); error: invalid use of...
You can't "call" anything inside a struct. A struct contains definitions of its members, not code. You can initialize a member in a constructor: struct RingBuffer { Semaphore m_free; RingBuffer() : m_free(10) {} // constructor with a member-initializer-list }; Or inline using a default member initializer: stru...
63,465,943
63,467,471
How to get array from ITK image without using loop?
Maybe have a function return a pointer or copy memory to a given pointer.
SimpleITK::Image has a lot of methods that return the pointer as you need: https://simpleitk.org/doxygen/latest/html/classitk_1_1simple_1_1Image.html you might want: SimpleITK::Image::GetBufferAsVoid() or other ones ...
63,466,105
63,466,258
Strange output when printing char assigned to hex value using std::cout
I am trying to print these data type. But I get a very strange output instead of what I expect. #include <iostream> using namespace std; int main(void) { char data1 = 0x11; int data2 = 0XFFFFEEEE; char data3 = 0x22; short data4 = 0xABCD; cout << data1 << endl; cout << data2 << endl; cou...
Most likely you expect data1 and data3 to be printed as some kind of numbers. However, the data type is character, which is why C++ (or C) would interpret them as characters, mapping 0x11 to the corresponding ASCII character (a control character), similar for 0x22 except some other character (see an ASCII table). If y...
63,466,847
63,467,505
How is it possible to convert a std::vector<std::vector<double>> to a torch::Tensor?
I have a std::vector<std::vector<double>> where I want to conver it into a torch::Tensor in libtorch. However it seems, the torch::tensor(), or torch::from_blob(), can't be used for this purpose! I tried to use c10::ArrayRef and then use that for converting the data into a torch::Tensor by doing c10::ArrayRef<std::vect...
the easiest way would be to use a simple std::vector<double> instead of a vector of vectors. You would have contiguous memory and torch::from_blob would work (as mentionned in the other answer). If that is not possible/convenient, I suggest the following workaround. I assume that your vector is a (n,m) matrix (i.e all ...
63,466,914
63,468,679
Move-semantics vs const reference
my class has string variables and I want to initialize them with values passed to the constructor. My teacher thought us to pass strings as a const-reference: MyClass::MyClass(const std::string &title){ this->title = title } However Clang-Tidy suggest using the move command: MyClass::MyClass(std::string title){ t...
None is optimal since they both default construct title first and then copy assign or move assign it. Use the member initializer list. MyClass::MyClass(const std::string& title) : title(title) {} // #1 // or MyClass::MyClass(std::string title) : title(std::move(title)) {} // #2 //or MyClass::MyClass(const s...
63,466,933
63,466,974
__FUNC__ undefined in VSCode
I knew __FUNC__ is predefined macro, but when come to vscode it can not recognize __FUNC__. https://learn.microsoft.com/zh-tw/cpp/preprocessor/predefined-macros?view=vs-2019 Which setting should I need to change or modify?
You want __func__, not __FUNC__. If you’re on gcc or clang and the goal is to get readable output you can use __PRETTY_FUNCTION__ instead which yields better results (such as actually working for template functions).
63,467,490
63,469,450
How write sort with unknown argument. Cant iterate with void*/
In this void* ic = b + j * sz; and this void* jc = ic - sz; lines ide writing that expression must be a pointer to a complete type. I need to wright function which can sort everything so i use void*. I don't now how to iterate with void*. How get access to elements void* baselike array. UPD pcharToInt is wrong. At fist...
In C++ you don't throw away type information. Instead of typedef int (*CFT) (const void*, const void*); void insort(void* base, size_t n, size_t sz, CFT cmp); int cmp1(const void* a, const void* b); You should be writing template<typename T> using CFT = bool(*)(const T *, const T *); template<typename T> void insort(...
63,467,648
63,467,797
C++ - memory leak caused by using placement new over *this pointer?
As we know, placement new just constructs an object without allocating any memory. Also all members in the class Resource are objects instead of pointers, although std::string internally holds a dynamic array which will be freed when the std::string object is being destroyed. And *this points to the memory allocated on...
The standard (latest draft) says: [basic.life] A program may end the lifetime of any object by reusing the storage which the object occupies ... if there is no explicit call to the destructor or if a delete-expression is not used to release the storage, the destructor is not implicitly called and any program that depe...
63,467,893
63,468,022
Assigning to DWORD from incompatible type nullptr_t
Despite reading several internet and forum questions/answers I do not yet understand why the following code generates an "assignment from incompatible pointer type" error. void ITEM_MANAGER::FindItemMonster(LPCHARACTER ch, std::string name_item){ DWORD iGasite = 1; int iIndex = 0; itertype(m_map_pkDropItemG...
You are using NULL as a constant for zero, when it has been defined as: // in /usr/include/sys/_null.h:35:14 #define NULL nullptr Since C++11, this is the standard definition. The type of nullptr is std::nullptr_t, not an integer, so it can't be assigned to DWORD iGasite which is an unsigned int. Simply remove all pla...
63,468,513
63,468,563
How to use the same constructor argument as a class parameter in order to save memory
I am currently working in an embedded system that has an extremely low amount of available memory (2 kB!). So, I need to save as much memory as possible. And I need to pass as Struct as argument to the constructor and then work with this struct inside my class. The traditional way that I normally do that is as follows:...
You could have a member of reference type, so that you don't have to make any copies: class Class_name { Data_type &newInstance; // this refers to the parameter passed to the constructor public: Class_name(Data_type &passed_as_reference) : newInstance(passed_as_reference) {} AMethod() { third_party_method...
63,469,223
63,469,262
C++ char array[] memory leak
i created char arr[] and assign to it string literal char arr[] = "some string"; // arr occupies 12 chars in memory std::cout << std::strlen(arr) << std::endl; // lenght is 11 chars + 1 null-terminator //arr[11] is '\0' next i put null-terminator into 6 el...
Is it memory leak? No. How compiler will know that it must free memory after first '\0'? (when will delete variable arr) The variable is 12 chars. It's the same as writing: char arr[12] = "some string"; So it will always free 12 chars. The variable is an array of 12 chars; the fact that the 6th char happens to...
63,469,333
63,469,419
Why does the false branch of "if constexpr" get compiled?
Why is this code giving error while compiling? My knowledge (and also this) of "if constexpr" says the else block shouldn't get compiled. if constexpr (true) { int a = 10; } else { int b = 10 } The error is: error: expected ‘,’ or ‘;’ before ‘}’ token Compiler used: g++ version 7.5.0 While compiling I used -s...
There are 2 separate, but related issues here. Firstly, if constexpr will only conditionally compile a branch within a template. Outside of a template, all branches will be compiled and must be well formed. Secondly, even in a template, the discarded branch of an if constexpr can't be ill-formed for all possible instan...
63,469,656
63,469,806
Issues with C++ bitfields
I have to write a file header with a specific data format. For simplicity, let's just assume it is: bits [0-7]: index a bits [8-9]: index b bits [10-15]: index c All of them are simple unsigned integers. I thought I might use bit fields to get a nice syntax. I defined struct Foo { unsigned int a : 8, b : 2, c : 6; ...
From [class.bit]/1 [extract]: [...] Allocation of bit-fields within a class object is implementation-defined. Alignment of bit-fields is implementation-defined. and, from [defns.impl.defined]: implementation-defined behavior behavior, for a well-formed program construct and correct data, that depends on the implemen...
63,469,757
63,472,723
Segmentation fault when stepping into a function defined in the same file using an ARM cross-toolchain
I have this simplified example, int myf(void) { int a = 1; int b = 2; return a + b; } int main(void) { int sum = myf(); // <--- bp here printf("Result: %d\n", sum); return 0; } I have a breakpoint at int sum = myf() and I run the debugger. Gdb successfully stops at this point, but a step into...
Set the GDB search path - in Tools->Options->Debugger. In the Additional Startup Commands box. Place there the correct sysroot (corresponding to the platform you are running from), and follow with the full path of your shared libraries debug build, from the local machine. Also, make sure to run as regular user (set in ...
63,470,173
63,471,344
How to stack a tensor of shape (n, k) with tensors of shape (k) in libtorch?
torch::stack accepts a c10::TensorList and works perfectly fine when tensors of the same shape is given. However, when you try to send the output of a previously torch::stacked Tensor, it fails and gives memory access violation. To be more concrete, let's assume we have 3 Tensors of shape 4 like: torch::Tensor x1 = tor...
You can add a dimension to y with torch::unsqueeze. Then concatenation with cat (not stack, so different from numpy but the result will be what you ask for) : torch::Tensor x1 = torch::randn({4}); torch::Tensor x2 = torch::randn({4}); torch::Tensor x3 = torch::randn({4}); torch::Tensor y = torch::randn({4}); torch::Te...
63,470,603
63,470,739
What is the best way to take an input line and add the words in the line to a vector in C++?
Basically I want to take an input line with multiple words (length not specified), word by word and add each word to a vector. I can use getline and write a function to split it but wanted a more concise way to read each word and keep on adding it to a vector till Enter key is pressed. Something like this till enter ke...
A nice way to split each word of the string and store them into a vector would be taking the help of std::istringstream (from sstream library): #include <iostream> #include <vector> #include <sstream> int main(void) { std::string input; std::string temp; std::vector<std::string> words; std::getline(std::cin, ...
63,471,019
63,471,113
Expression isn't computed correctly
I wrote this code that has evaluated everything correctly until this specific set of numbers : #include <cmath> int n1 = 187972 ; int n2 = 12026 ; double a = 0.002 ; int partial = round((n1*n2)*a) ; int result = n1 - partial ; result is returned by the program as 4256804, which is completely wrong. I suppose I am mis...
as in the comments suggested, the result is correct because n1*n2 is overflowing the int max value generating a negative number as result from an overflow actually -2034416024 here ideone so you can verify https://ideone.com/NIGCmx a solution could be use long numbers instead
63,471,049
63,471,220
recv() returns strange buffer C++
I know C++ for quite long, but started using it for my purposes some what a year and a half ago. I started learning network programming on C++ and the first networking project is "File Transfering between hosts over TCP/IP" which sounds kind easy but I am stuck with sending data. I am trying to send small buffer less t...
In C++, sizeof(buffer) is the size of the pointer type. You may want to read up on more modern (as in after 1998) C++. We have std::vector nowadays, and that has a convenient size method. It would return 4096 for your buffer. Also, vector handles new[] and delete[] for you. The fact that you get 8 "a"'s suggests that y...
63,471,251
63,471,298
How many chars or characters , or bytes of data std::cout can output at once?
I am learning C++, so you are very right to assume that I am new to C++ and programming as well. I am trying to understand iostream library, not the whole, but the things that newcomers must know before jumping into another topic. My understanding of std::cout is that it is a variable that holds bunches of chars or val...
There is no specified limit. There may be a practical implementation specific limit. Most likely, it will be way more than you'll need. Note that std::cout streams to standard output. While that is often displayed in console, that is not necessarily the case.
63,471,387
63,472,782
Should volatile still be used for sharing data with ISRs in modern C++?
I've seen some flavors of these question around and I've seen mixed answers, still unsure whether they are up-to-date and fully apply to my use case, so I'll ask here. Do let me know if it's a duplicate! Given that I'm developing for STM32 microcontrollers (bare-metal) using C++17 and the gcc-arm-none-eabi-9 toolchain:...
I think that in this case both volatile and atomic will most likely work in practice on the 32 bit ARM. At least in an older version of STM32 tools I saw that in fact the C atomics were implemented using volatile for small types. Volatile will work because the compiler may not optimize away any access to the variable t...
63,471,746
64,039,893
C++ SYSENTER x86 calls in inline assembly
I'm about to learning how sysenter on x86 works. and i created a simple console application on x86 platform, which should call the NtWriteVirtualMemory function manually in inline assembly. i started with this code here, but it seems that the compiler dont understand the opcode "sysenter" so i decided to _emit them wit...
Making system calls in x86 Windows is different from x64. You need to specify the correct arguments length in ret otherwise you will get illegal instruction and/or runtime esp. Furthermore I don't recommend you to use inline assembly, instead use it inside an .asm file or as shellcode. To make a correct x86 system call...
63,471,924
63,471,994
Werror missing declarations in C++ with SFML
I am making a game using C++ with SFML lib and in my main I created couple functions. I know it is a bad manner to do that in main but yeah. when I try to compile the code I am getting error: src/main.cpp: In function 'void create_platforms(std::vector<std::unique_ptr<sf::Sprite> >&)': src/main.cpp:12:6: error: no prev...
can I just declare those in main.cpp? Technically yes. What matters for the -Wmissing-declarations option is that a declaration is before definition. The file in which you put the declaration is irrelevant. Note however that this may be against the spirit of the warning. It is unclear why you want to get warnings abo...
63,472,006
63,492,984
Is there a way to use backspace in terminal without hitting backspace key
I have a configuration in VS code for running CPP files using code runner extension. It is configured to run "cd $dir" which outputs cd "c\Users\user\folder\" instead of cd "c\Users\user\folder" Because of the last backslash, this command not giving any output so I am looking for an option to use a backslash to ad...
I suggest adding a shell delete to your command: \u007f so cd $dir\u007f should delete the last character output by $dir. The hexcode is here: https://github.com/xtermjs/xterm.js/blob/0e45909c7e79c83452493d2cd46d99c0a0bb585f/src/common/data/EscapeSequences.ts but it is easy to convert to unicode.
63,472,425
63,472,773
Why are pow(x,1/p) and pow(x,1.0/p) not equal even though printing their values gives the same result
The question is: You are given 2 numbers (N , M); the task is to find N√M (Nth root of M). Input: The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains two space separated integers N and M. Output: For each test case, in a new line, print an ...
Why are pow(x,1/p) and pow(x,1.0/p) not equal even though printing their values gives the same result (?) Computations differ due to precision. Computations are not mathematically exact: pow() did not receive an exact 1/3. With float p, 1/p can differ from 1.0/p as the first is done using float (or wider) math and t...
63,472,739
63,473,098
Log anything i want using auto keyword
I programmed a log class that logs messages in color in the terminal. I want it to be able to log anything I give it to log. I guess templates are the way to go. But can't i use auto as an argument type, then check if it is a string and if not call the tostring method of the object ?
Since c++20 you can use auto and overload for the other types you want to handle differently. void log(auto test) { std::cout << std::to_string(test) << std::endl; } void log(const std::string &str) { std::cout << "str: " << str << std::endl; } int main() { log(std::string("test")); log(10); }
63,472,896
63,473,086
Why does C++ not attempt to use the second template overload?
I was implementing a simple smart pointer class, and I decided I wanted to make my own versions of the std::make_unique / std::make_shared functions to go along with it once I finished. I created these two overloads: // note: Box<T> is my "unique pointer" type, it has a partial specialization for T[], // and it works a...
"Forwarding reference" deduced template type arguments are greedy, which is interfering with your overload resolution. When you call: auto box = make_box<Point3D[]>(20); This is actually calling make_box<T,Args...> with T = Point32[] and Args = int -- which is unambiguously resolved as a better overload than calling m...
63,473,426
63,473,458
How to fix Segmentation Fault in linked list
I'm getting a segmentation fault error that I don't know how to fix. List.cpp and List.hpp are bigger, but I added just what I'm using in main.cpp. Here is the code: List.hpp #ifndef LIST_H #define LIST_H #include <iostream> #include <cstdlib> struct Node{ int _value; Node *_next; }; struct List{ Node *_...
As the error(warning) message says, in the insert function you are doing: Node* node; But this simply declares a pointer that is not yet pointing to valid memory. Accessing members of the object such as _value pointed at by node will invoke undefined behavior. This can cause a segmentation fault. If you're unlucky, th...
63,473,484
63,475,603
LLVM KaleidoscopeJIT: How to view errors?
I've been following the LLVM tutorial and I'm now trying to tweak & try extending things but I keep running into an error where code won't JIT & the compiler (the one I've made with LLVM) will abort with: piler: /usr/lib/llvm-9/include/llvm/Support/Error.h:626: llvm::Expected<T>::storage_type* llvm::Expected<T>::getSto...
Solved this. .getAddress() returns an llvm::Expected which wraps around the address, it can contain an error or the address if found. To handle/log the error you must 'take' the error and log it with llvm::logAllUnhandledErrors auto address = expr_symbol.getAddress(); if (auto err = address.takeError()) { ...
63,473,644
63,528,019
How to convert gps time to utc in c++?
I am collecting GPS time (in ns) from a sensor and I am looking for a way to convert that to a UTC time in C++. I have a working code before in python. time_gps = time_gps * 10**(-9) # Converts ns -> s gps_epoch = pd.datetime(year=1980, month=1, day=6) delta = pd.to_timedelta(time_gps, unit='s') time...
I'm assuming that leap seconds are important to you since you're dealing with gps time which represents the physical seconds that are labeled leap seconds by UTC. It is fairly tricky to manipulate date/times with leaps seconds, which is why Unix Time is so popular in computer systems. In the C++20 chrono preview libra...
63,473,691
63,474,053
Create player objects based on the number of players from user input?
Background: I have created a player class and I want to ask the user how many players are going to play the game? Based on the user input I am trying to create that many instances of the player class. However, I used the following links to help me: Create object using user input http://www.cplusplus.com/forum/beginne...
The problem is with your while loop: int totalPlayers = -1; cout << "Enter total number of players: "; while ((totalPlayers < 1) && (totalPlayers > 5)) { cout << "How many players will be playing? (1-5): "; cin >> totalPlayers; } The while loop will only run if the condition is true, bu...
63,474,134
63,474,230
how to free memory of char arrays after passing them to exec*() family of functions
I am writing mixed C++/C code and making use of exec* family of C functions. consider the following code: char **argv = new char* [3]; argv[0] = "ls"; argv[1] = "-la"; argv[2] = NULL; execvp(argv[0], argv); perror("Failed to execute"); exit(EXIT_FAILURE); I understand that if execvp succeeds then it won't return, so t...
Should I be concerned about any sort of memory leak? When execvp succeeds, it would have replaced entire image with the ls process (copying all the arguments) and memory you allocated will be reclaimed automatically - the image will be torn down. This is not a memory leak and there's nothing you can or need to do in ...
63,474,315
63,500,826
AsmJit emit bytes or x64 absolute far jump
I want to emit absolute far jump using asmjit. Bytes of this jump: FF 25 00 00 00 00 // jmp qword ptr [null offset] 00 00 00 00 00 00 00 00 // 8-byte jump target address But I don't know how to emit jmp qword ptr [*] with 0 offset and raw address bytes after it. Can someone help me? Thanks in advance! UPD: I know how ...
There are multiple options: a) Embed the address after jump, this answers the question: a.jmp(asmjit::x86::ptr(asmjit::x86::rip)); a.embedUInt64(addressToEmbed); b) Do the same with Label: Label constPool = a.newLabel(); a.jmp(x86::ptr(constPool)); // later in the code. a.bind(constPool); a.embedUInt64(addressToEmbed...
63,474,446
63,474,710
How can I include my direct x install location in clion?
I'm trying to use clion, however when I try to include d3dx9.h it says it cant find the file specified, meaning that I'd have to include my directory for my dx9 install. I know in vs you can do it in your project properties, but I cant figure out how to do it in clion. Any help would be greatly appreciated, thank you.
Create CMakeLists.txt file in root of your sources, even if you build your project using different build system. CLion by default uses cmake and does not understand configuration files of other build systems and it needs this CMakeLists.txt to set up indexing of your project. In this CMakeLists.txt configure paths to l...
63,474,485
63,474,942
error with makefile in c++ on clean, file not found
Just starting out with c++ on Windows, I has a fresh install of WinGW just minutes ago and made sure to add it to path and all of that. I'm using the following Makefile main.exe: main.o g++ main.o -o main.exe main.o: main.cpp g++ -c main.cpp clean: rm *.o, main.exe when I run (doing this with powershell,...
Instead of rm *.o, main.exe use del *.o main.exe Thank you @JohnBollinger and @MathiasR.Jessen for the help in the comments. For commands in Makefile use cmd commands and executables only :)
63,474,548
63,474,984
GLIBC 2.7 version required. Compile C++ code with later GLIBC version while supporting earlier glibc
I have two machines, RHEL 4 machine RHEL 6 machine Now I have a code that I can compile on RHEL4 machine and then run the executable on both machines. But if I compile the same code on RHEL6 machine, I cannot run the executable on RHEL4 machine. It throws an error "GLIBC 2.7 version required". Now my quesiton is, GLI...
Let's confirm the default glibc versions on RHEL. From distrowatch for RHEL: RHEL 4 has glibc 2.3.4 RHEL 6 has glibc 2.12 I cannot run the executable on RHEL4 machine. It throws an error "GLIBC 2.7 version required". There are newer symbol versions in glibc since 2.3.4 that are in 2.12 but not in 2.3.4. So this is ...
63,474,596
63,475,301
Behaviour of explicit copy constructor
I have the following code: #include <iostream> struct A { A(int x=1, int y=1) : x(x), y(y) { } A(const A& other) : x(other.x), y(other.y) { } operator bool() const { return !x && !y; } friend std::ostream& operator<<(std::ostream& os, const A& a) { os << a.x << "," << a.y << "\n"; return os; } i...
This: A aa = A10x10; Performs copy initialization. Copy initialization works by converting the object to the type of the object being initialized. However, copy initialization does this by implicit conversion. And implicit conversion cannot call an explicit constructor. Even if it's the copy constructor. Now by all ...
63,474,630
63,477,566
Error cannot convert 'float*' to 'float' in return
I'm new in C++ and I'm trying to learn about the arrays' behavior in functions. It's an attempt of matrix-vector multiplication. #include <stdio.h> #define N 4 float Gi[N][N] = {{ 0.0, 0.0, 0.0, 1.0}, { 0.0, 2.57142857, 3.42857143, 1.28571429}, {-0.0, 3.4...
Arrays are not first-class citizens. As such they are not returnable by value. You will have to make use of a struct wrapper as such: struct matrix_t { float data[16]; };
63,474,785
63,486,692
How to debug an Android stack trace with __cxa_rethrow
I am building an Android app which in the latest version has a lot of crash reports like the following one on google play dash. It consists of several libraries cross compiled with android-ndk. Starting from frame #05 it halfway makes sense to me. What I wonder is how to go for the other half and what to make from the ...
After having received feedback from a user about how exactly to reproduce this crash, it was possible to resolve this with the confidence of a positive test. As assumed, it was a different exception raised by another library which was called from within transformInPlace(). Adding the following line fixed the crash and ...
63,474,929
63,475,017
Opengl triangle not drawn
I'm trying to draw a simple triangle on the screen. The window gets properly set up and everything seems okay to the point, where I'm trying to actually draw stuff. I have the following code, but it doesn't work for some reason. default_shader_program is program linking shaders shown after the function code void window...
Your array contains 9 elements instead of 12, but that doesn't cause the issue. The 2nd argument of glBufferData is the buffer size in bytes. Hence the size of the buffer is 9*sizeof(GLfloat) rather than 12: glBufferData(GL_ARRAY_BUFFER, 12, data, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, 9 * sizeof(GLfloat), data...
63,475,058
63,475,192
Strange behavior with constexpr interacting with const references
I tested the following code with both clang and gcc (trunk versions). Can someone explain why the case with the plain X struct does not work, while both the by value capture and the wrapper case that uses const reference work just fine. struct X { constexpr X(const int &v) : x(v) {} constexpr int Get() const { retu...
The rule you're violating here: constexpr X a(x); Is that a consetxpr pointer or a constexpr reference has to refer to an object with static storage duration - that's the only way for its address to itself be a constant expression. That is not the case with x. But once you make it so (the const was redundant): static ...
63,475,072
63,475,201
Can I separate the 2 types of syntax that call copy constructors into 2 different methods?
Since a copy constructor can be invoked by constructing with another object of the same type as the argument or by assignment, I was wondering if was possible to separate the two. I tried making 2 variations (where the only difference was the line of code used to copy the object) and generating assembly for both, but t...
Yes, in your particular example, you can distinguish between the 2 versions like this: class Thing { public: Thing() { } explicit Thing(Thing& from) { std::cout << "Constructor One\n"; } Thing(Thing const&) { std::cout << "Constructor Two\n"; } }; and now the initializations wil...
63,475,452
63,488,509
Member Function Pointer Template Substitution Fails
I have the following code: class A{ public: A() {} void foo(const B& b) { int a = b.a(); } }; template<class T, typename ... ARGS> std::function<void()> * invoke(T *t, void(T::* fn)(ARGS...), ARGS... args) { //Create a new std::function on the heap to be executed later std::function<void()>...
I figured out a solution that works for me based upon everyone's answers and comments. In my application, I need to ensure that one, and only one, copy of the arguments to the function being invoked is made because that function will be executed within a different thread at a different time and the original data might ...
63,475,631
63,475,647
Why am i getting exremely large numbers when adding elements of an array in c++?
I was trying to add the first 4 numbers of my array. When I test it I always get the number "4201077" even though the first numbers 4 numbers are 1 2 3 and 4. When I try with different numbers starting, I get a slightly different variation such as "4201092". What am I doing wrong? code: int main(){ int a [10]; in...
You never initialize count to hold any value. The line count += a[i]; reads from count in order to add a[i] to that value. In C++, reading from an uninitialized variable is undefined behavior in most cases, including this one. Therefore, your program might do anything at all, including (but not limited to) printing ...
63,475,796
63,476,039
Marshal.Sizeof() returning unexpected value
I'm debugging code in C# written by a 3rd party. The project is an old C++ project that was rewritten in C# by a contractor, and I have no access to the contractor. I authored the original C++ version. The issue is when the C# code gets the size of a structure that represents data received over a UDP connection. The st...
Add this to the structure: [StructLayout(LayoutKind.Sequential, Pack = 1)] internal class PROXY_HDR { public ushort pad; public ushort label; public byte flags; public ushort length; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4, ArraySubType = UnmanagedType.U1)] public byte[] ip; ...
63,475,839
63,475,997
C++ "periodic" iterator over the custom container
I have a class that contains the vector of elements of the specific class. The main idea is to generate periodic sequence of the elements, based on the one period of the sequence (elems_) and the number of the periods (nperiod_) so I do not need to store all elements, but just one period. class PeriodicContainer { priv...
If your underlying container is simply a std::vector, then you know that it's a contiguous container -- which actually makes this quite easy. You can form an iterator from the following: A pointer (or reference) to the container being iterated, and The current iteration count (note: not 'index'). This will be used as ...
63,476,282
63,479,480
Is there a way of changing the style of a Windows 10 win32 / gdi++ GUI program into Windows 95?
Windows 95 theme: Windows 10 theme: The Windows 95 theme look would be absolutely perfect for my program. Is there a way to do this using the Win32 API and GDI+ which the program is written in?
You can use SetWindowTheme function Include <Uxtheme.h> Add dependency to uxtheme.lib in Properties->Linker->Input->Additional Dependencies. Call SetWindowTheme(hwnd, L" ", L" "); after you create the window. Here is the sample: #include <windows.h> #include <Uxtheme.h> LPCWSTR g_szClassName = L"myWindowClass"; LRES...
63,476,350
63,476,425
Does LLVM (Clang) ever use GCC?
There are "sayings" on the web that LLVM (Clang) is built with GCC compatibility in mind and that it uses many of GCC's tools to compile code. However that does not make sense; isn't Clang a more advanced replacement for GCC? So straight to the point, does Clang use GCC at all? Are they related?
Depending on how it is configured, clang can use gcc components, e.g: to retain compatibility. Clang, just like gcc, is a compiler, and a compiler frontend. Strictly speaking, a C++ compiler does not link code, the linker does it. Clang can use either gnu ld, gold, lld or others. Those are all linkers, some part of the...
63,476,352
63,476,385
sum is 1 irrespective of numbers
having cal_sum in the last cout statement gives 1 as output irrespective of the values entered. when x+y is entered in place of cal_sum in cout statement then I m getting the correct answer .why? #include<iostream> using namespace std; //sum of 2 numbers. int cal_sum(int a,int b) { int sum; sum=a+b; r...
You are printing cal_sum itself, when you should be printing cal_sum(x, y): #include <iostream> //sum of 2 numbers. int cal_sum(int a,int b) { return a + b; } int main() { int x,y; std::cout << "enetr any 2 no\n"; std::cin >> x; std::cin >> y; std::cout << "sum =" << cal_sum(x,y); } You might...
63,476,535
63,476,599
How can we generate some amount of random numbers and link them to each other without getting a number linked to itself?
I am writing a program where I need to shuffle a list of persons and link them to another person from the list. But the problem is with odd numbers, because 1 person can be linked to themself. (I made that impossible so then nothing happens.) For example, if there are 3 persons called 'Bill', 'John' and 'Jonas'. If 'Bi...
This is essentially a "secret santa" problem. There is a simple algorithm for this: Shuffle the list of people randomly. For each person (except the last), link them to the next person in the list. Link the last person to the first. This is guaranteed to be a random linking, and guarantees that no person is linked to...
63,476,613
63,477,415
Is it possible to use "cin" while referring to a pointer in structure?
This code is showing an error at the cin statement. Why is this? Here is the error: no match for 'operator>>' (operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'int*') #include<bits/stdc++.h> using namespace std; struct go { int size, *p; } r; int main() { int sum = 0; r.size = 10; ...
std::istream does not have an operator>> to read an int* pointer. That is exactly what the error message is saying. What you are really trying to do is read into the individual int elements of the array that you are allocating. That means you need to deference the int* pointer so you can use the operator>> that reads...
63,476,703
63,476,907
Can std::exception_ptr copy constructor throw?
It seems to me that standard allows std::exception_ptr to not use ref-counting (i.e. std::exception_ptr cctor can be making a copy of exception object it points to). Which would mean following code may never call handle_eptr() and exception can escape main() with related consequences: #include <iostream> #include <stri...
Can std::exception_ptr copy constructor throw? No. Standard says (latest draft): [propagation] exception_­ptr meets the requirements of Cpp17NullablePointer [nullablepointer.requirements] No operation which is part of the Cpp17NullablePointer requirements shall exit via an exception.
63,477,077
63,477,281
What does the number represent when printing a socket in C++?
SOCKET sampleSocket; cout << sampleSocket << endl; // End up with a number I noticed that when I use cout to print a socket, I receive a number--what does that number represent and how can I retrieve it outside of using cout?
In Winsock applications, a socket descriptor is not a file descriptor and must be used with the Winsock functions. [...] Because the SOCKET type is unsigned, compiling existing source code from, for example, a UNIX environment may lead to compiler warnings about signed/unsigned data type mismatches. (See Socket Data ...
63,477,123
63,477,216
Why non const reference cannot be initialized to an object of different type?
I was reading this book and it is written that We can assign const reference of one type to an object of any other type, and the reason was given that, internally compiler assign the Rvalue to the object of the same type as reference and then const reference is initialized to that object of same type, But, if this type...
If the compiler has to perform an implicit conversion from one type to another, that means it has to create a temporary to hold the converted value. A non-const reference cannot bind to a temporary. Period. A const reference can, and it will extend the lifetime of the temporary. In other words: #include <iostream> usi...
63,477,481
63,477,950
(SFML, C++) How to access specific sf::Vertex in dynamically allocated sf::VertexArray?
I am new to SFML, learning it in C++ and I have this problem which I can't solve. What my program (class) contains is: in header file: sf::VertexArray *hitbox; in source file: this->hitbox = new sf::VertexArray(sf::TriangleFan, 20); //example and there's a method void Object::setPosition(sf::Vector2f position) { ...
Since this->hitbox is a pointer to a sf::VertexArray, you need to dereference it before using the operator[]: (*(this->hitbox))[0].position = position; It would probably be better to not use a pointer here at all.
63,477,616
63,477,737
What is "packet type ID"?
In linxu/if_ether.h I found this struct: struct ethhdr { unsigned char h_dest[ETH_ALEN]; /* destination eth addr */ unsigned char h_source[ETH_ALEN]; /* source ether addr */ __be16 h_proto; /* packet type ID field */ } __attribute__((packed)); What is "packet type ID field" for? I ...
It's the type of an Ethernet frame in big endian. Example values Related question
63,477,752
63,532,468
Compile-time: count #(~N) of members of type X and define a member array[N]?
Is there a way to count number of members in struct (ints in the below example) at compile time and define an array of same size in the same struct? Using a MACRO or a templated struct instead of the int type would be OK. struct A { int myInts[numInts()]; // here numInts() == 2 int a; char b; char c; ...
This can be approched using MAP-MACRO and some templates. You need to define your structs using a macro and pass all fields to it(eg. DEFINE_STRUCT(A, int a, char b, ...)). The number of int(or another type you want) fields can be counted by applying recursive template on a helper function of type void(int a, char b, ....
63,477,872
63,487,464
How to write N bits to QByteArray
I have a task to decode an RTP packet and extract the payload of this packet (audio data). In order to bypass all the RTP header fields, I have this function: quint32 readNBitsByRange(quint32 position, quint32 count, const QByteArray &array) { quint32 accuml = 0; while (count != 0) { const quint32 ...
After experimenting a bit, I found a more correct way to write the RTP packet in QByteArray and realized my previous errors. Therefore, I wrote a sample version of the correct RTP packet entry in QByteArray: class RtpHeader { public: quint16 m_vp:0x02; quint16 m_pf:0x01; quint16 m_xf:0x01; quint16 m_c...
63,478,034
68,367,962
Why is value-initialization specified as not calling trivial default constructors?
To value-initialize an object of type T means: ... — if T is a (possibly cv-qualified) class type without a user-provided or deleted default constructor, then the object is zero-initialized and the semantic constraints for default-initialization are checked, and if T has a non-trivial default constructor, the object i...
I haven't been able to track down an authoritative answer to my question. However, looking at the C++03 standard and the CWG issues list, I have a rough idea. Let's review value-initialization in C++03. It is defined for a type T as follows: If T is a class type with a user-declared constructor, then the default const...
63,478,258
63,479,621
How to pass a test fixture to a helper function in C++ GTest
I have a protected static method in my test fixture I wish to call from a helper function, instead of from the unit test function itself. class Fixture { ... protected: static void fixture_func( int foo ); }; void helper_func( int bar ) { Fixture::fixture_func( bar ); } TEST_F( Fixture, example_test ) { fix...
You cannot call protected nor private methods from outside of a class, no matter if that method is static or if the calling function is C-style one. In any case, you would need the class scope Fixture:: before fixture_func: void helper_func( int bar ) { Fixture::fixture_func( bar ); } You need to make fixture_func b...
63,478,420
63,487,162
Why does the console asks for more inputs? C++
I am trying to make a program where I calculate fees based on the ride type and time the user rented stuff. I came up with the method of how to do it, but when I try to read input the console keeps asking for more input. double computeFee(){ double fee, hour_rate, minute_rate; char ride_type, colon; int hou...
Each time you call computeFee(), the function code is executed. In your code, you call it twice, so it will ask you for the input two times. And given that the first time you call it you don't assign it, the first input will be lost. To make it work the way you want, your main code should be: int main(){ double fee...
63,478,645
63,479,051
catch all signal equivalent to catch all segment fault?
I'm wondering if there is a way to catch all segment fault/core dump, and print its callstack? Catching all signals look like a doable way, but I'm not pretty sure how it works, according to some of my experience, it did not always give the outcome I want, sometimes it just failed to catch that core dump, maybe I did s...
I'm wondering if there is a way to catch all segment fault ... Certainly. This can be achieved by registering a signal handler using std::signal. ... and print its callstack? This is a quite a lot trickier. There is no standard way to inspect that call stack in C++. Linux has several ways, but unfortunately the mos...
63,478,685
63,583,486
How to give blank data for Oboe library to play as sound?
Sometimes I want my audio output in Oboe to play nothing, but I dont want it to stop, I just want it to be silent while no data arrives. I tried: static void writeBlankData(float* pointer, int numFrames) { std::fill_n(pointer, numFrames, 0); } oboe::DataCallbackResult PlayRecordingCallback::onAudioReady( ob...
The most likely cause is that the stream is in stereo so has 2 samples per frame. Your current code assumes a mono stream. Try changing: writeBlankData(floatData, numFrames); To: writeBlankData(floatData, numFrames * audioStream->getChannelCount());
63,478,686
63,483,041
Using SFINAE to check whether function is constexpr or not
I want to check whether a function can be evaluated during compilation. I found this, but I don't understand the concept completely. I have a few doubts: What is the role of the following line in the code? template<int Value = Trait::f()> Every time when I need to check whether the function is compile-time evaluable,...
Here is just a quick example of what you can get with std::void_t to tackle your point 2 that can be generic in some way... #include <iostream> #include <type_traits> int f() { return 666; } constexpr int cf(int, double) { return 999; } template <auto F> struct indirection { }; template<typename F, class = ...
63,478,695
63,491,332
How can I generate random multiprecision ints of different bits using boost?
I need to generate a large number of random multiprecision ints (boost mpx_int) of various bits. My current approach is based on these two examples: boost multiprecision random, constexpr array. To generate a random number this way I need the number of bits as a constexpr. I can generate an array of constexpr ints, but...
I was able to accomplish this by fixing the independent_bits_engine to the largest amount of bits needed and then masking to the number of bits required. Example: #include <boost/multiprecision/cpp_int.hpp> #include <boost/random.hpp> #include <iostream> using namespace std; using namespace boost::multiprecision; usin...
63,479,248
63,491,089
How to use WM_MOUSEMOVE LParam value outside of WndProc in a separate translation unit?
Maybe this is just a code organization issue, maybe there is some extremely fundamental C++ knowledge that I am lacking -- I have tried for hours to arrive at a reasonable solution, and nothing appears to work, so I am turning to the internet. I am writing a Direct2D application for game development, and I am trying to...
Here are some possible ways to accomplish this. GetCursorPos() This is very simple, and returns the screen coordinates of the cursor, not the coordinates within a window. This could be (un)desirable based on the application you're making. You can use ScreenToClient() to convert these coordinates to window coordinates...
63,479,765
63,533,809
What's the best way of checking whether a torch::Tensor is empty?
I'm currently using the has_storage() method to check whether a tensor is empty or not, but I wonder if there is anything better other than this! and whether there are any implications involved in using this other than the fact that an initialized torch::Tensor always has a storage while an empty one doesn't!
After some digging, it turns out that the best solution for this is to use .numel() method which returns the number of elements a tensor has. In summary: To know whether a tensor is allocated (type and storage), use defined(). To know whether an allocated tensor has zero elements, use numel() To know whether a tensor ...
63,479,773
63,480,335
How to rename a protobuf msg? typedef like C/C++?
I defined the following protobuf message A and B: message A { optional int32 err_code = 1; optional string err_msg = 2; } message B { optional int32 err_code = 1; optional string err_msg = 2; } Can I directly use B as an alias for A? If I can't do it, how to gracefully copy an A message instance to a B...
There're 3 ways to do that: Copy field by field from A to B: a.err_code = b.err_code; *(a.mutable_err_msg()) = b.err_msg(); The code is tedious. Use reflection to copy fields in a loop without explicitly assign one field to another. You need to learn about reflection mechanism. You can serialize A to a string, and d...
63,480,110
63,480,423
Storing and writing vector to queue c++
#include <iostream> #include <queue> #include <thread> #include <process.h> #include <windows.h> #include <stdlib.h> int g_Width = 100; std::queue<std::vector<unsigned short>> BufferQueue; bool dataRead = false; unsigned short* g_pImgBuf = NULL; unsigned int _stdcall Write(void* arg) { std::vector<unsigned ...
You simply cannot do this in such a simplistic way. If you want one thread to pick messages off the queue that are being written by another thread you need mtuexes and condition variables. This is not a trivial task. I suggest a lot of googling. I will look too and updat here if I find a good link https://juanchopanzac...
63,480,159
63,480,251
Use reference to initialize class members
I always have the impression that I shouldn't use reference to initialize class member because I don't know the lifetime of the reference and If the reference value changes outside the class, the corresponding class member would also change to the new value. But after testing the following code, I am confused... clas...
Your Test(int& i) :m_i(i) invokes a copy constructor, and since your field is an int, not an int&, test 1 and 1.1 always print the original 10. In Test 3.1, there is no requirement that accessing memory that has been freed/deleted with yields garbage. (There are debugging compilers that deliberately put a distinct patt...
63,480,195
63,480,372
C++ getline() is only reading the last line in a text file
I am trying to read a text file and output every line but it only outputs the last line. How do I output every line? My code: int main() { std::ifstream ReadFile("example.txt"); std::string line; if (ReadFile.is_open()) { while (std::getline(ReadFile, line)); { std::cout << l...
You have a semicolon after the while loop which means it will keep iterating and do nothing as you have an empty statement (; means empty statement). This is why you got the last line as line was filled with the last line of your file in the last(3rd) iteration. while (std::getline(ReadFile, line)); Update your while ...
63,481,445
63,482,203
Why specifying std::ios::in for ifstream?
I want to use ifstream to load a font file into the memory and give it to FreeType. I find the standard I/O facilities a little discouraging. For now my question is why I have to specify std::ios::in for ifstream? The name ifstream already implies input operations, so why do we need this needless confusing things? Can ...
For now my question is why I have to specify std::ios::in for ifstream? You don't. It will always append the corresponding flag by the bitwise OR operation. The documentation explicitly states that: First, performs the same steps as the default constructor, then associates the stream with a file by calling rdbuf()->...
63,481,584
63,481,669
C++ search for a node in an ordered linked list
Hi I have an ordered linked list using structs. The struct has two elements: string name and int id. I am trying to search for a specific node so I can then print it but I keep getting the "Core Dump (Segmentation fault)" error when I try to run the code. /* * search: Auxiliary function that searches for a specific n...
I see one problem straight away (though there may be others). Your search function will return NULL if the item cannot be found, yet you blindly go and check if resp->id == c - that's unlikely to end well. You can fix that reasonably easily, you just have to adjust your check in showNode(): // Find a node and return it...
63,482,069
63,482,208
Simplest way to remove first part of a string if it matches (from beginning) ? (using boost is ok)
std::string str_a = "Hello World"; std::string str_b = "Hello "; If string matches from beginning, remove it or return it in a new string with result, doesn't matter. Result should then be "World". Whats the most stupid and simplest way to this with c++ ? One liner is preferred. Performance is NOT a concern. std is pr...
#include <iostream> #include <string> int main() { std::string a = "Hello World"; std::string b = "Hello "; if (a.find(b) == 0) { std::cout << "\"" << a.substr(b.length()) << "\"\n"; } return 0; }
63,482,070
63,482,286
How can I code something like a switch for std::variant?
I have some var = std::variant<std::monostate, a, b, c> when a, b, c is some types. How, at runtime, do I check what type var contains? In the official documentation I found information that if var contains a type and I write std::get<b>(var) I get an exception. So I thought about this solution: try { std::variant<a>...
The most simple way is to switch based on the current std::variant::index(). This approach requires your types (std::monostate, A, B, C) to always stay in the same order. // I omitted C to keep the example simpler, the principle is the same using my_variant = std::variant<std::monostate, A, B>; void foo(my_variant &v...
63,482,123
63,482,901
Why virtual inheritance cause pointer offset?
I know that multiple inheritance and virtual functions cause a pointer offset when casting the derived class pointer to base class pointer due to memory layout. However I cannot figure out why virtual inheritance can also cause this effect? What I only know about virtual inheritance is to prevent multiple instances of ...
The following code #include <inttypes.h> #include <stdio.h> #include <stdint.h> struct Base { long a; }; struct Derived : virtual public Base { long b; }; int main() { Derived object; intptr_t reference = (intptr_t)&object; printf("Base offset: %" PRIdPTR "\n", (intptr_t)(Base*)&object - reference); prin...
63,482,300
63,482,458
How to reload .bash_profile in Linux with C++ program?
I used system("source ~/.bash_profile") to reload it, but it does not work. Is there any other function or code to reload the bash with C++ program in linux?
The command source ~/.bash_profile works, if you're actually in the process running the bash shell you want to affect. When you started your C++ program, that started up in a different process, a child of the bash process, and therefore unable to modify the environment of that bash process. And, in fact, it's even wors...
63,482,915
63,483,004
What is the function in type_traits to check if the type is const char*?
I need to make a template function myPrintf that checks if the types are good with %d %f %s in given string. I have found these two std::is_integral_v<T> std::is_floating_point<T> but I don't know how to check if the given argument is const char* Does anybody know? Thanks
You can check whether types match exactly using std::is_same_v. For example: template <typename T> void foo(const T &t) { if constexpr (std::is_same_v<const char*, T>) { // do something here } } Note: std::is_same<A, B>::value is equivalent to std::is_same_v<A, B>
63,483,022
63,485,801
Visibility of a variable across threads in c++
Given the following code, Is it guaranteed to see the latest value 4 of a ? int a; mutex mtx; void f() { unique_lock<mutex> lck(mtx); // read(a); // is it guarantee it will see the value 4? } int main() { a = 4; thread(f); }
Yes, it is guaranteed: 32.4.2.2 Constructors [thread.thread.constr] Synchronization: The completion of the invocation of the constructor synchronizes with the beginning of the invocation of the copy of f. In other words, the construction of std::thread itself, which occurs in the original execution thread, s...
63,483,309
63,484,744
C++ data type greater than 64 bits
I'm trying to write an RSA implementation and need to work with numbers that are 100 bits and larger. Are there any C++ data types that can allow for this?
If by "C++ data type" you mean "primitive integral type guaranteed by the standard", then no. If by "C++ data type" you mean "primitive integral type that actually exists on my platform", then maybe, but you'd have to tell us what your platform is, and you haven't. If by "C++ data type" you mean "any type usable in C++...
63,483,551
63,483,692
Invoking the correct instance of an overloaded function template when passing derived classes
Let's say I have a class template template <class Ta> struct Base {}; And I've written some overloaded function templates around it: template <class T1, class T2> void f(Base<T1>&, T2){ std::cout << "1" << std::endl; } template <class T1, class T2> void f(Base<T1>&, Base<T2>&){ std::cout << "2" << std::endl; }...
You might use SFINAE to restrict one overload: As your Base is template, require custom traits (else std::is_base_of might be used): template <template <typename> class C, typename T> std::true_type is_template_base_of_impl(const C<T>*); template <template <typename> class C> std::false_type is_template_base_of_impl(....
63,484,121
64,284,502
libclang: how to get compiler macro definitions
With clang LibTooling API one can get a list of compiler predefines simply using clang::Preprocessor::getPredefines(), but I cannot find any equivalent in libclang API. Is it possible to get a list of compiler predefines with libclang API?
I could list all predefines using the fact that they are present in the beginning of a translation unit. So after parsing I just listed all top-level cursors of CursorKind.MACRO_DEFINITION that are not in any real location (cursor.location.file is None using python bindings API)
63,484,184
63,484,327
Why is the vector subscript out of range?
I'm trying to code this really simple addition program for practice. It takes in a list of inputs and stores it in a vector. Then it grabs each consecutive element out of the vector and sums it up. #include <iostream> #include <vector> int main() { std::vector<int> i; int input; int sum = 0; int y = 0...
If you want to loop through the vector, you need to check how many elements it has using i.size(): for (y; y < i.size(); y++) { sum = sum + i[y]; } This is the canonical use case for range-based for-loops: for(const auto& elem : i) sum += elem; Or better still use the STL algorithms: #include <numeric> cons...
63,484,474
63,484,731
Python version of c++ pointer to member?
Consider this C++ code: class TestClass{ public: int memberA = 0; int memberB = 0; }; void doSomethingToMember(int TestClass::* memberPointer, std::vector<TestClass> objects){ for(int i = 0; i < objects.size(); i++) (objects[i].*memberPointer)++; } We have a function that accepts multiple objects and we ...
To do the same in Python, you could use the getattr and setattr functions with member name instead of a member pointer: def do_something_to_member(member_name, objects): for object in objects: member_value = getattr(object, member_name) setattr(object, member_name, member_value + 1)
63,484,570
63,484,893
hidden friend in a class template name clashes with another symbol in inline namespace
I'd like to provide a hidden friend for my type, and at the same time there is another object with the same name in an inline namespace. Everything works fine with normal types. But if I have a template, the compiler errors when I instantiate the template redefinition of 'cpo' as different kind of symbol Here is the c...
Your code is well-formed. This is Clang Bug 37556. Compiling this well-formed program with -std=c++2a: namespace X { inline namespace Y { int swap; } template<class> struct S { friend void swap(S&, S&) {} }; } int main() { X::S<int> s1, s2; swap(s1, s2); } produces diagnostics (https...
63,484,825
63,487,502
Function taking pointer-to-method regardless of constness
I want to implement a generic function that will take reference to object and pointer to its member function and invoke it. However I'm not able to do so when my class has both const and non-const methods as I need to provide two overloads: template<typename Ret, typename Class, typename ...Us> Ret callMethod(Class &ob...
Here's a C++14 alternative without using std::function. what I want to ultimately achieve is pass a 3rd parameter, a data buffer from which method arguments will be extracted - hence the template function to handle it as generically as possible What you use at the call site will be perfectly forwarded here: template<...
63,485,690
63,486,209
Below is the code for subset sum problem in gfg. Please tell me what is wrong in it
#include<iostream> #include<bits/stdc++.h> using namespace std; #define ll long long bool check(int a[], int n, int s) { bool dp[n+1][s+1]; for(int i=0;i<n+1;i++) { for(int j=0;j<s+1;j++) { if(i==0) dp[i][j] = false; if(j==0) dp[i][j] =...
#include<iostream> #include<bits/stdc++.h> using namespace std; #define ll long long bool check(int a[], int n, int s) { bool dp[n+1][s+1]; for(int i=0;i<n+1;i++) { for(int j=0;j<s+1;j++) { if(i==0) dp[i][j] = false; else if(j==0) dp[i]...
63,485,746
63,485,848
C++ error when instantiating a vector of int arrays (vector<array<int, 3>>)
I am new to C++, so this is probably just a simple mistake, but when I try to create a vector of integer arrays, for example vector <array<int, 3>> triangles = ({0, 1, 2}, {3, 4, 12});, I get this error: error: expected ';' before '}' token vector <array<int, 3>> triangles = ({0, 1, 2}, {3, 4, 12}); ...
Your syntax is incorrect, hence the error. Try the following: int main() { vector<array<int, 3>> triangles {{1,2,3},{2,3,4}}; //cout << triangles; for (const auto& triangle : triangles) for (const auto i : triangle) cout << i << '\n'; return 0; }; Moreover, you can not directly ou...
63,486,019
63,486,063
C4512 assignment operator could not be generated
I'm working on updating an old C++ application, it is being compiled with MSVC 2013, not the latest I know. I'm getting a warning: 1>c:\fraenkelsoftware-millikan\shared\debug\debughelper.h(84): warning C4512: 'HowLong' : assignment operator could not be generated 1> c:\fraenkelsoftware-millikan\shared\debug\de...
The class has constant private data members const boost::posix_time::ptime m_start; ///< Start time const std::string m_str; ///< Duration of what we are trying to measure const IDebug::Severity m_sev; You may not reassign constant objects. So the compiler issues a message that it is unable to generate ...
63,487,157
63,487,368
Is there a way to know which signal triggered slot in Qt?
Assume that i have two signals (void signal1() and void signal2()) and one slot (void slot()). Both signals are connected to the slot: connect(this, &Classname::signal1, this, &Classname::slot); connect(this, &Classname::signal2, this, &Classname::slot); In implementation of the slot(), is there a way to know which si...
You could go through lambdas that provide the extra info... connect(this, &Classname::signal1, this, [source = 1, this]() { slot(source); }); connect(this, &Classname::signal2, this, [source = 2, this]() { slot(source); }); (The above assumes your...
63,487,417
63,487,839
shared_ptr to derived class
I am fairly new to C++ and I am still learning to write clean code. Below are excerpts from the current legacy code I have. class A { public: setDataManager(dm) { _dm = dm; } void recieveData(data) { _dm.processData(data); } private: std::shared_ptr<DataManager> _dm; }; cl...
You can create a shared pointer to a derived class and assign it to a shared pointer to a base class. That seems to be the only piece you are missing. https://godbolt.org/z/Gf7fb1 #include <memory> class Base { public: virtual int Foo(); }; class Derived:public Base { public: virtual int F...
63,487,530
63,488,186
error: cast from ‘uint8_t* {aka unsigned char*}’ to ‘unsigned int’ loses precision [-fpermissive]
I want to print addresses of member elements of a structure variable. When i try to compile this program it gives me error (error: cast from ‘uint8_t* {aka unsigned char*}’ to ‘unsigned int’ loses precision [-fpermissive]).I am using https://www.onlinegdb.com/online_c++_compiler. Note: i am using unsigned(ptr) otherwi...
Using the online-compiler you provided and changing this line cout<<hex<<unsigned(ptr)<<endl; to cout << hex << (uintptr_t) ptr << std::endl; prints the addresses. When checking the size of these datatypes using: std::cout << "sizeof(uintptr_t) = " << sizeof(uintptr_t) << std::endl; std::cout << "sizeof(unsigned int)...
63,487,748
63,557,296
How to get mongocxx gridfs id in format "bsoncxx::v_noabi::types::bson_value::view"
I am working with mongocxx 3.6.0 driver, I try to store and receive bytes from gridfs. I am able to run the example code in https://github.com/mongodb/mongo-cxx-driver/blob/releases/stable/examples/mongocxx/gridfs.cpp, but I want to search and get suitable file. When I examine the documentation http://mongocxx.org/api/...
I found the answer for(auto doc : cursor) { std::cout << bsoncxx::to_json(doc) << "\n"; bsoncxx::types::bson_value::view id = doc["_id"].get_value();
63,487,817
63,487,902
Trying to compile a cpp file but command prompt saying file not found
I have downloaded the c++ compiler from MinGW also set the environment variables
'<' and '>' are research characters for redirection and are not to be used in file names. most likely in this case it is trying to read input from hello_world as it would be seeing < hello_world but not find the file The > p.cpp would be attempting to write any output to p.cpp, so may have replaced what you had in tha...
63,488,703
63,489,136
C++: cast array/vector integer element to constexpr
I couldn't really find a solution online anywhere for this. I am a bit of a dinosaur from before C++11 and I couldn't figure out typecasting a constexpr. Does anyone know how to convert a C-style array and/or a std::vector (integer) element into a constexpr? That is to say, let's say int a[]={1,2}; vector<int> v={1,2};...
Suggestion: if you can use at least C++14, instead of std::vector, if you can, use a std::array Declaring it constexpr #include <array> int main () { constexpr std::array<int, 2u> a {1, 2}; constexpr auto b = a[1]; } std::array is a type compatible with constexpr and so it's operator[]() (const version), or...
63,489,528
63,490,123
Issue with Modular Exponentiation C++
I'm trying to perform Modular Exponentiation for large values (upto 64-bits) and I wrote this function for it: uint64_t modularExp(uint64_t num, uint64_t exp, uint64_t mod) { string expBits = bitset<64>(exp).to_string(); expBits = expBits.substr(expBits.find("1")+1); string operations = ""; ...
First of all, some general advice: It's better not to use strings when working with integers, as operations with strings are much slower and might become a bottleneck for performance. It's also less clear what is actually being done when strings are involved. You shouldn't use std::pow with integers, because it operat...
63,489,657
63,490,992
Convert a string of characters string words[] to double feature[] in c++
I read strings from a text file in my c++ script, those strings saved in string words[3] are in this form : abc[1] abc[2] abc[3]*abc[2] After reading those strings I want to convert string words[3] to double feature[3] in order to be able to replace those strings with the values of double abc[3] = {1,2,3}. So I want t...
What I meant in my comment is something like this. Playground Note that I omit the hardest part, which is parsing an arbitrary expression into basic operations. #include <iostream> #include <string> #include <map> #include <string_view> #include <algorithm> double abc[] { /*0*/ 5.0, /*1*/ 2.0, /*2*/ 3.0, /*...