question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
68,306,977
68,307,165
How can I deprecate a C++ header?
I would like to deprecate a C++ header so that if someone includes it in their code, the compiler issues a warning. I know that I can deprecate individual symbols, for example, using C++14 [[deprecated]], but is there a similar thing for headers? Maybe some clever trick? Note that I want the compiler to issue a warning...
Here is a possible (albeit perhaps not too elegant) solution. Insert in the header a code like that // badheader.hpp namespace { [[deprecated("This header is deprecated")]] constexpr static int badheader_hpp_is_deprecated = 0; constexpr static int please_dont_use_badheader_hpp = badheader_hpp_is_deprecated; } This cre...
68,307,098
68,307,329
What's happening when gdb sets multiple breakpoints on the same symbol at different addresses?
What's happening when I set my breakpoint on a symbol like: b Lock::acquire, but gdb shows multiple address for the same symbol? 1.1 y 0x000000000184b1df in Lock::acquire(bool) at lock.cpp:332 1.2 y 0x00007fa92b96099f in Lock::acquire(bool) at lock.cpp:332 1.3 ...
Inlined functions can appear inside other functions, at various addresses.
68,307,551
68,307,614
C++ outputs garbage values sometimes
I am trying to create a game like a simple PapersPlease but when my program outputs a random name from my array it outputs a garbage value (�) and I'm not sure on how to fix this issue: #include <iostream> #include <ctime> #include <cstdlib> using namespace std; int random_number; string RandomName; string names[12]...
RandomName = names[random_number - 1]; if random_number is equal to 0 then random_number - 1 will be equal to -1, which is out of range of the array. Make sure to always be inside of 0 and 11 (size of the array - 1)
68,308,022
68,308,068
auto with ternary operator and nullptr
Can I use auto with such usage of the ternary operator? auto obj = some_cond ? static_cast<className*>(baseClassObj) : nullptr; It compiles in Visual Studio, and the code works OK, but can there be any unexpected side effects? Or, will auto here always be className* and I can relax and write such code? Or, with the te...
auto deduces to the type of the value that is assigned to it. The ternary operator can only return one type. nullptr is implicitly convertible to any pointer type, but no pointer type is implicitly convertible to std::nullptr_t, so in this example the ternary operator must always return className*, and thus auto will...
68,308,773
68,308,803
Why does leetcode accept code which wouldnt usually be ran in an IDE?
Okay so the following class was accepted and ran in the Two sum problem in leetcode: class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> arr(2); for(int i = 0; i < nums.size(); i++){ for(int j = i+1; j < nums.size(); j++){ if(nums[i]...
Well, if the signature of twoSum has a vector<int>& parameter, you're not allowed to call twoSum with {2,7,11,15} as an argument, because that would require the creation of a temporary vector, and vector<int>& is not allowed to bind to that temporary. You would need to add const to the referenced type. This will be the...
68,308,834
68,308,910
Specifying template parameters on overloaded operator()
struct foo{ template<typename T> auto operator()(T arg) { return T{}; } } To use the operator(), I would call it like: foo()(1), which T would be deduced to int. However, if I want to specify T as something else, like long, the only way that seems to work is, which kind of defeats the reason of using operator(...
You can use the L or l suffix to specify that the integer literal 1 should be treated as a long instead of an int, eg: foo()(1L)
68,308,944
68,321,153
verify that members of c++ objects have constant address during runtime with vector example
I am trying to convince myself that objects in C++ have constant address during their lifetime. Here is a minimal working example: #include <iostream> #include <type_traits> #include <vector> class Class1 { public: Class1(unsigned int * pt); unsigned int * val_pt; }; Class1::Class...
I'm not sure what conclusions you extracted from the comments and responses above. I just wanted to make sure these were not among them: The address of a member variable is constant during runtime. If, for example, you have a vector of Class2 instances, and you resize that vector, the address of the vec_of_ints memb...
68,309,785
68,310,228
Program outputs incorrect numbers from array
Jeopardy point adding code. The program is supposed to get the number of players with a dynamic array. From there, you can enter players names and it will insert the names into a two-dimensional array. Then you can choose to call on a player to start adding points to. After looping a certain amount of times and pressin...
Technically, this is illegal: string playerList[playerNumber][2]; int points[playerNumber]; The size of the array must be known at compile time (not runtime). Though some compilers allow this as an extension to the language, it is not part of the standard language. Better choice would have been to use std::vector. Let...
68,310,825
68,310,866
if statements and relational and comparison operators: "Exceptions" When comparing three values/variables
Context Taking a c++ course and if statements and relational and comparison operators came up. I don't know enough c++ vocabulary so I apologize if this question has been asked before. I tried searching around, but I didn't find anything. Problem Below illustrates an example of what I am confused about. int n = 1; if(...
The 2 < n < 1 ain't does what you think it should: Because these operators group left-to-right, the expression a<b<c is parsed (a<b)<c, and not a<(b<c) or (a<b)&&(b<c) - cppreference.com The 2 < n part will return a Boolean value which in turn will be compared in the < 1. 2 < n < 1; // equal to (2 < n) < 1; So, in ...
68,311,667
68,311,926
Is this C++ ref example buggy?
I was checking aligned_storage in cppref, but I think its example is buggy. Here is the code: #include <iostream> #include <type_traits> #include <string> template<class T, std::size_t N> class static_vector { // properly aligned uninitialized storage for N T's typename std::aligned_storage<sizeof(T), alignof...
typename std::aligned_storage<sizeof(T), alignof(T)>::type data[N]; You seem to think that &data[i] will return the address of i-th byte in this array, while in reality it will return the address of i * sizeof(std::aligned_storage<sizeof(T), alignof(T)>)th byte, which is the same as i * sizeof(T)th byte. Example. OP:...
68,311,975
68,312,222
How to output an AVL Tree to a file in in-order traversal?
I'm writing a program that let the user insert an AVL Tree by reading from a text file then I output it in in-order traversal to another text file, this is my program: void in_order(AVLTree* root) { ofstream printToFile("output.txt"); if (root == NULL) return; in_order(root->left); printToFil...
The problem with your code may be due to the fact that in recursion you re-create ofstream printToFile("output.txt");. ofstream buffers the output, and clears it (ie outputs to a file) at the destructor which happens not in the order as you output in a file The solution to this problem can be to create this variable as...
68,312,427
68,312,532
How to print char array from index n in Arduino
Let's imagine I have String x = "hello there"; So I can print it from index e.g. 1 as: Serial.println(x.substring(1)); ello there I wanna do the same with char x[] = "hello there"; Any ideas? (Except using loops to print char by char)
You can use the & operator to get the string after the desired index like this: Serial.println(&x[1]);
68,312,568
68,312,694
Default size of an int variable, when an object is created?
class Vect { public: Vect(int n); ~Vect(); Vect(const Vect& original); private: int* data; int size; }; Vect::Vect(int n) { size = n; data = new int[n]; } Vect::~Vect() { delete [] data; } Vect::Vect(const Vect& original) { size = original.size; d...
What will be the default size of c.size ?? There is no default value except if you provide one. You should have a default constructor if you want to cover it (otherwise using uninitialized variable is undefined behaviour). For example: Vect::Vect() : data(nullptr), size(0) {} If it does not have a default value th...
68,313,012
68,313,198
Compile Assembler Source fail in msys2
When I compile a project in MSYS, An assembler source looks like: .file "a.S" .text .globl jump_fcontext .type jump_fcontext,@function .align 16 jump_fcontext: .size jump_fcontext,.-jump_fcontext .section .note.GNU-stack,"",%progbits Use command line "clang -c a.S", some error occure: a.S:4:7: error: expected absolute...
a.S:4:7: error: expected absolute expression .type jump_fcontext,@function ^ a.S:7:1: error: unknown directive .size jump_fcontext,.-jump_fcontext ^ According to the manual of (an older version of?) the GNU assembler, the .size and .type directives have a different meaning when used with the COFF file format (...
68,313,132
68,313,204
How does sprintf_s avoid buffer overflow issue
Visual Studio prompts me to replace sprintf with sprintf_s, instead of snprintf. sprintf_s does not require a length parameter, how does it avoid buffer overflow issue?
There are 2 versions. One template version which tries to deduce the size of the buffer and one where you pass the size. int sprintf_s<_Size>(char (&_Dest)[_Size], const char *_Format, ...) int sprintf_s(char * _DestBuf, size_t _SizeInBytes, const char *_Format, ...) If the first one cannot be deduced, you will have t...
68,313,138
68,313,259
Greatest common diviser of an arrray using divide conquer technique
I am trying to find the GCD/HCF of an array, I know to write the function that finds the GCD of two numbers using Euclid's algorithm. so to find the GCD of the array I thought to use this Euclid algorithm as a divide and conquer technique for GCD arrays. I'm successfully able to divide it but stuck with the merge funct...
Just find GCD of the results (GCD of array would be GCD of GCDs of left and right half of the array). ... long long leftGCD = hcf_arr(u,start,(end-start+1)/2); long long rightGCD = hcf_arr(v,(end-start+1)/2+1,end-start+1); return GCD(leftGCD, rightGCD); //Merge function } ...
68,313,637
68,316,173
Menu and toolbar disappear with wxTopLevelWindow::ShowFullScreen()
I try to display my app automatically in fullscreen. The problem is that my toolbar and menu bar disappears with the wxTopLevelWindow::ShowFullScreen() function and that whatever the option I add in. Does someone have any idea how to deal whith that ? Bellow a part of my code : MyApp.cpp #include "MyApp.h" wxIMPLEM...
ShowFullScreen has flags that determine what to hide. wxFULLSCREEN_NOMENUBAR wxFULLSCREEN_NOTOOLBAR wxFULLSCREEN_NOSTATUSBAR wxFULLSCREEN_NOBORDER wxFULLSCREEN_NOCAPTION wxFULLSCREEN_ALL (all of the above) wxFULLSCREEN_ALL is the default. So if you want the toolbar and menu bar you'll use. this->ShowFullScreen(true, w...
68,314,280
68,428,465
Container for Eigen Matrices
I am looking for a way to store matrix-like structures of sensor measurements, that are again matrices or vectors themselves. To give a more concrete example: Lets take an image, where a single pixel's RGB value can be represented as a Eigen::Vector3f. As such an entire image would become something like typedef Eigen::...
After thinking this through for some time and playing around with various approaches I ended up wrapping an Eigen::Tensor in a way that I hid one rank to the outside and returned and Eigen::Map to a particular "pixel". The basic idea looks as follows: template <Eigen::Index Rank, typename Scalar, Eigen::Index Measureme...
68,314,619
68,445,524
Mutual dependency of two objects
Quite frequently, I stuble over a situation like this: two objects need to know each other, and we have a mutual aggregation-style dependency (imagine, for example, one object handles a websocket connection, and the other handles a dbus connection, and we need to forward messages in both directions). A UML diagram woul...
When both objects run in their own thread, you could use channels (or pipes, or queues, or however you want to call them) for the communication between those two objects. You create a channel for each object and pass references to them as sending and receiving ends respectively to the objects. The objects than can list...
68,314,770
68,344,616
How do I change css styles of a gtkmm combobox?
Whenever a widget changes it's state, it is supposed to change its style. I have successfully implemented the signalizing, but I can't figure out how to change a combobox' style really. The function that changes a widget's style: { static Glib::RefPtr<Gtk::CssProvider> css{nullptr}; if(!css) { css = Gtk...
I found a solution for my problem. I assume 'padding' for comboboxes were at 0px, so i added 'padding: 2px;' in the css string.
68,314,891
68,315,051
Is "this->" always replaceable by explicit scope resolution in C++?
Many programmers like to use this-> (my feeling is that even if it is not necessary). Its advantage is obvious in class templates with base classes that depend on template parameters, and if templates has virtual functions it may be the only solution. So my question is the following: not considering dependent templates...
With name hiding, you have to use this when virtual comes into play: struct Base { virtual ~Base() = default; virtual void func() { std::cout << "Base\n"; } void foo(std::function<void()> func) { func(); // call the std::function this->func(); // virtual/dynamic call Base::...
68,315,119
68,315,217
Don't need a return after throw - standard or compiler specific?
If I have function like this int f() { //something if () { //something return 1; } throw std::runtime_error("msg"); } In Visual studio in compiles ok and works as expected, but is it a standard thing that after throw I don't need a return statement, or it can lead to some error on other com...
You are missing one important detail, and this is: Also this would compile without compiler errors int f_wrong() {} // Wrong! It does not produce a compiler error, but calling the function invokes undefined behavior. Also this is "ok-ish" when it is never called with a false parameter: int f_still_wrong(bool x) { ...
68,315,363
68,315,565
Class can't have constants of own type inside?
What I mean, is it possible to somehow do something like this? class Color { public: static constexpr Color BLACK = {0, 0, 0}; constexpr Color(int r, int g, int b) : r_(r), g_(g), b_(b) {} private: int r_; int g_; int b_; }; Compilers complain about class Color being incomplete when defining BLA...
You might move definition outside: class Color { public: static const Color BLACK; constexpr Color(int r, int g, int b) : r_(r), g_(g), b_(b) {} private: int r_; int g_; int b_; }; constexpr Color Color::BLACK = {0, 0, 0}; Demo
68,315,418
68,316,680
boost::spirit qi::uint_ valid number range
I want to parse string which consists of CC[n], where 1 <= n <= 4 or from SERVICE[k], where 1 <= k <= 63. Valid strings: "CC1", "CC2", "CC3", "CC4", "SERVICE1", "SERVICE2", ..., "SERVICE63". I wrote the next expression: ( '"' >> (qi::raw["CC" >> qi::uint_] | qi::raw["SERVICE" >> qi::uint_]) >> '"' >> qi::eoi) But how ...
The simplest way would be to use symbols<>. The elaborate way is to validate the numbers in semantic actions. My recommendation is is either symbols OR separate semantic validation from parsing (i.e. parse the numbers raw and validate the AST after the parse) Symbols This is likely the more flexible, most efficient, an...
68,315,420
68,315,421
Glib::Regex returns junk, but equivalent C functions work fine
I'm trying to use the Glib::Regex, but it keeps returning junk. Here is a simplified version of the code: void testGetPos(std::string fileName){ auto regEx = Glib::Regex::create( "^sprite_[0-9]+__x(-?[0-9]+)_y(-?[0-9]+)\\.tif$", Glib::REGEX_CASELESS ) Glib::MatchInfo match; if(!regEx->...
So, after writing this question, I tried one more thing and that fixed it. Thought I'd better document it here in case someone else hits the same issue. I changed the equivalent of: void testGetPos(std::string fileName){ to something like this: void testGetPos(std::string _fileName){ Glib::ustring fileName = Glib:...
68,315,538
68,315,733
Catch input from another shell
I currently have a C/C++ program which uses a barcode scanner as a keyboard, catches the input and does something with it. Here's the relevant parts of code: int get_InStream() { struct timeval tv; fd_set fds; tv.tv_sec = 0; tv.tv_usec = 0; FD_ZERO(&fds); FD_SET(STDIN_FIL...
This is a XY problem situation right here. Your problem 'X' is How can I access the keyboard device as which the barcode scanner presents itself to the system regardless of the current state of the system? But you think, that by solving the problem 'Y' How can I keygrab input directed to a different terminal? Probl...
68,315,612
68,322,183
Can programs use (significantly) less memory when compiled for different processors?
I have a C++ program I'm compiling for AMD64. Of course, different processors, despite being AMD64, support different features and instructions because they implement different microarchitectures. An easy way to optimise the program for one's own machine is to just use -march=native in Clang or GCC, but this isn't very...
Different alignment rules or type widths are the two main ways you could get a difference, but -march= doesn't change that, not when compiling for the same ABI on the same ISA. (Otherwise -march=skylake-avx512 code couldn't call -march=sandybridge code and vice versa, if they disagreed on struct layouts.) Compiling fo...
68,315,662
68,315,687
Use of templates in function parameters and return type
I'm trying to use a struct with a template in function parameters and return type while declaring function. template <typename T> struct my_struct { T value; }; my_struct<T> func(my_struct<T> input_1, my_struct<T> input_2); When I tried the above code I'm getting error: ‘T’ was not declared in this scope Howev...
You have to declare func as template if you want it to be a template. T is only declared inside the definition of the template my_struct. template <typename T> my_struct<T> func(my_struct<T> input_1, my_struct<T> input_2); Or if you actually want no template, but an instantiation of my_struct, eg for int my_struct<int...
68,316,903
68,317,729
Out of the bounds in C++ and undefined behaviour
I know that in c++ access out of buffer bounds is undefined behaviour. Here is example from cppreference: int table[4] = {}; bool exists_in_table(int v) { // return true in one of the first 4 iterations or UB due to out-of-bounds access for (int i = 0; i <= 4; i++) { if (table[i] == v) return true; ...
It's undefined behavior. We can juxtapose a couple of passages to be convinced of it. First, and I won't explicitly prove it, table[4] is *(table + 4). We need only ask ourselves the properties of the pointer value table + 4 and how it relates to the requirements of the indirection operator. On the pointer, we have thi...
68,316,999
68,317,105
friend std::ostream& operator<< declaration doesn't let me access the class' private members
I have the following class declaration: #ifndef ANIL_CURSOR_LIST_H #define ANIL_CURSOR_LIST_H #include <cstddef> #include <iostream> namespace anil { class cursor_list_node { private: int data; cursor_list_node* next; cursor_list_node* previous; friend class cursor_list; }; class c...
You need to define operator<< in the anil namespace. namespace anil { std::ostream& operator<<(std::ostream& out, cursor_list& rhs) { // ... return out; // don't forget this } } An easier option is often to just define the friend function inline: class cursor_list { // ... friend std::ostream& operator...
68,317,241
68,319,951
Making MakeFile for Curl in VSCode
I am trying to make a MakeFile for linking Curl, but I cannot find a good source to learn and implement my MakeFile, following is what I have written for my MakeFile: CC=g++ CFLAGS=-g -Wall BIN=~/Documents/Github/Covid-Visualizer/testing all: $(BIN) %: %.cpp $(CC) $(CFLAGS) $< -o $@ -lcurl and following is the ...
OK, well, that's your problem. As I said, make will only look for makefiles named Makefile (or makefile or, if you're using GNU make, GNUmakefile) by default. You have named your makefile MakeFile. So make is not reading that file. So none of your rules or recipes are available. You should either rename your makefi...
68,317,247
68,357,004
301 Moved Permanently on GET request (some sites) C++
I just want to make a GET request to my telegram bot using C++ code but it's getting 301 Moved Permanently (but if I use web-browser it works fine). Request to other sites work just fine, almost with no errors (google.com, ip2c.org ...). Below I provide the code I'm using: const std::string host = "api.telegram.org"; c...
I had to redirect it from HTTP to HTTPS, and the problem was solved by changing the port from 80 to 443
68,317,535
68,344,839
Qt Transparent for selected Mouse Events
C++ Qt newbe here. I work with a QDial object that is intended to be controlled with a mouse wheel, it works fine as such, emitting valueChanged() signals when necessary. I would like to put a semi-transparent QToolButton on top of it, allowing users to click on the button (and set QDial value to a pre-defined number) ...
You can use QObject::installEventFilter to have the parent object filter the events before they reach the tool button. Then, override the parent's QObject::eventFilter to handle/ignore the event. I create an example below: mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QToolBut...
68,317,657
68,357,897
Properly close the pipeline to save image of udpsrc (currently my image is empty)
I would like to save one image of my updsrc. When the user click on a button the code bellow is running. But when I look at my image, it is empty. I try a lot of "way" to stop the pipeline but I think that I did not closed the pipeline properly. Does anyone have any idea ? GstElement* snappipe; GError* error = ...
I solve the problem like that : std::string strPathImage = "\\image.png"; GstCaps* caps; GstSample* from_sample, * to_sample; GError* err = NULL; GstBuffer* buf; GstMapInfo map_info; g_object_get((*ptrstats).sink, "last-sample", &from_sample, NULL); if (from_sample == NULL) { GST_ERROR("Error getting last sample...
68,317,672
68,318,910
coordinate conversion script isn't giving me an accurate reading SVY21 to WGS84
I would like to convert my dataset of SVY21 coordinates, into WGS84 coordinates. I am currently using this script from this repo I found but this script this yields inaccurate results with a discrepancy of up to 0.04, so the coordinates that I convert end up being on an entirely different geographical location in the s...
You probably have your coordinates the wrong way around. Consider the following: import pyproj xfm = pyproj.Transformer.from_crs('EPSG:3414', 'EPSG:4326') x, y = 38816.0396118, 34379.9602051 print(xfm.transform(x, y)) # prints: (1.3673123058118237, 103.89064694097199) print(xfm.transform(y, x)) # prints: (1.32719274...
68,317,800
68,318,148
VS2019 typedef changing when including <random>
Here I have a method which returns a vector: std::vector<uint32_t>& GetElements() const noexcept { return m_Elements; } And when I'm assigning the result to a variable: auto& elements = object.GetElements(); And hovering over elements, VS2019 says that it's type is: std::vector<std::seed_seq::result_type>, after ...
This is just IntelliSense™ being somewhat less than intelligent! Both std::seed_seq::result_type and uint32_t are defined as unsigned int, so I guess it's getting confused as to which one to show. (Presumably, the actual compiler has no such problem, and your code compiles without error.) From <stdint.h>: typedef unsig...
68,317,896
68,318,297
no match for ‘operator+’ (operand types are ‘std::vector’ and ‘std::vector::size_type {aka long unsigned int}’)
I can't find a way to apply the size( ) function. I have the following output: main.cpp:13:23: error: no match for ‘operator+’ (operand types are ‘std::vector’ and ‘std::vector::size_type {aka long unsigned int}’) sort(arr, arr + arr.size()); in the following code : vector<int> removeDuplicates2(vector<int> a...
In some cases it could be faster to use a std::set for deduplicating. That would reduce the data moved, because duplicates never get inserted into the temporary data structure. Then, removeDuplicates2 should get a const reference to eleminate an unnecessary copy of the entire array. Ideally, you could return the constr...
68,317,970
68,318,050
*this (Return reference to the calling object) does not return changed object's value in that function
Suppose there are two object : num1 , num2 each store integer number of 5 . I want to add both object's value using non member function so result is : 10 . But THE OUTPUT show value : 5 . Is there any error in class member function or *this pointer ? main.cpp #include<iostream> #include"Person.h" using namespace std ...
Comments are liars: DataSum.combine(Rdata); // add Rdata to Ldata , call class function combine This does not "add Rdata to Ldata". You are calling a method of DataSum which is a copy of LData. Modifiying the copy has no effect on the original LData. Don't make a copy: void add(Person &Ldata , const Person &Rdata) ...
68,318,339
68,319,345
pybind11: Enum vs Enum Class?
I understand the difference between enums and enum classes in the context of C++, but in the context of binding enums and enum classes is there any real difference? Say for example: enum class options { maybe, yes, no, }; enum words { hello, world }; I've just been binding them the same way (see below), s...
According to the docs, it appears that the only difference is: The enum_::export_values() function exports the enum entries into the parent scope, which should be skipped for newer C++11-style strongly typed enums. So by not calling export_values, Python will require the enum name as part of the scope when specifying...
68,318,341
68,318,457
Using R functions within a C++ function
I'm trying to convert R code implementing the golden section method to C++ code. Here is the R code: goldensectionR <- function(f, dXl, dXr, dXm, dTol = 1e-9, ...) { dFr = f(dXr, ...) dFl = f(dXl, ...) dFm = f(dXm, ...) dRho = (1.0 + sqrt(5))/2.0 if (dFl > dFm | dFr > dFm) { stop("Inital conditio...
The problem is that Rcpp doesn't know that the function will return a double, so what it makes it return instead is a SEXP - which is basically a wrapper that could stand in for lists, numbers, strings or other things. If you're sure your SExpr will always be a real you can use the asReal function to cast the SEXP to d...
68,318,509
68,318,715
How to use a global variable as part of an array name
I have four arrays: int a1 [3] = { 10, 20, 30 }; int a2 [3] = { 10, 20, 30 }; int a3 [3] = { 10, 20, 30 }; int a4 [3] = { 10, 20, 30 }; I want to call array depending on a global variable: int sys=1; lets say: int a1+sys; // this should gives array a2 int a1+2*sys; // this should gives array a3 How can I achieve t...
It seems that what you're looking for are arrays of arrays: int a[][3] = { { 10, 20, 30 }, { 10, 20, 30 }, { 10, 20, 30 }, { 10, 20, 30 }, }; auto& a2 = a[sys]; auto& a3 = a[2*sys];
68,318,538
68,319,450
Lemon graph how to find all paths between two nodes
I'm using the Lemon C++ library for graphs, and what I need to do is to find all the paths between two nodes. I'm able to find a single path (the shortest), but I need all of them. Is there a way to achieve this with Lemon? // Create the graph ListDigraph g; ListDigraph::Node a = g.addNode(); ListDigraph::Node b = g.a...
Thanks to srt1104 comment this is how I "solved" the problem, assuming I'm looking for all the paths between a and d. Dfs<ListDigraph> dfs(g); dfs.init(); dfs.addSource(a); std::vector<ListPath<ListDigraph>> paths; ListPath<ListDigraph> currPath; ListDigraph::Node prevNode = a; while (!dfs.emptyQueue()) { ListDig...
68,318,610
68,364,867
Dividend history from Yahoo finance
Is there a convenient way to obtain dividend history for a specified company from the Yahoo finance API? For example, the historic data can be obtained by the following link, with some variable conditions https://query1.finance.yahoo.com/v7/finance/download/code_name?period1=from&period2=to&interval=1d&events=history W...
You can get the past dividends for, say Apple, using this query https://finance.yahoo.com/quote/AAPL/history?period1=from&period2=to&interval=div%7Csplit&filter=div&frequency=1d&includeAdjustedClose=true To get the csv file, use this for Apple https://query1.finance.yahoo.com/v7/finance/download/AAPL?period1=From&perio...
68,319,087
68,319,394
Is there a way to create "empty" types to use for class templates?
I have a class template that looks like this: template <typename T> class TextureIcon { static std::unique_ptr<Texture> s_texture_; public: static void setTextureFile(std::string&& filePath); static std::unique_ptr<TextureIcon<T>> instance(); private: TextureIcon(); sf::Sprite sprite_; }; The idea...
Instead of using types, you can use an enum class to create different texture enumerations and then have that enumeration type as a non-type template parameter for the TextureIcon class. That would look like enum class Textures { Flower, Leaf, Branch }; template <Textures T> class TextureIcon { static Textures s_...
68,319,120
68,319,976
Vectorized/vectorizing functions in C
For me, one of the most interesting features in languages such as R or Scilab is the possibility of parallelizing operations by vectorizing functions ("meaning that the function will operate on all elements of a vector without needing to loop through and act on each element one at a time", in the words of The Carpentri...
In c (prior to c11), a given "function call" cannot be overloaded. If you want a function that operates on a vector or a function that operates on an element, those functions should have different names. With c11, _Generic and macros let you dispatch based on argument type. See this SO answer. That would permit sin(...
68,319,261
68,319,691
Template deduction on function with variadic template arguments
I am trying to write a sort of task graph. When I emplace new Tasks I want to be able to add a varying amount at once and get a tuple that contains a handle for each added task. I have written a base case for one task and overload with variadic template arguments that calls the base case. template<typename Task> node<T...
std::enable_if_t<(sizeof...(Tasks) > 1)> is just void (when it exists). So your template is template <typename... Tasks, void> whatever. So you have a non-type template parameter of type void. Good luck matching it. What you actually want instead is typename = std::enable_if_t<(sizeof...(Tasks) > 1)>, a type template p...
68,319,563
68,319,731
get-line gets always the same line C++
I have a file with data like this 10000 9.425 1.00216 -0.149976 20000 19.425 0.973893 -0.135456 30000 29.425 1.01707 -0.115423 40000 39.425 1.0181 -0.12074 . . . to get the data what I am doing is to read the whole line and then separate the line by the spaces to get the data I need. The problem is that the file has 3...
Have some issues with that code: I don't see where n is set so how do you know it is correct. The proper way to read a line is to call getline() and then test it worked (it can be done in a single line). while(std::getline(datas, str)) { // Successfully read a line from the file } You don't need to manually con...
68,319,574
68,319,648
Const Class and member functions
Do you need to define const functions when you want to create a new const instance of a class? Somehow my compiler dont find the "regular" (not const) functions, when i try to access them from a const class instance.
Yes, if an object is const, you can only call const functions on that object. If a function is not marked const, the compiler must assume that it is allowed to change the members of the class. And since you can't change the members of a const class instance, you cannot call non-const functions on that instance either....
68,319,676
68,320,189
Printing All The Files Path's In C:\ With C++
I tried to print all the files path's in C:. But I saw that I am getting permission errors. void getAllFilesInDirectory(wstring directoryPath, vector<wstring> &files) { for (filesystem::directory_entry directory : filesystem::directory_iterator(directoryPath)) { if (GetFileAttributesW(directory.path().wst...
You said in comments that: I want that my code will ignore files that he doesn't have access to them std::filesystem::directory_iterator and std::filesystem::recursive_directory_iterator both have a constructor that accepts a std::filesystem::directory_options enum as input, which has a skip_permission_denied item av...
68,320,503
68,320,700
Is there anything that would make a static bool thread safe?
I recently came across some code that was working fine where a static bool was shared between multiple threads (single writer, multiple receivers) although there was no synchronization. Something like that (simplified): //header A struct A { static bool f; static bool isF() { return f; } }; //Source A bool A::f ...
Your hardware may be able to atomically operate on a bool. However, that does not make this code safe. As far as C++ is concerned, you are writing and reading the bool in different threads without synchronisation, which is undefined. Making the bool static does not change that. To access the bool in a thread-safe way y...
68,320,551
68,320,665
Writing to .txt with WriteFile() C++
(Using C++, Windows 10, Microsoft Visual Studio 2017) Hello, I am new to serial ports but trying to learn how to open, close, read, and write with them Right now, I am trying to use the CreateFile() and WriteFile() functions to write to a txt file. I created a .txt file called "write.txt" and saved it in my Documents ...
You are not accessing the text file that is located in your Documents folder. You are accessing a text file that is located at the root of the drive where the calling process's current working directory is currently pointing at. You need to explicitly query the OS for the path to the Documents folder (ie, via SHGetFold...
68,321,203
68,321,440
Is casting an instance of a class to its subclass legal?
Is casting a class to a subclass of itself without additional data fields well defined? For example if I wanted to hide certain internal only methods from an end user like in the following. #include <string> #include <iostream> // public.hpp class Talker { public: Talker(std::string text) { this->text = text; ...
From cppreference: Performing a class member access that designates a non-static data member or a non-static member function on a glvalue that does not actually designate an object of the appropriate type - such as one obtained through a reinterpret_cast - results in undefined behavior: You can perform the reinterpre...
68,321,552
68,321,694
How to define less than (<) operator or std::less struct for Eigen::Vector3f?
I want to create a map of indices to vertices: using IndicesToVertices = std::map<Eigen::Vector3f, uint32_t>; But operator< is not defined for Eigen::Vector3f. I don't want to mess with the class itself, so I cannot declare a friend operator< for it, which seems recommended for custom "owned" types. I have tried to de...
It is generally a really bad idea to use floating point values (or aggregates) as keys into a map. That is a fundamental design issue. I mean, if there is a NaN, everything explodes. And two seemingly identical derivations of a floating point value can compare unequal. But it isn't hard to write a comparison operator...
68,321,576
68,321,667
Any benefits to declare an enum class underlying type bool?
In the library I am currently developing, I have this little thing: enum class BoolMode : uint8_t { TrueIfFalse = 0, TrueIfTrue = 1 }; This is a tiny helper used to easily produce reversible condition checks, while only having to create a single implementation that's easy to write and to read... For this help...
If bool is the underlying type of X, then std::underlying_type_t<X> is bool. Variables of type bool and enums with bool underlying type only have two valid states; 0 and 1. Variables of type uint8_t and enums with uint8_t underlying type has 256 valid states; 0 through 255. Both a compiler, and metaprogramming, can be ...
68,321,606
68,321,774
Confusing definition of multidimensional arrays in C++ Primer
The book provides the following example: int arr[10][20][30] = {0}; // initialize all elements to 0 My current understanding: It's one array of size 10, containing 10 elements, all of which are arrays themselves, of size 20, containing 20 elements, all of which are arrays themselves, of size 30, containing 30 elements...
Do I have terrible reading comprehension or is the book wrong? The book seems to say what's in your quote. It's worded poorly, in my opinion. Without speculating on the authors' intent, it could perhaps be more clearly written as: First we see that arr is an array of size 10. The elements of that array are themselve...
68,321,805
68,326,277
Options for callback from python to c++
Hello i've been trying to call a python user-defined callback from c++ using cython for a while. But it looks like it's impossible without changes on the c++ side or a static function buffer. So, is there only one option for binding a propper callback (ctypes with CFUNCTYPE)? Cython 0.29.23 A.hpp: typedef void (*Callba...
A function pointer does not have any space to store extra information. Therefore it is not possible to convert a Python callable to a function pointer in pure C. Similarly a cdef function of a cdef class must store the address of the instance to be usable and that is impossible too. You have three options: Use ctypes ...
68,322,092
68,322,207
Return error message if the command is wrong in C++
I'm working on this project where I set up some commands that my TelegramBot can execute. And I would like to add an error message if the command written is wrong. Here is the code: void handleNewMessages(int numNewMessages){ Serial.print("Handle New Messages: "); Serial.println(numNewMessages); for (int i...
Let's make the example smaller if (text == "/FlashOn") { do stuff } if (text == "/start"){ do stuff } else { report error } This code will always test if (text == "/start") regardless of the outcome of if (text == "/FlashOn") and if text is "/FlashOn", it cannot be "/start" and will execute the else and print ...
68,322,286
68,322,354
What's wrong with my LRU? Did I use std::deque mistakenly?
I'm quite frustrated about this, now I'm still have absolutely no clues why am I getting wrong. So I'm doing LRU implementation as following: #include <iostream> #include <unordered_map> #include <deque> #include <list> using namespace std; class LRUCache { public: LRUCache(int capacity) : cap(capacity) { ...
So what the heck is going on with std::deque::erase? Did I do something wrong? You have two data structures, one of which maps to iterators of the other: deque<int> cache; // deque of keys unordered_map<int, pair<int, deque<int>::iterator>> pos_map; If the iterators are to a dequeue, then the invalidation ru...
68,322,502
68,322,648
C++20 template lambdas with template parameter that is not related to function parameters
I have array of tuples. I'm sorting it. I can choose which field to use for sorting at runtime. switch (columnIndex) { case 0: std::ranges::sort(rows, [reversed](const rowType& a, const rowType& b) -> bool { if (reversed) { return std::get<0>(a) < std::get<0>(b); } return...
Without the lambda you can write a functor template: template <size_t index> struct comparator { bool reversed; bool operator()(const rowType& a, const rowType& b) const { if (reversed) { return std::get<index>(a) < std::get<index>(b); } return std::get<index>(a) > std::get<...
68,322,591
68,322,637
How to store indicies of an array in preprocessor defines?
I am creating a VST(virtual instrument) program in cpp and I have an array of structs that represent various parameters in my program: const FloatParam_Properties FloatParamProps[NUM_FLOAT_PARAMS] = { //Frequency {"BaseFreq", "Base Freq", 0.0, 20.0, 5.0, 0.6}, //0 {"FreqDelta", "Freq Delt...
Use x-macros: #define PARAMS(X) \ X(BaseFreq, "Base Freq", 0.0, 20.0, 5.0, 0.6) \ X(FreqDelta, "Freq Delta", -20.0, 20.0, 0.0, 0.6) \ X(OscSelect, "Wave form", 0.0, 3.0, 0.0, 1.0) const FloatParam_Properties FloatParamProps[NUM_FLOAT_PARAMS] = { #define PARAM_STRUC...
68,322,878
68,322,952
What does !(cout << ....) mean
I just came across a code snippet in C++ here: https://www.geeksforgeeks.org/c-cpp-tricky-programs/ One of the snippets is basically: if (!(cout << "A")) { cout <<" B "; } else { cout << "C "; } The output is: "AC" What exactly does the argument in the if clause mean ? And how would you word it in regular Engl...
First, std::cout::operator<< returns a reference to the stream. Next, std::ostream has an operator bool (inherited from std::basic_ios): Returns true if the stream has no errors and is ready for I/O operations. Specifically, returns !fail(). Hence, what happens is that cout << "A" prints "A", then returns a reference...
68,322,926
68,348,272
Error while linking library available through conan-package using target_link_libraries. When linking manually, it works
[Background] I have to move some .cpp files out of repo [repo2] to new repo[repo1]. To achieve this, I took these cpp files from repo2 and made a library (xyz.lib in repo1) as follow. [In repo1] add_library(XYZ PUBLIC stdafx.h stdafx.cpp m.cpp p.cpp) ...
In the conanbuildinfo.cmake some of the PACKAGE_LIBS path were not set. This happens when conanfile.py from which the package was created does not contain the information about exact path of libs present in package. In such cases, we need to explicitly mention the name of the libs while creating the package. For Eg: If...
68,323,099
68,323,137
Why can I modify const_cast-ed object in constexpr function?
I always assumed: writing to const_cast ed variable is UB there is no UB allowed in constexpr So I am confused why this code compiles: constexpr int fn(){ int v = 42; return [v]() { const_cast<int&>(v)+=5; return v; }(); } static constexpr auto val = fn(); int main() { return val; } n...
This part is true: there is no UB allowed in constexpr This part is not: writing to const_cast-ed variable is UB The actual rule is, from [dcl.type.cv]/4: Any attempt to modify ([expr.ass], [expr.post.incr], [expr.pre.incr]) a const object ([basic.type.qualifier]) during its lifetime ([basic.life]) results in unde...
68,323,102
68,323,221
How to acess the result from a function pointer in dart
I am trying to get the return value from c++ function in dart. My c++ code is something like this static bool is_alive() { return true; } From dart, I loaded the shared lib with this native code and I am trying to call that is_alive() function. typedef BooleanFunction = Pointer<Int8> Function(); Pointer<NativeFunct...
For some reason you never actually call your isAliveFunc function. Just call the function as you would any other: Pointer<Int8> casted = isAliveFunc(); or Pointer<Int8> casted = isAliveFunc.call(); You should also be paying attention to your Dart static analysis warnings and errors. Your function definitions are als...
68,323,616
68,689,141
Unable to initialize vector with initializer list in visual studio code
#include <vector> #include <iostream> using namespace std; int main() { vector<int> v = {1,2,3,4}; for (int x : v) { cout << x << ' '; } return 0; } When I run the above code in vscode I receive the following ERROR: non-aggregate type 'vector' cannot be initialized with an initializer list gc...
I copied your code and named it test.cpp. I faced the same issue and I solved it by adding some configurations. Find tasks.json and add something in args. "args": [ "-g", "-Wall", "-std=c++11", "test.cpp" ] It works on my MAC! I used command+shift+B to compile and it generated a.out after compiling. Th...
68,323,774
68,323,812
Template pack expansion with functions
The code below works as intended. struct A { template<typename T> void do_real_stuff() {} template <typename... Types> struct DoStuff; template <typename Head, typename... Tail> struct DoStuff<Head, Tail...> { DoStuff(A &base) { base.do_real_stuff<Head>(); ...
You can't partially specialize function templates - only class templates. But you don't actually have to do that in this example. You're already using a fold-expression, just also include the first type: struct B { template<typename T> void do_real_stuff() {} template <typename... Types> void DoStuff(...
68,323,902
68,323,954
How to use string to call function in a class?
I hope to use map library to call a function by a string with the function name, I've tested the following example and everything are working well. #include <string> #include <iostream> using namespace std; typedef void (*pFunc)(); map<string, pFunc> strFuncMap; void func1() { printf("this is func1!\n"); } void...
Your code doesn't work because func1 is a member function and the syntax for member functions is different. You need a map of member function pointers (offsets) typedef void (theClass::*pFunc)(); map<string, pFunc> strFuncMap; Then you can store the pointer with strFuncMap["func1"] = &theClass::func1; And you need an...
68,324,084
68,340,810
Can't use newline in OutputDebugStringW, weird behavior in DbgView
I'm using OutputDebugStringW in my application. Since WinDBG does not automatically append a newline, I had to add the \n in my output buffer: #include <iostream> #include <windows.h> int main() { wchar_t buff[100]; ZeroMemory(buff, sizeof(buff)); _snwprintf_s(buff, sizeof(buff) / sizeof(wchar_t) - 1, L"[t...
As pointed out by Retired Ninja, _snwprintf_s fill out the buffer with another value if the program is build in DEBUG mode. In this case the wchar_t is filled with 0xFEFE: If I compile the program in Release mode, the string will be NULL terminated.
68,324,090
68,324,191
how to use a function object as a custom comparator for accessing a local variable instead of using a lambda function in C++?
I am trying to learn priority_queue concept in C++, and I came across this interview question. Although, I managed to solve this problem with a lambda function, I could not figure out how to do the same operation with a custom comparator as a function object (I think it is called as 'functor') I really had a hard time...
You can create an object explicitly like this: struct // no need to name the type { unordered_map<string, int> &freq; // store variable by reference // write operator() bool operator()(const string &left, const string &right) const { if (freq[left] < freq[right]) { retu...
68,324,150
68,332,925
reading a binary file in c++ just like in python
I want to read a file in binary mode in c++. Initially i was using python to do the same when i read the same file using python i got the result b'\xe0\xa4\xb5\xe0\xa4\xbe\xe0\xa4\xb9' which when converted to INT resulted in 224 164 181 224 164 190 224 164 185 and i am able to notice that all these INTs are always in t...
As mentioned in the comments, the issue here is that char by default, is signed - meaning it takes values in the range [-128, 127]. This was, 224 will roll over to the negative end and become -32. You should use an unsigned char, which will make the range [0, 255]. #include <iostream> #include <io.h> #include <fcntl.h>...
68,324,244
68,324,272
Std::Cin isn't working and says it is an incorrect operator
#include <iostream> using namespace std; int main() { int Principal = 0; int RetirementAge = 65; int CurrentAge = 0; std::cout << "What is your current age?" << std::endl; std::cin >> CurrentAge >> std::endl; std::cout << CurrentAge << "Is this correct?" << std::endl; return 0; } It gives t...
The problem is this part: >> std::endl std::endl is for output streams only, don't use it when reading in CurrentAge. std::cin >> CurrentAge;
68,324,299
68,325,178
C++: inherited classes have pure virtual functions with identical names. How can I override them separately in my base class?
The following code illustrates my question: namespace foo1 { class bar1 { public: virtual void fn() = 0; //this must remain pure virtual }; }; namespace foo2 { class bar2 { public: virtual void fn() = 0; //this must remain pure virtual }; }; class bar3: public f...
Sure. struct foo1bar1helper:public foo1::bar1{ void fn()final{foo1bar1fn();} virtual void foo1bar1fn()=0; }; now bar3 just inherits from this instead of bar1 and overrides foo1bar1fn(), Do the same with bar2. You can also use CRTP to dispatch and do away with the extra vtable lookup; template<class D> struct foo1b...
68,324,995
68,325,372
Randomly Shuffle an array and using quick sort algorithm
I have been trying to write a code to randomly shuffle the array elements, and then use the quick sort algorithm on the array elements. This is the code I wrote: #include <iostream> #include <cstdlib> #include <ctime> using namespace std; void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } void...
Basically, when the error is segmentation fault, you should be looking for a bug which you will feel like crashing your head into wall, after finding it. On line 26. change <=, to < . It's in your partition function. for (j = s; j < e; j++) A little explanation about quick sort; After each time quickSort function runs ...
68,325,368
68,325,934
Package was not found in the pkg-config search path
I am trying to install this package on ubuntu 18.04. The installation instructions say that the installation command should look like the following: - autoreconf -i -f - ./configure --with-libmaus2=${LIBMAUSPREFIX} \ --prefix=${HOME}/biobambam2 - make install The first line seems to work without any errors. When I...
you need to install correctly libmaus2 and set correctly PKG_CONFIG_PATH : configure and compile libmaus2 this way : ./configure --prefix=/SOFT/libmaus2 && make -j8 install export PKG_CONFIG_PATH=/SOFT/libmaus2/lib/pkgconfig ./configure --prefix=/SOFT/biobambam2 && make -j8 install
68,325,594
68,325,689
Why is the destructor of child class called before parent‘s’?
in C++, when the object's desctructor is called, it first invokes child class's destructor, and then parent's, which is the opposite of construct procedure. But why? It seems to be a simple question, but I haven't found a satisfying answer on the internet. Could someone explain the nessisity of doing destructing in suc...
Assuming you're talking about parent/child meaning inheritance consider that struct Car : Vehicle { ... }; is not really much different than struct Car { Vehicle _base; ... }; except that automatically when you refer to a Vehicle property in a Car method _base. is implicitly added by the compiler. The standard even...
68,325,673
68,326,195
Why default capture is not consistently const for both local variables and member variables?
I'm curious what's the story behind following inconsistency with passing default parameters: struct Example { void run() { int localVar = 0; auto l = [=](){ // localVar = 100; Not allowed (const copy of localVar) memberVar = 100; // allowed (const copy of this pointer - NOT c...
You're right, this is a lame behavior. That's why in C++20 the implicit capture of this (i.e. by reference) is deprecated when the capture-default is =. Presumably the intent is to change = one day to capture *this (i.e. by value).
68,326,170
68,326,754
Changing the file's creation timestamp in Linux programmatically in C/C++
The statx() system call was added to Linux kernel and now it is possible to get the creation (birth) time of the file from statx.stx_btime stucture field on supported filesystems. But I can't find any support in utimensat() of similar system calls. Is it possible to change file's creation timestamp in C/C++ and how?
statx.stx_btime is filesystem-specific. Linux has only three standardized timestamps - ctime, atime, and mtime - which are filled by the filesystem-agnostic generic_fillattr function. Creation time on the other hand is filled by filesystem-specific functions, for instance with ext4 you can see the relevant code here: i...
68,326,497
68,326,639
Why is this access of base class data members deemed to be type punning (in optimized builds)?
I've got something along the lines of: #include <utility> #include <cstdlib> struct Core { void* mData{}; size_t mCount{}; }; template <typename T> struct Actual: protected Core { Actual() = default; Actual(Actual<T> const& other) = delete; Actual<T>& operator=(Actual<T> const& other) = delete; Actual(A...
Looks like a GCC bug. GCC 9.4 and newer don't diagnose this. If you rewrite operator= like this, it stops complaining, and this form is also shorter. Actual<T>& operator=(Actual<T> other) { std::swap(mData, other.mData); std::swap(mCount, other.mCount); // I like this more than `mCount = tmp.mCount;`. retur...
68,326,585
68,326,644
Fill a char* in another function using malloc in c/c++
I'm codding for Arduino (ESP8266), and have to read a string from a file, to use it. I don't know how long is that file, so I have to create a char* and pass it to the readConf function so that malloc decides for the memory size. void readConf(char path[], char **buff){ SPIFFS.begin(); if (SPIFFS.exists(path)) ...
The function parameter buff is a local variable of the function void readConf(char path[], char **buff){ So changing it within the function buff = &bu; //!This is the problem! has neither effect on the variable password declared in the function setup char* password; readConf(file_path, &password); You need to write ...
68,326,597
68,326,673
How can the type of braces influence object lifetime in C++?
A friend of mine showed me a program in C++20: #include <iostream> struct A { A() {std::cout << "A()\n";} ~A() {std::cout << "~A()\n";} }; struct B { const A &a; }; int main() { B x({}); std::cout << "---\n"; B y{{}}; std::cout << "---\n"; B z{A{}}; std::cout << "---\n"; } In GCC...
Gcc is correct. The lifetime of the temporary will be extended only when using list-initialization syntax (i.e. using braces) in initialization of an aggregate. (since C++20) a temporary bound to a reference in a reference element of an aggregate initialized using direct-initialization syntax (parentheses) as opposed ...
68,326,861
68,327,104
Armstrong number program in C++ does not print the correct output
#include<iostream> #include<math.h> using namespace std; int main() { int num,count,temp,sum=0,powr,rem; cin>>num; temp=num; while(temp>0){ ++count; temp=temp/10; } while(num>0){ int num; rem=num%10; powr=round(pow(rem,count)); sum+=powr; n...
Your definition of Armstrong number is correct i.e. sum of pow of digits where pow = count of digits. However, the problem comes in the last while loop. The control moves out the while loop when num equals to zero. And then in the statement if(sum==num){cout<<"true";} you are comparing simply sum == 0 which obviously ...
68,327,199
68,327,820
cannot initialize a parameter of type 'int **' with an lvalue of type 'int [m][n]' note: passing argument to parameter 'dp' here
I was trying a DP problem but I am not able to pass the dp[m][n](type of int matrix) table as a reference to the recursive function. how to pass it? Below is the code that I wrote. class Solution { public: int countPaths(int m,int n, int **dp){ if(m==1 || n==1) return 1; if(dp[m][n]!=-1)return dp[m][...
If you look at the underlying memory structure you will see why the compiler isn't letting you pass int[m][n] in place of int**. If you have int**, what you pass is a pointer to an array of pointers to arrays of ints. The memory therefore looks like: int** -| V [ int*, int*, int*, ...] V V V...
68,327,292
68,327,350
i'm writing a cpp program to print all prime numbers between two numbers . Program is running successfully but it is not printing anything
#include <iostream> using namespace std; bool isPrime(int num){ for(int i=2;i<=num;i++){ if(num%i==0){ return false; } } return true; } int main() { int a,b; cin>>a>>b; for(int i=a;i<=b;i++){ if(isPrime(i)){ cout<<i; } } return 0; }...
for(int i=2;i<num;i++) you've used i<=num where the logic should be i<num in your isPrime function. cause all the primes are divided by themselves. but you should not count that while finding primes
68,327,499
68,327,945
Using Reinterpret_Cast in a Constexpr Function
To my understanding C++11 specifically designates that reinterpret_cast cannot be used within a constant expression. The reason (again to my understanding) is that the compiler cannot interpret the validity of the conversion. With that being said, there does seem to be some level of trickery that can be used to allow t...
Firstly, a compiler can execute a function at compile-time even if it's not constexpr, as long as it doesn't affect the visible behavior of the program. Conversely it can execute a constexpr function at runtime, as long as knowing its result is not required at compile-time. Since you're saying you don't know how to tes...
68,327,583
68,331,432
Can't figure out how to link C++ package I want to compile to a library
I want to compile biobambam2 package which is dependent on libmaus2 library. Both are separate folders in one directory. I compiled libmaus2 and libmaus2.pc file is in its base directory. Now if I try to compile biobambam2 using this command: - autoreconf -i -f - ./configure --with-libmaus2=/SOFT/libmaus2-2.0.794-relea...
Ubuntu 18.04 example : Build in /home/name/tmp/ sudo apt install python3-pygments libsnappy-dev libgmp-dev Downloaded from Ubuntu 20.04 https://packages.ubuntu.com/focal/libdeflate-dev → sudo gdebi libdeflate0_1.5-3_amd64.deb && sudo gdebi libdeflate-dev_1.5-3_amd64.deb Installed gcc94-c++_9.4.0-9_amd64.deb https://dri...
68,328,017
68,328,073
Single colons in arbitrary expressions?
I need to figure out what this obfuscated C++ code (written by someone else) does. I've figured pretty much everything, except one tricky part: bool part1(char *flag) { int *t = (int *) memfrob(flag, 8); unsigned int b[] = {3164519328, 2997125270}; for (int i = 0; i < 2; b[i] = ~b[i], ++i); return !(...
The code is making use of two-letter alternative tokens, also known as "digraphs". Specifically, <: is [, and :> is ]. So, syntax like 0<:t:> is just 0[t], and since array subscripts can be swapped with the array identifier, this is just t[0]. A great tool that can help with deobfuscating code is cppinsights.io. As can...
68,328,226
68,328,277
JSON file error in Visual Studio Code:Expected comma json(514)
A strange problem. I don't think there's something wrong with this JSON file,but it tells me: Expected commajsonc(514). I cannot find any answer to help me out.Though there are many similar answers. What should I do? { "C_Cpp.errorSquiggles": "Disabled", "files.associations": { "array": "cpp", "...
JSON disallows "trailing commas", a comma after the last value inside a data structure. Try removing trailing commas on these: "typeinfo": "cpp", "**/*.o": true, Also, add a comma before this line: "files.exclude": {
68,328,290
68,328,324
Why does std::atomic compile from C++17 even with a deleted copy constructor?
I have a simple code: #include <atomic> int main() { std::atomic<int> a = 0; } This code compiles fine with GCC 11.1.0 with -std=c++17, but fails with -std=c++14 and -std=c++11. using a deleted function std::atomic::atomic(const std::atomic&) Why is that? In C++17 class std::atomic still doesn't have a copy con...
Since C++17 such copy elision is guaranteed. For std::atomic<int> a = 0;, a is required to be initialized from 0 directly. Note: the rule above does not specify an optimization: C++17 core language specification of prvalues and temporaries is fundamentally different from that of the earlier C++ revisions: there is no ...
68,328,559
68,328,842
std::visit can't deduce type of std::variant
My purpose is getting any value from the data array without specifying the type every time when I'm getting the value. I created special tables that describes the field information (field name and type) and also wrote a function that helps me to interpret data properly. The code is presented below: #include <iostream> ...
One fundamental rule of C++ when it comes to optimizations of any kind is that no compiler optimization can have any "observable effects". This means, amongst other things, that well-formed code cannot be optimized into ill-formed code. And ill-formed code cannot be optimized into well-formed code. const auto value = g...
68,328,782
68,329,048
Constructor taking std::initializer_list is preferred over other constructors
I compile this code below with GCC 11.1.0 with a flag -std=c++17. It occurs that on the stdout is printed initializer_list. I compiled the same code with MSVC with the flag -std=c++17 but it printed "copy constructor". Which compiler is more compliant with the cpp standard? Is compiler free to choose one of the constru...
The compiler is pretty much never "free to choose" for stuff like this. If it were, we wouldn't be able to write pretty much any portable C++ code. [over.match.list] does give priority to initializer_list constructors. Constructor function overloading under the rules of list initialization gets invoked at step 3.6. Ste...
68,329,004
68,329,119
C++; find all smaller numbers that are only divisible by 2 or 3, and no other prime number
my problem is to find all natural numbers smaller or equal to n (n < 10^4), which are: divisible by 2 or 3 indivisible by any other prime number. The first part is of course easy, however I cannot combine it with the second one. It seems very simple, yet I cannot think of an elegant solution. Thanks
Every natural number can be written as a mutiple of primes. It follows that all numbers satisfying your requirements can be written in the form 2a3b. So you just need a couple of nested loops for a and b (or perhaps more eficiantly for 2a and 3b),
68,329,121
68,329,410
Why there is Qt::UserRole in delegate in this example?
I read a tutorial book about delegates in QT. There is a simple example. We create QComboBox as editor with 3 values: "", "Pan", "Pani". We reimplement 3 methods: createEditor, setEditorData, setModelData in TitleDelegate class. I understand the first and the second one. QWidget * TitleDelegate :: createEditor (QWidget...
Look at this Documentation about Qt::ItemDataRole: But For User roles: As It says : For user roles, it is up to the developer to decide which types to use and ensure that components use the correct types when accessing and setting data.
68,329,626
68,329,728
Recommended way to have backward compatible concepts in C++20
I'm fairly new to concepts but I like them so far and wanted to use them in a project. The problem is I also wanted the project to compile with earlier C++ standards. So far I've come up with the following pragmatized solution: #if ISCPP20 template<NumT number = double,Index index = int,CoordinateContainer<number>...
As a practical matter, if you want to be able to easily remove concepts from code with a macro check, you should not use any kind of compact concept syntax. That means you should always use explicit requires clauses. This makes the syntax easier to #if around. If you have overloaded concepts, where multiple definitions...
68,329,639
68,330,011
GCC codegen: What does pthread_create_key() have to do with std::shared_ptr copying?
While comparing assembly for std::shared_ptr vs. boost::shared_ptr, I noticed that GCC generates a whole lot more code for void test_copy(const std::shared_ptr<int> &sp) { auto copy = sp; } (https://godbolt.org/z/efTW6MoEh – more than 70 lines of assembler) than for the boost version, on which GCC's implementation of...
I think this is because GCC's libstdc++ is checking whether the program is actually multithreaded. If it's not, then it can skip the expensive locked instructions to atomically modify the reference counter, and revert to ordinary unlocked instructions. Boost doesn't have this feature and uses the locked instructions ...
68,329,762
68,337,006
Visual Studio C++ : same program using different amounts of RAM under different executable names
This might be a general question, but this problem is really getting me confused. I have two different C++ applications, compiled with Visual Studio 2012, needing an instance of the same object. I have put a breakpoint before the creation of each object to measure the RAM usage by stepping my programs. The first one ta...
Alright, I "solved" it, kind of. You're not going to believe what the problem was. TL;DR : Renaming the executable lowers the RAM usage from 80 MiB to 28 MiB. It seems that Windows is suspicious of non-verified applications, as I discovered a directory full of logs inside C:/Users/<Me>/AppVerifierLogs/. It seemed that ...
68,329,828
68,330,069
How to memoize or make recursive function with no apparent pattern?
Consider the following code, it was done for the Codeforces Round #731 (Div. 3), problem B https://codeforces.com/contest/1547/problem/B In short, you are given a string and you are supposed to check if it's possible to create that string by sequentially adding letters in alphabetical order in either the front to the b...
You are doing brute force approach which is time complexity of n * 2^n. And it looks pretty reasonable to fail(TLE) when n is around 20 (taking into account that t is up to 10000) I cannot come up with a way for efficient memoization, however this problem can easily be solved with greedy approach. You don't have to ch...
68,329,853
68,330,016
Vector push back a derived smart pointer into a vector of smart pointers of a base abstract class
Suppose I have the following base abstract classes class Worker { public: struct Details { std::string name; }; public: virtual void work() = 0; }; class Manager { public: virtual ~Manager() = default; virtual void hire(Worker::Details details) = 0; virtual v...
The push_back doesn't work because you forgot to make the inheritance public. Probably the same issue for emplace_back, though you should never use emplace_back for a vector of smart pointers.
68,330,503
68,330,613
How to convert a integer to a binary in C++20?
I am trying to convert a char into a binary. So first I used static_cast< int >(letter) then I used cout<<format("The binary value is {:b}",integer_value);. I am using C++20 in Visual Studio 2019, so that is why I used format. However, I used it but it gives the wrong value. For example, I typed in k and it showed a bi...
The output shown is numerically correct – it's just missing a leading zero. You can force the addition of leading zeros by specifying a field width (8) and add the 0 in the specifier. The following line (using {:08b}) will output your binary value in the desired format: cout << format("The lower case letter is {} and i...
68,330,757
68,573,120
MS Visual c++ "The number of source files and corresponding outputs must match"
I'm trying to compile my code on c++ in msVisual2019 but I get an error at every try: Severity Code Description Project File Line Suppression State Error MSB6001 Invalid command line switch for "CL.exe". System.ArgumentException: The number of source files and corresponding outputs must match. at Microsof...
Preprocess to a File doesn't seem like a good idea according to its description: This option suppresses compilation... I'm glad you set it to No. – rturrado Jul 10 at 21:04 Thanks @rturrado :D
68,330,827
68,330,933
To initialize 2D vector with zero values
I want to construct an 2D-array of value passed n, basically I am trying construct n*n array and want to assign all values to zero. to do that vector<vector<int> > ans(n, vector<int>(n)); I am trying like this but when check for the size it is returning value of n passed. where i am expecting the array size to be n*n I...
You might like an idea to create own container class, which may or may not use std::vector as a storage. and would emulate 2D-array using vector or dynamically allocated 1D array. That way you would have a contiguous sequence of elements, you may treat the data as 1D array when required without taunting UB, etc. Such ...