question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
65,102,143
65,102,270
Socket bind() error: invalid operands to binary expression
Code: if (bind(sockfd, (sockaddr *) &addr, sizeof(addr)) == -1) { Error: fs_server.cpp:264:56: error: invalid operands to binary expression ('__bind<int &, sockaddr *, unsigned long>' and 'int') if (bind(sockfd, (sockaddr *) &addr, sizeof(addr)) == -1) { This was working when I run this code using C++11, a...
Your code is trying to call the C++ std::bind() function, not the socket bind() function. This is likely due to a using namespace std; statement in your code. To ensure the correct function is being called, you can either get rid of the using statement, or else qualify the call as using the function from the global nam...
65,102,498
65,102,566
How do you include header and implementation files in c++?
I am learning c++ and the instructor made a video on how to make classes and functions in multiple files. I have 3 simple c++ files called "main.cpp", "something.h", and "something.cpp", they are all in the same directory that has no other files. (they are below) the problem is that the linker is throwing an error mess...
At simplest, clang++ -Wall -g something.cpp main.cpp -o main. You could also compile something.cpp first to create something.o... clang++ -Wall -g -c something.cpp ...then specify to link with that when compiling main.cpp: clang++ -Wall -g main.cpp something.o This last approach scales better, as if you only change m...
65,102,912
65,103,256
Memcpy segmentation fault even when memory is allocated
I'm attempting to copy the data from one file by writing it to memory and then copy it into another using memcpy but I'm stumped. I cannot get it to stop giving me segmentation fault. I have a feeling it has something to do with the allocated memory, but I also made sure the file size of the output file is the same as ...
creat creates a file which is only open for writing. You cannot mmap such a file descriptor because there is no such thing as write-only memory. If you were to check the return value from the mmap of out_fd, you would find that it failed, with errno == EACCES. When mmap fails it returns an invalid pointer MAP_FAILED...
65,103,508
65,120,850
Is it possible for a macro to expand to code that will be executed exactly once when a program starts, regardless of how many times it's used?
In my Qt apps, I use a preprocessor macro to automatically both declare and register a meta-type: #define Q_DECLARE_AND_REGISTER_METATYPE(TYPE) \ Q_DECLARE_METATYPE(TYPE) \ static struct TYPE ## _metatype_registrar { \ TYPE ## _metatype_registrar() { \ qRegisterMetaType<TYPE>(); \ } ...
This is the sort of problem that can be resolved with a singleton pattern. In a nutshell, the singleton pattern ensures only a single instance of a type is ever created. One approach could be to create an inner singleton class that implements your registration action in the constructor. Then, your outer class would obt...
65,103,549
65,103,600
What does this fragment does? Static pointer to self
class X { private: static X* obj; X(){}; public: static X* setObj(); static void removeObj(); }; X* X::obj = nullptr; X* X::setObj() { if ( obj == nullptr ) obj = new X; return obj; } void X::removeObj() { delete obj; obj = nullptr; } Can't exactly understand what the class and ...
It's a Singleton, but it's got the potential to be buggy in multi-threaded usage. This is the correct way to do it in C++11 - names changed to match your code: X &getObj() { static X inst(...); return inst; } No need to explicitly delete the object since the runtime will do it automatically on shutdown.
65,103,587
65,104,847
create table with rows and columns (full box) in c++
i want to create a table with has box for each house members table. i use here a 2D array for member and use some ascii character like '|','-' for rows and columns and its create with loops ,, but i have a problem ,,, the boxes doesn't complete good , the left column of box doesn't complete and there is a "endl" in pro...
Like this ! #include <iostream> #include <conio.h> #include <stdio.h> #include <windows.h> #include <string.h> using namespace std; void setTable(); string table[10][2] = { { "black", " 0" }, { "brown", " 1" }, { "red", " 2" }, { "orange", " 3" }, { "yellow", " 4" }, { "green", " 5" }, { "blue", " 6" }, ...
65,103,828
65,103,966
How to use cout and cin without #include in C++?
I want to make a program in C++ without #include and I don't want to use printf and scanf in my program. I can use printf and scanf in my program without #include: extern "C" { int printf(const char *format, ...); extern int scanf(const char *format, ...); } But I can't use cout and cin in my program without #...
How to use cout and cin without #include in C++? There is no standard way to do this. std::cout and std::cin are variables of implementation defined classes. Only way to get the definitions of those classes is to include them from the standard header.
65,103,941
65,105,480
How can i use regex in my code to split string line that divided by comma
Hello i have text file has each line like below. 101,Tarkan,E,1,22,1,1,0 102,Mustafa,E,2,54,0,0,1 103,Seher,K,2,65,0,1,0 104,Ali,E,1,88,0,1,0 105,Ahmet,E,3,12,1,0,0 106,Osman,E,5,2,0,0,0 107,Remziye,K,3,63,0,0,1 108,Ayse,K,1,10,0,0,0 109,Esma,K,2,25,0,0,0 ...
Not sure regex is better, but you might do: const std::regex reg{R"(^(\d+),(\w+),(\w),(\d+),(\d+),(\d+),(\d+),(\d+)$)"}; while (std::getline(fkisiler, line)){ std::smatch items; if (std::regex_match(line, items, reg)) { kisiler[j].id = stoi(items[1]); kisiler[j].isim = items[2]; kisile...
65,103,980
65,104,061
Why does a simple C++ program generate so many branch commands? Using perf on Linux
I must be doing something stupid or using perf incorrectly ? #include <iostream> int main() { return 0; } Compile command (Using g++-9.2.1) g++ -std=c++17 -Wall -Wextra -pedantic -O3 Source.cpp -o prog Following the tutorial stat Run a command and gather performance counter statistics I attempte...
About 80% of the branching comes from dynamic linking. Files need to be opened and then the dynamic libraries need to be parsed. This requires a lot of decision making as the contents of the file have to be tested to see what their format is, what sections they have, and so on. Most of the remaining 20% is precisely th...
65,104,337
65,104,390
Get Array Length using Templates (Assignment)
I am trying to write a code that gets the length of an array with any type. I can't change anything in the main function since this is an assignment. The code I wrote is the implementation of array_length. I do not understand why I can get the length of both the int and the double but not the length of the char array. ...
The return type of array_length is T, when being passed a char array, the return type would be char. Then std::out would print the return value as a char with ASCII code 8. Change the return type to std::size_t. template<class T, size_t N> size_t array_length(T (&arr)[N]){ ... } BTW: As the implementation, you ca...
65,104,375
65,104,974
Deletion from a Circular Linked List
I was working on the codes for Deletion from a Circular Linked List. While working on this code on this, I realized that there was an error while deleting the first element of the list, but I could not find how to fix this error because I am not fully aware of the subject. Help with this // C++ program to delete a ...
You need to add a return statement when head node is the one which needs to be deleted. Also, as @molbdnilo pointed out, you should use (new and delete) or (malloc and free).
65,104,558
65,106,815
Save Data to a .DAT file
I need to save data the user input to a dat file, I got a description of an item, price, quantity my code is this, it doesn't save the data though void saveInventory() { ofstream outfile; outfile.open("inventory.dat", ios::binary); if(!outfile.is_open()){ cout<<"File openning error."<<endl; return; } outfile.wr...
You may have to write something like: outfile.write((char*)&items[0], items.size() * sizeof(item));
65,105,137
65,106,660
How do I customize a QSlider that would work with timestamps?
I am new working with QT. I am familiar with the QSlider class of Qt. But I am not sure whether it works with Timestamps. I have a QSlider object that can return an integer based on the position of its tick. However I want to customize it so that it can return timestamps (Ex. 10:50:20) instead. Could you tell me whethe...
okay! so it was really easy! #include <QApplication> #include <QSlider> #include <QLabel> #include <QTime> #include <QVBoxLayout> int main(int argc, char *argv[]) { QApplication a(argc, argv); QWidget w; w.resize(500, 200); w.show(); auto vLayout = new QVBoxLayout(&w); auto slider = new QSlid...
65,105,781
65,105,983
What does this C++ syntax means?
I am trying to understand the inner workings of a cpp code. The bit I am focusing is composed of 2 .cpp / .h. The Base class is called Ionization. The Derived class is called IonizationTunnel. Inside IonizationTunnel.cpp I see the following: #include "IonizationTunnel.h" IonizationTunnel::IonizationTunnel( Params &para...
Yes, it's called a member initializer list. It's the only place you can call the base constructor, there is no super() like in Java or Python. Both () and {} are ok for initialization: the former performs "direct initialization", the latter performs "direct list initialization". Their behavior can differ sometimes. E.g...
65,105,932
65,333,895
Why does an out-of-class member template definition need a repetition of its declaration 'requires-clause'
This is related to the following question: Does a class template's requires clause have to be repeated outside member definitions? In other words, given the code for the following templated struct A, the requires-clause needs to be repeated for the foo() function definition (per the standard paragraphs quoted in the li...
According to the last section of https://en.cppreference.com/w/cpp/language/constraints you can specialize templates not only on parameters but also on their constraints. Like parameter specializations the standard defines also a partial ordering of constraints, such that a template specialization might be more constra...
65,105,987
65,107,784
Can boost::container::strings be serialized using boost serialization?
I am attempting to serialize a class which contains a boost::container::string #include <iostream> #include <cstdlib> #include <boost/container/string.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/string.hpp> class car { public: car() {} ...
Yes. Surprisingly, the necessary support is not baked into Boost. Though if you look inside the string serialization header you will find that it has support as "primitive", and it takes just one line to enable it: BOOST_CLASS_IMPLEMENTATION(boost::container::string, boost::serialization::primitive_type) Now it works ...
65,106,010
65,107,022
Libc hypot function seems to return incorrect results for double type... why?
#include <tgmath.h> #include <iostream> int main(int argc, char** argv) { #define NUM1 -0.031679909079365576 #define NUM2 -0.11491794452567111 std::cout << "double precision :"<< std::endl; typedef std::numeric_limits< double > dbl; std::cout.precision(dbl::max_digits10); ...
0.11920465852172932 is represented by 0x1.e84324de1b576p-4 (as a double) 0.11920465852172930 is represented by 0x1.e84324de1b575p-4 (as a double) 0.119204658521729311251 is the long-double result, which we can assume is correct to a couple more decimal places. i.e. the exact result is closer to rounded up result. Th...
65,106,269
65,161,750
Field gets overwritten when opening audiostream in OBOE
I am using OBOE to build an sound app. I have in my AudioEngine.cpp defined couple of fields (audiosample - float, starting position field - int field, sample lengths field - int field etc.) However one of the fields (sample lengts - int field) gets overwritten when I open the audiostream with playbackBuilder. See code...
The solution is instead of C-style array to use Standard Library container. In my case its std::vector as I don't know the exact size at compile time. So I obtain an C-style array from JNI and create a vector , in this way the values are not overwritten . C-style array do not somehow offer protection for the data when ...
65,106,412
65,106,455
C++ msvc compiler not type checking function parameter that's a reference
enum inputs : int { OPTION1, OPTION2 }; struct optionStr { float someData; inputs tst; optionStr(inputs _in) { tst = _in; } optionStr() {} }; void foo2(const optionStr& _in) { printf("inputs tst: %d\n", _in.tst); } int main() { foo2(OPTION1); // no compile time error?! } OPTION1 is defi...
Marking constructor with a single argument explicit will prevent construction of unnamed temporary in foo2 invocation. explicit optionStr(inputs _in) { tst = _in; }
65,106,483
65,106,546
Overloading operator + and doing a + b where a is int and b custom object
I've overloaded + operator for my custom class when the second argument is int. For example if my object is x, then x + 7 is possible while 7 + x is not. How can I make the latter possible? I think including my class code is not necessary here.
Overloading operator + and doing a + b where a is int and b custom object By defining the overload operator+(int a, custom b). It may however be preferable to make the custom type implicitly constructible from int in which case you would only need one operator overload operator+(custom a, custom b) which would work w...
65,107,051
65,107,228
Transparent read from stdin or a file in C++?
I would like to parse either an stdin stream or a file. So I want a function/method to accept either of this. Note that my goal is not to call read twice! As istream is the base class for cin and ifstream` I should be able write this: #include <iostream> #include <fstream> void read(std::istream &fp) { while(!fp.e...
std::cin is an instance of std::istream and not derived from std::ifstream but the opposite is true. Inheritance graph of Stream-based I/O: (Taken from cppreference.com - Input/output library) So, OPs intention can be performed using a reference or pointer to std::istream. Demo: #include <iostream> #include <fstream> ...
65,108,946
65,109,147
Hash table's resizing crashes program
I'm trying to implement Hash Table in c++ using STL list of pairs. Initial maxSize I set to 1, and I'd like to increase hash table's size twice as soon as its currentSize is greater than 75% of maximum capacity. I am getting error "Cannot dereference end list operator". Here is my implementation: template<class V> clas...
There are multiple bugs in the shown code. In your rehash: it = arr->erase(it); erase() always returns an iterator to the value that follows the one that was just erased. That's how it works. So, if it already happened to be referencing the last value in arr, erase() removes it and effectively returns end(). Afterward...
65,109,114
65,178,718
Avoiding the func(char *) api on embedded
Note: I heavily changed my question to be more specific, but I will keep the old question at end of the post, in case it is useful to anyone. New Question I am developing an embedded application which uses the following types to represent strings : string literals(null terminated by default) std::array<char,size> (not...
I think that you are looking at two largely and three subtly different semantics of char*. Yes, all of them point at char but the type-specific info on how to determine the length is not carried by that. Even in the ancient ancestor of C++ (not saying C...) a pointer to char was not always the same. Already there point...
65,109,504
65,109,653
This comparison between a vector of numbers converted to a string and a string from a text file is not working?
I am trying to compare a vector of doubles to a string of numbers. In the code below I just copied a line from the txt file and put it in the vector, converted each number to a string and concantenated it. Then the program reads lines from the same txt files with the exact same format with the spacing. But, according t...
You have an extra space at the end of concanstring because of which comparison fails, you have to remove that extra space like this int main() { std::vector <int> momentum{ 5, 0 , 4 ,2 , 6 , 0 , 1 , 5 , 1 , 4 }; std::string newstring; std::string concanstring; std::ifstream datafile("thedata.txt"); for (int i = 0; ...
65,109,692
65,112,161
QT Type being defined as an int by an external library?
I am working on integrating a project into another project, and am having some build issues with QT. The issue I am getting is a line being produced in a moc file thats declares QMetaType::Bool. It says "expected unqualified-id before 'int'", followed by a couple bracket errors down the line caused by that one error. B...
The C preprocessor in C++ is an inheritage from C. Roughly speaking, it provides text replacements beyond (before) precise syntactical analysis of the compiler. (cppreference.com – Phases of translation) Due to this, the preprocessor is namespace agnostic which was not a problem in C (where something like namespaces me...
65,109,727
65,109,790
Why returning a const reference via delegation gets a segmentation fault in c++, while without the delegation just be "fine"
Consider #include <iostream> #include <utility> const auto& foo() { return std::make_pair("hi there", 2020); } int main() { //const auto& p = std::make_pair("hi there", 2020); // Okay, just warning, no segfault const auto& p = foo(); // Oops, segmentation fault std::cout << "The value of pair is:\n" ...
It's not the delegation, per se, that's the problem, but the function to which you delegate: that function returns a reference to a local object, which will cease to exist by the time the calling routine gets hold of it (or tries to). You code, taken as is and compiled with clang-cl (Visual Studio 2019) gives the follo...
65,109,768
65,381,972
Linking 2 projects together in Visual Studio 19
I have 2 projects in 1 solution both projects contain cpp/h files I am trying to have a "Base" project where the "Main" project will contain the files from the "Base". "Base" configured as Utility project hence does not actually compile anything, of course since it does contain cpp files that even if I use the VS refer...
Solved using a β€œShared Items Project” more info here https://devblogs.microsoft.com/cppblog/cross-platform-code-sharing-with-visual-c/
65,109,875
65,109,980
Extra "0" in output when factorizing a number
Write a function int fact(int n) which displays the factors of the integer n, and returns the number of factors. Call this function in main() with user input #include<iostream> using namespace std; int fact(int n); int main() { int n,factor; cout << "Enter an integer : "; cin >> n; factor = fact(n); ...
You should count in your int fact() function. Set a variable to 0 and increment each time you currently display i. Then at the end of the function instead of returning 0 return the count variable. int fact(int n) { int count=0; for (int i = 1; i <= n; ++i) { if (n % i == 0) { cout << i...
65,109,903
65,110,928
Writing a compiler backend using LLVM: return value for statements
I'm writing a basic compiler for the a subset of the C language, and I'm using the LLVM C++ api to write the backend. I'm following this tutorial mostly. I understand that each node in the AST must return an llvm::Value, that works for expressions, but what do I return for C statements? For example, for an if-else bloc...
Phi nodes represent the operation of getting a value from the union of several predecessor blocks. You will need one phi node for each value determined within the if/else, e.g. a register variable which is assigned conditionally. If you aren't using register variables or carrying them between basic blocks, then you won...
65,110,069
65,121,882
Intercepting Windows Messages from Webview2 (Edge/Chromium)
I have recently migrated a project of mine to WebView2 and the last part I can't figure out is how to intercept the Windows Messages for the webview. My code is very similar to webview/webview but I was unable to find help on their GitHub. Previously, I was able to find the hWnd for the webview and use SetWindowSubcla...
The problem is, that the real window that controls and gets all this input is in another process. You just see a window that shows the output in your process. Look into Spy++. Everything below Chrome_WidgetWin_0 belongs to a new process (MSEDGEWEBVIEW2) and is not part of your process. So you can't subclass such a wind...
65,110,131
65,110,326
Compilation error when instantiating templated std::function
I want to pass a functor that accepts a templated argument to a templated function. Something like this: // Generic translator template <typename T> int foo(T arg, std::function<int(T)> translate) { return translate(arg); } // Concrete translator int chartoint(char c) { return static_cast<int>(c); } // Call site ...
The immediate reason for your error is the fact that in int foo(T arg, std::function<int(T)> translate) T for std::function is in non-deduced context. The easiest (albeit unpleasant) way to fix would be to provide template argument explicitly: foo<char>('p', chartoint); // no compilation error here
65,110,143
65,110,967
Using typealias in place of typedef defined in class in definition
Why does this fail to compile? I am trying to reduce the amount of repetition since in the real code the class name is huge and the type is actually a very long name https://godbolt.org/z/8YarWs #include <vector> template<typename T> struct S { using type = std::vector<T>; type f() const; }; template<typena...
This is a GCC bug; the closest(1) confirmed open bug report seems to be: Bug 69348: alias declarations can not be used inside qualifiers of declarators which highlights that GCC rejects the following well-formed program: template <class T> struct X { int foo(); }; template <class T> using foo2 = X<T>; template...
65,110,442
65,110,787
How to handle the ios::failbit correctly
I tried to make a program that takes the inputs until the -1 is entered and handles the inputs properly using exceptions. It takes user inputs FirstName and Age and print the FirstName and increased age by 1. If the second variable is not an integer(age) then it should print FristName and 0. But my program gives me an ...
try using cin.ignore() like this cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); You have to include <limits> header file.
65,110,469
65,111,109
How to start a loop on a QThread
How can I start a loop on a different thread by pressing a QPushButton? The main idea is, when pushButtonStart is clicked, start a loop on a QThread, and when pushButtonStop is clicked, stops the loop in the QThread. The loop can be done by QTimer, for loop or while loop, but he needs a way to stop by pressing a button...
I have this code to create a new timer and set up a connection when it fires. This is in the Start code. checkTimer = new QTimer(this); connect( checkTimer, SIGNAL(timeout()), this, SLOT(checkTimerFired()) ); checkTimer->start(3000); My "stop running" button sets programCreated to false, and checkTimerFired starts wit...
65,110,533
65,111,531
How to reassign unique_ptr in a different scope?
I tried the following: #include <iostream> #include <memory> using namespace std; class Obj { public: Obj(int x) : x(x) {} int x; }; void func(unique_ptr<Obj> o) { o = make_unique<Obj>(new Obj(5)); } int main() { unique_ptr<Obj> o; func(o); cout << o->x << endl; return 0; } ...
You need to use a mutable reference parameter, and an "in/out" or "update" parameter. #include <iostream> #include <memory> using namespace std; class Obj { public: Obj(int x) : x(x) {} int x; }; void func(unique_ptr<Obj>& o) { o = make_unique<Obj>(5); } int main() { unique_ptr<Obj> o; func(o); ...
65,110,592
65,111,454
Is a nested class name be considered as a current instantiation when it is used in a enclosing class template
According to the rule: temp.res#3 When a qualified-id is intended to refer to a type that is not a member of the current instantiation ([temp.dep.type]) and its nested-name-specifier refers to a dependent type, it shall be prefixed by the keyword typename, forming a typename-specifier. If the qualified-id in a typenam...
Is a nested class name be considered as a current instantiation when it is used in a enclosing class template? No. However, as with many other passages of the standard, paragraph [temp.dep.type]/1.1 is indeed a mouthful: A name refers to the current instantiation if it is (1.1) in the definition of a class template...
65,110,637
65,116,464
Launching a second Linux program and exit current one from C/C++?
Is it possible from a C or C++ Linux program (say /usr/bin/foo), to programmatically launch another program (say /usr/bin/bar), and have foo exit normally and for bar to keep running? system(3) isn't suitable as it blocks until the other program completes. I'd like something that returns immediately. The programs are ...
With Qt, you can use bool QProcess::startDetached(const QString &program, const QStringList &arguments, const QString &workingDirectory = QString(), qint64 *pid = nullptr) as described here https://doc.qt.io/qt-5/qprocess.html#startDetached Here is a minimal example of how to use it : #include <QCoreApplication> #inclu...
65,110,681
65,110,810
params in overriden function-call operator() c++
I have come across this overridden function-call operator() inside a IonizationTunnel.h file: void operator()(Particles *, std::vector<double>*, unsigned int, int ipart_ref = 0) override; This matches exactly with the parameters of a virtual void operator() inside a Ionization.h file: virtual void operator()(Particle...
An unused parameter that does not necessarily need a name can be useful sometimes to let overload resolution pick the desired overload: void foo(int) { std::cout << "this is foo(int)\n"; std::cout << "I dont need a name for the argument, because I am not using it anyhow"; } void foo(double) { std::cout << "...
65,111,233
65,121,866
Is there a way to choose a random button using nana library?
So i just started using nana c++ library. I made some buttons and i need to find a function or something that choose a random button from those i created. Is there anyway i can do that? Ps: i'm using code::blocks
There's no real reason to use an extra library for the random part; the C++ standard library has the functionality already. See <random>; you'd probably want a std::uniform_int_distribution. This assumes you've got your buttons numbered; else just stuff a pointer to each button in a std::vector<Button*>. One tip: unlik...
65,111,707
65,116,684
Number of ways to distribute N items to three peoples under given conditions
I've been attempting to solve a problem that states, determining the number of ways to distribute N items to three persons. The distribution would consider best if the total weight of items the first person gets is divisible by 3, the weight of items the second person got is divisible by 5 and the total weight of item ...
The dynamic programming state that you need are three flags for whether people 1, 2, and 3 have received anything, followed by 3 numbers giving the sum of what they have received mod 3, 5, and 7. In Python I'd build up a dictionary whose keys are tuples representing the state and whose values are the counts. In C++ yo...
65,111,900
65,112,735
The command aborts unexpectedly while entering a line through the cin.getline function
The command aborts unexpectedly while entering a line through the cin.getline function 3 Manchester United 2 Ronaldo Portugal Rooney England Everton 2 Rooney England Barkley England Real Madrid 3 Figo Portugal Ronaldo Portugal Bale Wales Portugal Output: Manchester United Real Madrid using namespace std; struct footba...
That is because you have to use cin.ignore() everytime you use cin.getline() after cin>> because cin>> leaves the new line ch in buffer. Just add cin.ignore(); as a first line when you enter your first loop.
65,112,164
65,178,708
How to resolve `clang: error: unsupported option '-fsanitize=leak'` on apple devices
I am trying to run a simple leak check program. #include <iostream> int main() { double *ptr = new double(3.14); } using the command g++ -g -fsanitize=leak -o main main.cpp and I get the following error: clang: error: unsupported option '-fsanitize=leak' for target 'x86_64-apple-darwin20.1.0' I stopped u...
According to this answer you should use: g++-10 -g -fsanitize=leak -o main main.cpp (in this cases (with flag leak) there is no leak message for me ./main, but it compile) then it should be: g++-10 -fsanitize=address -g main.cpp ; ASAN_OPTIONS=detect_leaks=1 ./a.out and it detect leak well. Note, that the correct path...
65,112,264
65,112,647
How to create array of templated objects without dynamic allocation
I have been developing software driver for the SPI I/O expander in the C++ programming language. I have decided to model the registers in the I/O expander in this manner class Register { public: virtual bool read(void) = 0; virtual bool write(uint8_t data) = 0; virtual uint8_t getData(void) = 0; virt...
Dynamic polymorphism is not related to dynamic memory allocations. You can have a statically allocated object of some derived class and assign its address to a pointer-to-base. In your case, it might look as follows: Register* register_map[2]; TypedRegister<int, 0> obj1; TypedRegister<long, 1> obj2; register_map[0] =...
65,112,480
65,122,075
May I use cli() and sei() in the interrupt?
May I use cli() and sei() like this: ISR(EXT_INT0_vect) { cli(); MyFunction(); sei(); } I heard that it is forbidden. Is it or I can use cli() and sei() like above?
Calling cli() and sei() manually (like in your example) is redundant if you want normal interrupt behavior. That is, because AVR automatically clears the global interrupt flag before the ISR is executed. There are rare use cases for nested interrupts, where you may want to manually re-enable interrupts using sei() with...
65,112,626
65,112,747
How to emplace to a std::vector of std::array?
With a vector of vectors, I can do this: std::vector<std::vector<int>> vov; vov.emplace_back(std::initializer_list<int>{0, 0}); However, the equivalent fails for the vector of std::array: std::vector<std::array<int, 2>> voa; voa.emplace_back(std::initializer_list<int>{0,0}); What is the correct way to emplace an arra...
std::array doesn't have any constructors, it's initialization follows aggregate initialization. You have two options, either use push_back instead of emplace_back with a brace-init-list: voa.push_back({ 0, 0 }); Or you can use std::array's (implicit) copy and move constructors and construct a temporary std::array: voa...
65,112,706
65,112,918
Build a QImage from a buffer
How I can build a QImage from a buffer for example? In this case I'm using a buffer of 3x3 with vale from 0 (black) to 255 (white). 0 255 0 255 0 255 0 255 0 and it is store into a unsigned char buffer[9] = {0, 255, 0, 255, 0, 255, 0, 255, 0}; At the moment I'm trying this but doesn't work: QImage image{buffer, 3...
The constructor you're using... QImage(uchar *data, int width, int height, QImage::Format format, QImageCleanupFunction cleanupFunction = nullptr, void *cleanupInfo = nullptr) has the caveat... data must be 32-bit aligned, and each scanline of data in the image must also be 32-bit aligned Hence the QImage implementa...
65,112,844
65,112,927
Why does member assignment fail in initializer list but not in the constructor?
I am writing code that follows the member dependency schemes discussed in: Resolve build errors due to circular dependency amongst classes In it's simplest form, the code headers looks like this: A.h class B; class A{ public: A(); void send(int i); B* b; }; B.h #include A.h #include foo.h class B : public f...
In your assignment: b = new B(this); you are constructing a B object from this, and assigning a pointer to this object to b. You need to do the same thing in your member initializer list: A::A() : b(new B{this}){};
65,112,952
65,113,136
Check if theres a point that lies outside of circles
So i'm trying to make an console application that checks if it has any N(x,y) points outside of n circles. So the program work perfect when there is one circle. But when i enter more than one circles, its not working properly. Here is my code: #include <stdio.h> #include <iostream> #include <cmath> using namespace std...
The not so relevant parts removed your loops are basically this: for(int i = 0; i<brToc; i++) { outside = false; for(int j = 0; j<n; j++) { dx = ...; dy = ...; r = ...; if(pow(dx,2) + pow(dy,2) > r) { outside = true; break; } } if(outside) cout << "Point: " << i+1 << " is outside \n"; ...
65,113,025
65,113,160
Multiple template functions with enable_if and is_same and with missing argument list of the class template in C++
I have the following code which compiles nicely: #include <iostream> struct Res {}; struct Jac {}; template <typename T, typename S> class A; template <typename S> class A<Res, S> { public: A() { std::cout << "A<Res, S>" << std::endl; } }; template <typename S> class A<Jac, S> { public: A() ...
You can change foo to accept a template template parameter CT that is templated on two types, and enable_if the specific overload based on whether CT<Res, S> is the same type as A<Res, S>, or B<Res, S>: template<typename S, template<typename, typename> typename CT, std::enable_if_t<std::is_same<CT<Res,S>, A<Res,S>>...
65,113,267
65,113,544
Brace-enclosed initializer for matrix constructor fail in type std::complex<double> >
I implented a contructor for my matrix class to do brace-enclosed initialization using nested std::initializer_list. The constructor works fine for primary type: `int`, `double`; but renders error-reading for `complex`. How to fix this error reading? The matrix class template <typename T> class xxx { public: ...
Your problem is not related to the initializer list. The problem is that this code #include <iostream> #include <complex> int main() { std::complex<double> x = (1,2); std::cout << x; } Is not doing what you expect it to do. Output is (2,0) Because (1,2) is the comma operator at work. std::complex<double> x =...
65,113,490
65,113,562
this program receive numerical input and stores and when the input is 42 ,it stops receiving the inputs and prints the stored received input
Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely… rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits.
You are not using the std::vector correctly. You are trying to read input into vector elements that do not exist yet. You would have needed to resize() the vector first for that to work. But since you don't know up front how many input values will actually be entered, you will have to instead read the input into an i...
65,114,431
65,114,580
Does it makes sense to call sync() on output-only fstream?
I found some legacy company code that was using an std::fstream and calling fs.flush() after each write, then fs.sync() each time a certain amount of data were written to the stream. This code only needs to do output operations, not input ones. std::fstream fs(filename, ios::out | ios::binary); fs.write(buff, size); fs...
If you look at http://www.cplusplus.com/reference/fstream/fstream/ you will find sync under the heading "Public member functions inherited from istream" and its description is: Synchronize input buffer Synchronizes the associated stream buffer with its controlled input sequence. So no, this is not needed for output-o...
65,114,434
65,114,729
Use Python 3 in OpenWRT Build System
Trying to create OpenWRT build system for Omega linux on chip device according to manual on my Ubuntu 20. Got error below while run make menuconfig ... Checking 'python'... failed. ... Build dependency: Please install Python 2.x My system has Python 3 while manual asks to install Python 2. How to solve this problem?
Since Python3 is not backward compatible you need to provide Python2 for installation. Follow this instructions to create an isolated Python2 environment in your system: Install Python2 (add repository if needed): sudo apt install python2 Install pip (package manager): curl https://bootstrap.pypa.io/get-pip.py --o...
65,114,480
65,114,481
How can I get an element from within a ListViewItem's ItemTemplate?
I have a ListView that uses a custom ItemTemplate (doesn't everyone?): <ListView> <!-- ... --> <ListView.ItemTemplate> <DataTemplate x:DataType="x:String"> <MyGreatControl Thing="{x:Bind}" /> </DataTemplate> </ListView.ItemTemplate> </ListView> MyGreatControl today has extensive keyboard handling c...
You want to use ContentTemplateRoot! MyGreatControl^ GetMyGreatControlFromListViewItem(ListViewItem^ listViewItem) { return safe_cast<MyGreatControl^>(listViewItem->ContentTemplateRoot); } This also works for any arbitrary elementβ€”if you have a StackPanel, for example, ContentTemplateRoot will return the StackPanel ...
65,114,864
65,115,875
How can a class be made (partial) owner of a pointer given a function that returns a unique_ptr
This question is a follow-up to Why doesn't returning a std::unique_ptr violate unique_ptr's deleted copy constructor? (which is answered here: Returning unique_ptr from functions ) This leads me back to the original problem I'd faced. I have to work with a function (outside my control) that returns a std::unique_ptr. ...
The constructor in your top example tries to copy the unique_ptr but a unique_ptr isn't copyable. You need to move it instead: #include <utility> //... PtrOwner(std::unique_ptr<int>&& p) : p_(std::move(p)) {} There's nothing partial about the ownership though. PtrOwner is now the owner. Period. To get a reference to...
65,115,018
65,115,596
The results for the sum of the rows is correct, but the sum for the columns gives wrong results for a 3 x 4 array
I am trying to make a program where the sum of the rows and columns are counted individual, the rows turn out fine, but the columns is giving weird results. The correct result is suppose to look like this (example Matrix) 9 1 2 4 2 2 8 0 3 3 3 3 Sum of row 0 is 16 Sum of row 1 is 12 Sum of row 2 is 12 Sum of column 0 i...
I'm gonna do something I shouldn't, but you've put enough effort into this that I want to show you where the issues are with an answer that works: #include <iostream> using namespace std; // Use Constants to declare the size of your array to make it easier to iterate in loops. // Also allows the compiler to know at c...
65,115,075
65,115,147
How do I find info about a class in a complex C++ code?
I am trying to understand a complex set of .cpp / .h files which are assembled into a Physics code. Inside one .cpp file, there is an overloaded function call operator() which reads: void IonizationTunnel::operator()(..., Patch *patch, ...) { ... ... double ran_p; ran_p = patch -> rand_ -> uniform(); } ...
If you are using Atom, you can try to click on "Find", then "Find in project", and then try the expression "Random" or "class Random" or "struct Random". Other IDEs should have similar functionalities (see comments to the question).
65,115,108
65,131,284
Problem with getting OpenCV image data to C#
So I'm fairly new to C++, and I tried to use it to read images using the OpenCV library. My idea was to put the C++ code in a DLL and then get the decoded image by calling the DLL from a C# script (I need the image in C#). I looked arround a bit on what would be the best way to send the bytes to C#, and saw that most p...
Ok, nevermind, turns out it actually makes more sense to just return the unsigned char* from the C++ function and then convert it in C#. If anyone else has problems with this, here's the thread I found this answer on (Thanks to Louis.fr). Here are the methods I ended up using: In C++: unsigned char* GetUnsignedBytes(ch...
65,115,466
65,115,829
Throw error on max instantiations of class
I want my program to throw an error when a defined maximum number of objects of a certain class (MAX) is reached. I must limit the number of instantiations because I'm working with a framework that provides a limited amount of resources. Currently I have the following (simplified): class Resource { private: sta...
I will answer the general question, without considering any of the details of the application. Is the use of std::domain_error recommended or should I use another type? Or should I not throw an error at all and follow a different approach? Regarding which exception to throw: std::domain_error specifically has to do w...
65,115,505
65,115,594
If a function returns a std::unique_ptr, is it reasonable to assume each returned value is to a new object?
I'm learning about std::unique_ptr, trying to grok what it represents. Given a function (out of my control) that returns a unique_ptr, is it implied/well understood that each invocation returns a unique_ptr that points to a new object (different than any prior invocation)? By way of example, the following code produces...
It should be assumed that, if a function returns std::unique_ptr<T>, then the returned smart pointer points to an object that is not currently managed by anyone else. This does not necessarily mean that it always refers to a different object. So long as this convention is followed, double-free bugs will be avoided. If ...
65,116,035
65,121,622
DXGI AcquireNextFrame receives the next frame only after 20ms (50fps), is it possible to speed up to 10ms?
Good afternoon. I'm writing a program that would record video from the desktop at 100 fps, but I ran into a problem, AcquireNextFrame receives the next image from the desktop only after 20 ms, because of this, the maximum fps that I can get will be 50, you can do something with this? Thanks.
IDXGIOutputDuplication::AcquireNextFrame will receive nothing if nothing changes on the captured output. It's not like a "PleaseCaptureScreenNow" command. Timouts are expected and must taken into account. That's why you can't really design a workflow for example like capture => convert => copy/encode on just one unique...
65,116,511
65,116,659
What is the output of the following code? (exception handling c++)
Student here. I am trying to learn the basics of the exception handling in c++ and a got a piece of code which confuses me. Can someone please explain me why the output is 120 ? Also, I don't understand why i have in the body of the exec() func { X, x}. What does {} do here? Thank you ! #include <iostream> #include <st...
If you actually run the code, you will see the output for yourself: 120 Live Demo What is happening is this: main() enters the try block and calls exec(). exec() creates a nested scope, creating and destroying an X object in that scope. The constructor and destructor of that object print to cout, so you see 1 and 2...
65,116,648
65,116,718
Why is list::remove_if() giving me an error?
I was making a chess engine and I have a list of moves. std::list<Move> moves; I also have a function that checks if the king is under a check after a specific move. bool Board::check_after_move(const Move& move) { Board temp=*this; temp.DoMove(move); return temp.check(); } After I generate possible moves...
check_after_move is a non-static member function, so you cannot make a basic function pointer from it. The easiest general solution is to pass a lambda that captures this: moves.remove_if([this](const Move& move) { return check_after_move(move); }); Or you can bind the this pointer directly: moves.remove_if(std::bind(...
65,116,650
65,140,287
How to use "pessimistic" Couchbase locking with the C API?
This is incredibly frustrating... I'm using the Couchbase v3 C API, and I ran into a problem that would be solved perfectly by using their "pessimistic" locking. After much effort I believe I've finally figured out how to lock records using it (with lcb_cmdget_locktime(), which presumably takes a parameter in microseco...
Thank you for question Time in seconds, note that the server might reset time to default, if it larger than maximum time (both durations are configurable). The following command will help to discover effective values for the feature. $ cbstats -u Administrator -p password localhost all | grep ep_getl ep_getl_default_t...
65,116,704
65,116,920
Why is compiler optimisation breaking my code?
I was having some issues with this code. It was working in debug mode but would erroneously output 0.0 for some of the csv lines in release mode. It was only when I added the preprocessor commands that turn off optimisation around line 19 that everything started to work in release mode. Does anyone have any insight ...
Your input vector is not being initialized as you expect. It always has size two, and all the strange results you observe are a result of Undefined Behaviour due to reading the vector out of bounds. You could have found this with your debugger, or by checking against input.size() or using input.at(i). It turns out that...
65,116,756
65,116,842
Function argument explanation
void print(std::ostream& out=std::cout) const { for(int i = 0; i < _items.size(); i++) { out << _items[i] << " "; } } What does the std::ostream& out=std::cout in the function's argument mean?
std::ostream& is the type of the parameter, a reference to a std::ostream object. out is the name of the parameter =std::cout means that the default argument for the parameter is set to std::cout Thus, you can call print as: print() and the argument will be std::cout by default
65,117,087
65,117,190
adding or converting between cv::Point3d and cv::Vec3d
Since they both have three elements, it seems logical to have a overloaded addition operator to add between the two types. Or would this not make sense from a design point of view? But since that doesn't exist, we have to convert Vec3d to Point3d first. This link mentions there's a way to convert them but I don't see i...
cv::Point3_<T> has a constructor which takes a generic cv::Vec<T, 3>. Note that Point3d and Vec3d are just typedefs with T = double. So it should be possible to simply do cv::Point3d p{v}; // or p(v) or p = v; you get it. // ...
65,117,186
65,141,076
Qt5 create an exe file
I'm trying to create a Qt5 executable on Windows, when I built the project from QtCreator and went to the build folder and started the .exe I received a lot of missing library errors, and I fixed it using windeployqt: >C:\Qt\5.15.2\msvc2019_64\bin\windeployqt.exe App.exe Then I had another problem: The application was...
There's a description for this process (which is called deployment) in the Qt manual, e.g deployment with windeployqt, you might also look at the Qt Wiki for manual deployment. BUT: It looks as though you mixed up something in you application: Visual C++ Redistributable Packages are needed in case you compile your appl...
65,117,640
65,118,136
Different syntax of passing an array to a function in C++
#include <stdio.h> void test2(int (&some_array)[3]){ // passing a specific sized array by reference? with 3 pointers? } void test3(int (*some_array)[3]){ // is this passing an array of pointers? } void test1(int (some_array)[3]){ // I guess this is the same as `void test1(some_array){}`, 3 is pointless. } int...
void test2(int (&some_array)[3]) This is passing a reference to an array of 3 ints, eg: void test2(int (&some_array)[3]) { ... } int arr1[3]; test2(arr1); // OK! int arr2[4]; test2(arr2); // ERROR! void test3(int (*some_array)[3]) This is passing a pointer to an array of 3 ints, eg: void test3(int (*some_a...
65,117,652
65,117,773
Visual Studio community 2019 cannot add cpp files to project
file browser Installation details Main problem: I have created a new, empty project and I want to populate it with pre-existing .cpp files and a header file, but the file browser does not allow the .cpp or .h extensions to show. Possible cause 1: I think it might be the installation details Possible cause 2: I hav...
In Solution Explorer, right-click on your project and select Add β†’ Existing Item... (You have probably clicked on the solution itself rather than on the project.)
65,117,849
65,118,344
Creating a vector in class then using class object in function not working
I have a class Employees. I'm trying to make the user insert and delete an employee but it's not working. The size of the vectors should be 500. class Employees{ public: int maxx = 500; vector<string> Surname; vector<string> FirstName; vector<string> birthdate; int vacation[500]; public: Employe...
There are a lot of things wrong with this code. But the particular issue you are asking about is caused by your functions passing the Employees object by value, so a copy is made, and any changes you make to the copy are not reflected in the original object in main(). You need to change the parameters to pass the Empl...
65,117,893
65,117,959
Why std::queue requires the element to be copyable?
In the code below std::deque compiles, but std::queue does not: class A { public: explicit A(int a) : m_a(a) { ++count; } ~A() { --count; } A(A const &) = delete; A(A && other) : A(other.m_a) { other.m_moved = true; } A & operator = (const A &) = ...
Elements are copied when you construct queue from deque, but you've deleted copy constructor for deque's value type (A). So you need to move d when constructing queue. ... int main() { std::deque<A> d; std::queue q(std::move(d)); // added std::move q.push(A(1)); return 0; }
65,118,156
65,119,459
Extended Inline Assembly in C++: Is it necessary to preserve volatile registers?
I am analyzing the following snippet of extended inline assembly code that returns the sum of two numbers given as parameters into a function. int addAB(int a, int b){ int result; __asm__( "movl %%ebx, %%eax;" "addl %%ecx, %%eax;": "=a" (result) : "b" (b), "c" (a) : "cc"...
There is really just one rule to know: If you modify any(*) register, you must tell the compiler about it, either by declaring that register as an output operand, or by listing it as a clobber. That's all. It doesn't matter whether the register is "volatile" (aka caller-saved) or not. And if you do inform the compi...
65,118,167
65,118,243
Condition inside if-statement not being satisfied, but is still executing
So mostly everything is starting to work with my vector class but I've run into one more small problem. Inside of my overloaded == operator, I have an if-statement that is executing even though it shouldn't be. Here it is, bool myStringVector::operator==(const myStringVector& data){ std::cout << this->size() << " "...
You are comparing C strings (const char*) with each other. This does not compare the contents of the strings, but rather the locations in memory where they are stored. You can use strcmp to compare them as follows: bool myStringVector::operator==(const myStringVector& data){ if(size() != data.size()) return f...
65,118,370
65,242,227
Compile with /MT flag from command line using cmake
How can I add the '/MT' flag from the command line using cmake? Can I simply go cmake -D CMAKE_CXX_FLAGS="/MT" ..? In the tutorials I've found online, I see people setting CMAKE_CXX_FLAGS_RELEASE and CMAKE_CXX_FLAGS_DEBUG separately and haven't seen any examples with setting it from the command line.
Did some testing, it did not work with cmake -D CMAKE_CXX_FLAGS="/MT" .. but worked with cmake -D CMAKE_CXX_FLAGS_RELEASE="/MT" .. I verified the resulting library using dumpbin.
65,118,449
65,118,670
Why is QueryInterface() returning E_INVALIDARG?
I was coding a project and I came across a bug where QueryInterface() was returning E_INVALIDARG, I don't know which argument is invalid because both arguments are simple enough, am I overlooking something simple or what? The bit that that is failing comes from Microsoft themselves specifically documentation, if I'm do...
There are only 2 parameters to QueryInterface() for E_INVALIDARG to complain about, and offhand they look fine to me inside of your CreateSecondaryBuffer() function. The 1st parameter is being passed a hard-coded IID, so the problem has to be with the 2nd parameter, which expects to be passed a pointer to (in this cas...
65,118,817
65,119,831
Setting up VScode for C++ and I get redirected to settings.json every time I try try to hit debug
I've already installed and set up all of the necessary technologies to make C++ run in VScode, including the C/C++ debugger extension, the C/C++ compiler extension, the coderunner extension, and minGW. I'm using Visual Studio Code version 1.51.1, C/C++ extension version 1.1.2, C/C++ compile and run extension version 1....
I have minGW and VS Code setup on my windows. You can try my setup and see if it solves your issue of debugging. Inside your project folder make another folder .vscode and add these three files : tasks.json launch.json c_cpp_properties.json In launch.json edit "miDebuggerPath": "<your_path_to_debugger>\\gdb.exe" In c...
65,118,931
65,120,196
Newton Tangent method in C++
So I have to write a Newton tangent programm with the starting point 1.0. I have to show the iteration count and the root that result at the end. If I type in 100 for U0, the root/result should be 2,499204 but somehow it shows me 17.3333 and just one iteration count which i dont think is the correct result. I don't kno...
fabs(xn-xn1)>epsilon is always false as prior code does xn=xn1; @user4581301 Changing to ... double delta; // add do { i++; xn1 = xn - f(xn)/fstrich(xn); delta = xn-xn1; // add xn=xn1; cout<< "Iteration count: "<<i << " " << xn<< " " <<endl; //} while (fabs(xn-xn1)>epsilon); } while (fabs(delta)...
65,119,121
65,119,269
How to insert into an array given a position using std::move_backwards
I am trying to implement insert function using std::move_backward. I found this code on cplusplus.com. I don't quite understand how std::move_backward work. #include <algorithm> // std::move_backward #include <string> // std::string int main () { std::string elems[10] = {"air","water","fire","earth"}; //...
If you want to insert ether into the second position, simply change the range that you are moving backwards to not include the 0th position: std::move_backward(elems+1, elems+4, elems+5); // ^^ ignore 0th position elems[1]="ether"; // insert element at at 1st position Here's a demo
65,120,130
65,120,492
Is std::begin on an empty std::valarray undefined behavior?
I was playing around with std::valarray and UndefinedBehaviorSanitizer, and noticed that std::begin an empty std::valarray causes undefined behavior. Here is the code: #include <valarray> int main() { std::valarray<int> a; std::begin(a); } To reproduce, compile the code with g++ -fsanitize=undefined and run t...
n4659 - C++17 final working draft Β§26.2.1 General container requirements [container.requirements.general] Table 83 β€” Container requirements a.begin() - no precondition so a.begin() must be valid on an empty container. However valarray is defined in Β§29.7 Numeric arrays [numarray] from the Β§29 Numerics library [numeri...
65,120,172
65,120,498
move sematics in thread wrapper class with RAII in C++
I am trying to get a RAII wrapper class around std::thread to work in C++. #include <iostream> #include <thread> #include <vector> using std::cout; using std::endl; void threadFunction() { for (int i = 0; i < 20; ++i) { cout << "thread function pointer executing..." << i << endl; } } // RAII wrappe...
It may not look like it at first glance, but t2 is a function prototype, not a variable declaration (search for "most vexing parse"). You can change it to a variable by adding some parentheses: ThreadJoinRAII t2((std::thread(threadFunction))); then it will call your ThreadJoinRAII constructor.
65,120,445
65,120,505
How to correctly store the result of arithmetic operations on int type to double type and different types in C++?
I have two times stored in int type in a struct and want to calculate the no. of hours elapsed in between two times. How do I correctly store the result of in a double variable. I seem to get the difference wrong. Also how do I store the result up to two places after the decimal point. This is my code : struct time { i...
The error is because this expression (t2.min+t1.min)/60 will return int. That's because (t2.min+t1.min) is of type int and 60 is of type int. Hence \ will be an integer division operation. To resolve it you can convert your (t2.min+t1.min) to the double with static_cast<double>(t2.min+t1.min). See more about static_cas...
65,120,508
65,120,585
How to call vector function from main() in C++?
I'm trying to call the vector function 'twoSum' which is inside the class 'Solution' but is giving me 'Expected variable name or 'this' in lambda capture list' error when I'm trying to call the function. Here's the code: #include <iostream> #include <list> #include <vector> using namespace std; class Solution { public...
In C++, you can't create a std::vector with a [1, 2] expression. The most similar thing will be implicitly creating an instance of std::vector by list initializer with {1, 2}. See more about this in std::vector and std::initializer_list documentation. Also, there will be an issue with passing to the function. Because r...
65,120,716
65,120,744
Integer literal for fixed width integer types
Is there some c++ proposal for Integer literal for fixed width integer types like this? // i's type is unsigned int auto i = 10u; // j's type is uint32_t auto j = 10u32;
Yes: P1280R0 Integer Width Literals (published 2018-10-05). It proposes the following literals: namespace std::inline literals::inline integer_literals { constexpr uint64_t operator ""u64 (unsigned long long arg); constexpr uint32_t operator ""u32 (unsigned long long arg); constexpr uint16_t operator ""u16 (unsig...
65,121,003
65,121,031
Terminate called after throwing an instance of 'std::out_of_range when comparing characters of binary number input
I am pretty new to coding and encountered the following error. terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::at: __n (which is 6) >= this->size() (which is 6) Aborted (core dumped) The code for the following was: #include <iostream> #include<algorithm> #include<string> usi...
The second input is read 100101, because of the leading zero. Trying to access as many characters as 1010100 has will go beyond its length. To solve read both in as string. E.g. like the following (note that the code only demonstrates the change I propose, it is still vulnerable by differently long input like 100 10 an...
65,121,282
65,124,248
Execute function only once every pc session (pc start)
I have a driver that I haven't made and I manual map it. Say the function is ManualMap(); as an example. That function gets called everytime I run my program. It's basically in main(); Now what I want to do is to make that function only be called once every session. So if PC was restarted, that function will be called,...
You will have to use canary. The simplest way to do this is to create a file on disk each time you run ManualMap(). Then you need to make sure that when your computer is started that file gets deleted. This will be OS-dependent. You create a script that will delete the file and then make sure it runs on startup (Window...
65,121,303
65,490,282
c++ - How would I detect if the middle button is held down?
Is it possible to detect if the middle button is being held down in c++? I saw this question, but it did not mention anything about listening for buttons except the left mouse button. I want int main(){ while (1){ while((GetKeyState(VK_LBUTTON) & 0x100) != 0){ mouse_event(MOUSEEVENTF_LEFTDOWN | ...
You are specifically asking about how to do something for the middle mouse button which you have only found explained for the left mouse button. (At least you stress that very much, though I do not see how the shown code is applicable....) So when searching for MOUSEEVENTF_LEFTDOWN and VK_LBUTTON I found that e.g. here...
65,121,335
65,199,302
How to manualy set white balance of a uEye camera?
How can I programmatically set the white balance of an uEye USB camera (from the IDS manufacturer) to work with no automatic white balance and pre-defined multipliers when is_SetWhiteBalanceMultipliers() function is obsolete? Some background: I work with a uEye USB2 camera (from IDS) connected to Linux machine. I need...
I had the same issue. I think you can achieve the old result using the function "is_SetHardwareGain" on which you directly pass the main, red, green and blue gains. In my case I disabled the white balance before doing it just to make sure it works. In this example, I wanted to set the values to RGB gains = [8%, 0%, 32%...
65,121,668
65,180,594
Convert NV12 to BGR by NVIDIA Performance Primitives
I'm trying to convert NV12 image to BGR by npp, but in the final array i have zeroes. int lumaStepBytes, chromaStepBytes; int rgbStepBytes; auto dpNV12LumaFrame = nppiMalloc_8u_C1(dec.GetWidth(), dec.GetHeight(), &lumaStepBytes); auto dpNV12ChromaFrame = nppiMalloc_8u_C1(dec.GetWidth(), dec.GetChromaHeight(), &c...
the problem went away when I changed the video card. GeForce 740 to 1080
65,121,754
65,124,082
Best practice to build C++ program with optimization while keeping debugability in production env
I am writing a C++ server program that will be deployed to *nix systems (Linux/macOS). The program sometimes runs into segfault in production environment, and I would like to collect some information like core dump file. But I have no idea what the best practice is for doing this: I would like to make the program perf...
This will be a rather general answer. If you are still having reliability issues then go with RelWithDebInfo. Alternatively, you can override -O2 optimization to get compiler to optimize all the way. You need to strip when debug info is present. This doesn't change any of the stuff that actually gets executed, but rem...
65,121,768
65,122,378
Using MOCK functions in another class
I try to isolate my class, so because of the exchanging external free functions with mock implementations, because of that, I have created my mock class for free functions, which had external dependency in another class. So how will I call this mock functions in my class? Is there any implementation you can suggest to ...
IMO using unique_ptr is a way to go if you want to have one owner of this mock class, and the owner is the class under test. See this post which shows how to use unique_ptr is such context. However, for simplicity, I'd suggest to start of with regular references - it will be easier at the beginning. Regarding your impl...
65,122,176
65,122,522
C++ value as map: Value is not updating in second map
I have a std::map with value as another map. I want to update the value of inner map. When inner map values is update and print immediately, it shows the updated value. But after that when a display function is called, it doesn't show the updated value. Not sure what I'm missing. #include <iostream> #include <map> typ...
The problem is on this line: for(auto search: a.s.apnPoolValidationDb) this is a ranged-for loop over the key-value pairs in the outer map. But note the variable declaration! Your search variable is declared as an auto, not an auto&. So, you're actually making a copy of the inner maps in each iteration of this loop. Y...
65,122,618
65,122,883
how to make g++ ignore calloc pointer type error when compiling c code
For example, the line below compiles ok with gcc, float *m = calloc(rows*cols, sizeof(float)); but g++ complains about the pointer type mismatch like below. ../../../../../YOLO/darknet/src/gemm.c:33:22: error: invalid conversion from β€˜void*’ to β€˜float* (maybe callc always returns void* in c++?) Can I make g++ just i...
The solution to this problem is actually not to add a static_cast as eerorika suggests but compiling the C code with a C compiler. There are a number of subtle differences between C and C++ that can lead to unexpected results, and the compiler won't catch them all. So even if you change all the type warnings you might ...
65,122,780
65,122,821
Why do I get an error in this code when using "using namespace std;" and "bits/stdc++.h"?
Actually this code works fine in "DEV C++", but when I put it into my "Hacker-Rank" panel it gives this error "reference to function is ambiguous", although all the online compilers are giving errors... I don't think here function overloading is somewhere interrupting, because this error mostly comes in function overlo...
For starters this else code block else{ function(n); } returns nothing. Though it is allowed but confuses readers of the program because they expect that if there is an explicit return statement in the if sub-statement then a similar return statement should be in the else sub-statement. It seems the name function ...
65,122,951
65,124,540
Set of Pairs program in C++
I am making a set of pairs of Max and Min elements of Every Subset in an Array.But its giving me these errors. And at last I need Size of set. (Edited with some suggestions) In function 'int main()': 27:12: error: 'max_element' was not declared in this scope 27:12: note: suggested alternative: 'max_align_t' 28:12: erro...
To make your last programme works, it was needed to move the declaration of std::vector<int> v; Moreover, your code has a complexity O(n^3). In practice, it is possible to get a complexity O(n^2), by calculating iteratively the max and min values. This code compares your code and the new one. The results are identical....
65,123,184
65,134,765
EFI Memory Map returns 0 sections of EFIConventionalMemory
As stated in the title, getting the EFI Memory Map in a UEFI bootloader is yielding no sections of EFIConventionalMemory. If I'm not mistaken, this should be the majority of the memory? It is returning this on both QEMU and on real hardware. Setting QEMU to have 2GB RAM causes a memory segment of ACPIReclaimMemory to b...
The memory type list was incorrect. Here is the correct EFI_MEMORY_TYPE_STRINGS: const char* EFI_MEMORY_TYPE_STRINGS[] { "EfiReservedMemoryType", "EfiLoaderCode", "EfiLoaderData", "EfiBootServicesCode", "EfiBootServicesData", "EfiRuntimeServicesCode", "EfiRuntimeServicesData", "EfiConventionalMemory", "EfiUnusableMemor...
65,123,615
65,135,616
boost::program_options::options_description doesn't work for simplified command name
#include <boost/program_options.hpp> namespace bpo = boost::program_options; int main(int argc, char* argv[]) { int apple_num = 0, orange_num = 0; std::vector<std::string> addr; bpo::options_description opt("all options"); opt.add_options() ("apple,a", bpo::value<int>(&apple_num)->default_valu...
The chosen commandline style doesn't expect the equals-sign with short options: ./sotest -a=99 error But ./sotest -a 99 apple count:99 orange count:20 sum:119 To fix the expectations: auto style = bpo::command_line_style::default_style | bpo::command_line_style::allow_long_disguise ; bpo::store(parse_comma...
65,123,698
65,127,444
How can I get the c++20 std lib?
How do I get sys_seconds? I use /usr/bin/c++ on Ubuntu 20.04 to compile following snippet: RCLCPP_WARN_STREAM(get_logger(), "Time: " << std::chrono::sys_seconds(time_.seconds())); and I get following error: error: β€˜sys_seconds’ is not a member of β€˜std::chrono’; c++ output is: c++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0 ...
according to https://en.cppreference.com/w/cpp/compiler_support c++9 supports c++20 That's not what the linked page says. On your system, c++ is linked to g++ by default. The linked page says that some C++20 features are implemented in GCC 9, while many features are not. How can I get the missing c++20 std lib? By ...
65,123,708
65,124,089
Can't create atomic with ()
I was trying to create std::atomic_bool objects in different ways: std::atomic_bool f1 = false; // OK std::atomic_bool f2 = {false}; // OK std::atomic_bool f3{false}; // OK std::atomic_bool f4(false); // ERROR: expected identifier before Β«falseΒ» Why the last one does not work? P.S: compile with g++ -std=c++20....
You can't initialize a member variable with parentheses, because that must be a member function declaration according to the grammar. This syntactic quirk did not cause any issues until it became possible to write member initializers in the variable's declaration.
65,123,826
65,124,263
Proper use of std::sort in c ++
for example I have a string data with the following contents std :: string words {"armando dippet"}; if using words.begin () / end () then it works, but if std :: string words [] {"gandalf", '"harry", "malfoy", "ron"} using std::sort(words.begin () / end ()) does not work, but must be changed to std :: sort (std :: be...
Going backwards std::string * dynamic_length {new std :: string [2] {"hermione", "aziz"}}; Pointers are not arrays. They don't have a length, so you will have to record that elsewhere. std::sort(dynamic_length, dynamic_length + 2); Arrays lack methods. They are only an contiguous sequence of values. The array type ho...