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 |
|---|---|---|---|---|
62,689,753 | 62,691,061 | Why does: comparison of integers of different signs only happen sometimes? | SOLUTION: Check if people have installed a custom compiler.
Solution extended: I had only compiled on servers and not locally on my machine, when I did that I could reproduce the answer of @A.K.
The compile on the servers are custome versions of g++ and clang++. Sorry for wasting peoples time :( The compilers will be d... | I cannot reproduce your issue with g++ 8.1.0. I always get an Error/Warning if I try to compare an int (which is signed by default) with size_t (which is unsigned by default). Which is to be expected since int is defined as signed by default: https://de.cppreference.com/w/cpp/language/types
The same happens (of course)... |
62,690,082 | 62,693,220 | Why does this boost mp11 mp_count_if_q code always return 0? | I wonder why the following code does not work as expected(is_numeric is always 0).
#include <type_traits>
#include <utility>
#include <boost/mp11/algorithm.hpp>
#include <boost/mp11/bind.hpp>
#include <boost/mp11/tuple.hpp>
using namespace boost::mp11;
using NumericTypes = std::tuple<short, unsigned short, int, unsig... | You are comparing against std::remove_cvref<T>, which itself is a type and rightfully not a numerical. But I assume you want to test against the type produced from the trait: std::remove_cvref<T>::type, or better std::remove_cvref_t<T>.
Now
template<typename T>
static constexpr int is_numeric = mp_count_if_q<NumericTyp... |
62,690,329 | 62,690,488 | Force using implicit cast in assign opertor | In following code is there any way to force on compiler using implicit cast to bool (in b3 = b2 assignment) instead of generating copy assignment operator without using cast operator? Unfortunately after explicit deleting copy assignment code does not build. Lack of explicit casting is important for my framework.
class... | Explicitely deleting the assign operator means that you want the class to be non copyable. Here, you just want the copy assignment to use a bool conversion:
Base& operator=(const Base& other) {
*this = static_cast<bool>(other);
return *this;
}
Unfortunately, you will have to override the assignment operator in... |
62,690,548 | 62,691,137 | Random Numbers aren't reaching limit | I am creating a random number generator for numbers between 110,000 and 320,000. When I run it, no numbers are above 150,000. Is there some way to make sure that numbers above 150,000 are generated? Even generating thousands of numbers do not work. I am aware I have lots of things included. Here is the code:
#include <... | As noted by John. You could use more recent random number generators easier to manipulate.
Adapting the code from C++ Reference about uniform_int_distribution
for your use case is straightforward:
#include <iostream>
#include <random>
int main(void) {
std::random_device rd; // Will be used to obtain a seed for th... |
62,690,778 | 62,692,110 | How to list UTF encoded filenames in a given directory in CPP? | I'm trying to get all the files in a given directory, under Windows 10, using a CMake based CPP project (VS compiler).
I can't use boost or other libs.
I'm using the following function
string search_path = "D:\\*.*";
WIN32_FIND_DATA fd;
HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd);
... | If you have c++17 you could also try with standard library solution
for(auto& p: std::filesystem::directory_iterator("D:\\")) {
std::wstring file_name = p.wstring();
}
|
62,691,028 | 62,692,805 | Why do we declare the size of a single or a multi-dimensional array as a constant value? | Ever since I started the competitive programming, I always found that people always used to initialize the single or 2D arrays based on a constant maximum value from the maximum value of the input specification.
But I've always wondered why people do that when you can initialize the array based on the input.
For exampl... | The 3 methods have their own advantage and disadvantage. The choice depends on the goal.
First method: a static storage duration array
The array last for the duration of the program execution,
Memory allocation is performed at program start up (probably by the os), and is very cheap
It does not provide value semantic.... |
62,691,155 | 62,691,449 | Show type of param in template | I'm trying to get my head around reference collapsing (item 28 on https://www.amazon.com/Effective-Modern-Specific-Ways-Improve/dp/1491903996), and want to play around with feeding different things to a template.
I call the template with lvalue and ravlue, but I don't see the exact types in the template. How can I get ... | Really great book. Seems like you have jumped many chapters though.
In Item 4, you would see how you could do that with Boost.TypeIndex, with:
std::cout << boost::typeindex::type_id_with_cvr<decltype(param)>().pretty_name();
|
62,691,294 | 62,695,845 | Boost Spirit X3: error: no type named 'size' in '...' | Im trying to parse into a struct containing a std::string and std::vector, but I always get a error when using the %-operator of Boost Spirit.
I already tried to isolate the list parsing into a seperate rule (source) and the as<>-directive from this question
Without the predicate_arguments rule it works perfectly.
The ... | I forgot to import the ast_adapted.h into my decfile_parser.h. The error was because the struct of course was not adapted to a Fusion Sequence.
|
62,691,761 | 62,692,150 | wrting to csv file in c++ fails | Im working with this code which is supposed to detect faces. The code works totally fine, but as soon as I try to insert three lines for writing to csv file, it breaks down with lengthy error of some 100+ lines -ERROR FILE LOG.
This code was taken from :- https://github.com/shunyaos/shunyaface
// Header file for Face-R... | You forget to end this line cout<< "In while"<<.
Somewhere in your code is this snippet
out<< "In while"<<
// Capture a frame
~~~~~~~~~~~~~~~~~~
cap >> frame;
You should try to fix error from top to bottom. The first error is regarding cout, operator<< and cv::VideoCapture cap.
|
62,691,777 | 62,698,601 | How to extract a perticular data from xml whole output data in C++ | I have a C++ function which prints whole xml output data on console. This data has many elements. I want to print particular element on the console.
My function looks like below:
void SampleEventListner::OnBarcodeEvent(short int eventType, std::string & pscandata){
cout << pscandata << endl;
}
This above code is ... | I like to use pugixml; small lightweight and fast.
#include <iostream>
#include "pugixml.hpp"
std::string XML = "<outArgs>\
<scannerID>1</scannerID>\
<arg-xml>\
<scandata>\
<modelnumber>DS9308-SR00004ZZWW</modelnumber>\
<serialnumber>19361523701373 </serialnumber>\
<datalabel>0x68 0x74 0x68 0... |
62,691,890 | 62,693,443 | In cycle sort algorithm, I was looking for a case where we observe the unstable nature of the algorithm | I was reading about the cycle sort algorithm and found out that it is unstable in nature, however, I am having difficulty in coming up with a case that shows the unstable nature of the cyclic algorithm.
Could someone give a case where we can observe the unstable nature of the algorithm?
More information on the algorith... | So let's say we have a group of data as below:
2 sets of letter "A" to "E". To better differentiate them, I'm gonna call duplicate data with a number attached to them. So "A"s would be "A1" and "A2" and so on.
Now let's try to sort them based on the algorithm you mentioned.
Step 1:
Taking the first data out, and fin... |
62,692,631 | 62,696,984 | 'Reflection' using structured-bindings | I was wondering if it was possible to use fact that in
struct Foo
{
int x;
};
int main()
{
Foo foo;
auto [a0] = foo;
auto [a1, b1] = foo;
auto [a2, b2, c2] = foo;
// auto [a, b, c, ...] = foo;
}
only the first structured-binding is valid, in order to create metafunction that takes any pod typ... | The main issue here is that a structured bindings declaration is just that -- a declaration. We cannot form a "structured binding expression" in order to get the type, which is required in metaprogramming to constrain a template (for e.g., the void_t pattern, or a concept/requires clause)
Per [dcl.struct.bnd], despite... |
62,692,691 | 62,692,769 | Is a function call returning a pointer to an object a prvalue? | Let's imagine this function:
C* get(C* c, int offset) {
return c + offset;
}
I would like to know if a call to this function is evaluated as a prvalue:
C array_c[3];
C* c2 = get(array_c, 2);
Is get(array_c, 2) a prvalue?
According to Value categories page on cppreference:
a glvalue (“generalized” lvalue) is an ... | get(array_c, 2) and *get(array_c, 2) are two different expressions, and have different value categories.
get returns pointer by value itself, then get(array_c, 2) is considered as an rvalue (prvalue) expression. You can't perform assignment on it like get(array_c, 2) = nullptr; or get address from it like &get(array_c,... |
62,693,076 | 62,697,800 | OpenGL - calculating position in NDC works in shader but not in 'regular' program | I'm currently working on a 2d-sicescrolling jump'n'run with opengl. I currently want to check for my enemies if they are rendered on screen to stop collision calculations for enemies which are not visible. To do that, I check in each frame if the position in NDC is between [-1, 1] for the x- and y-axis.
This is done by... | As pointed out in the comments by user BDL I was applying the position twice (once in the translate and once when multiplying with MVP). I also deleted the scaling, since its not necessary for a single point.
The method now looks like this and works as I wanted:
bool Enemy::checkWithCameraArea(glm::mat4 view, glm::mat4... |
62,693,377 | 62,693,473 | Recusion and Templates in C++ | I try to compute derivatives using Tangent mode. I tried to implement it using recursion.
I got the following problem: I got a recursion with Templates which compiles forever.
template <typename T>
void dern(int n, const T &x, T &dy)
{
using DCO_T = typename dco::gt1s<T>::type;
DCO_T _x, _y;
dco::value(_x) = x;
... | n should be a compile time parameter passed as template argument.
template <int n, typename T>
void dern(const T &x, T &dy)
{
using DCO_T = typename dco::gt1s<T>::type;
DCO_T _x, _y;
dco::value(_x) = x;
dco::derivative(_x) = 1;
if constexpr (n > 1) {
dern<n - 1>(_x, _y);
} else {
f(_x, _y);
}
dy... |
62,693,395 | 62,693,647 | How to read from QFile? It shows that file not accessible | I've been trying to read .xml file using QFile. But qt creator can't even find it, but file exists inside project (also I tried to read it from another directory, not project's, it doesn't work, too). Debuger says file not accessible.
Here's my code:
QFile file("../info.xml");
if (file.exists())
if (file.open(QFile... | This is not a complete answer, but rather a list of what may have gone wrong.
Check the file path :
QFileInfo inf (file);
qDebug() << inf.QFileInfo::path();
Ensure that the file is in the right directory, i.e. in the same you have your .exe (build-ProjectName-...). You can check this by using QDir::currentP... |
62,693,455 | 62,693,821 | What settings are needed in Xcode to get this code to build | Let's take this code, which is in a header file. The project itself is Objective-C++ (.h & .mm files).
This looks like a mix of C++ and Objective-C. From what I've read, in order to mix Objective-C++ with Objective-C you have to keep all C++ stuff out of the header file, however this is not the case.
The project builds... | I assume you are only #include/#importing this header from .mm files.
The default struct field values are a new feature of C++11. Is the C++ standard in the new project perhaps set to C++98?
I'm not 100% sure on the details, but perhaps some of the more complex default value expressions are only possible in an even new... |
62,693,528 | 62,693,670 | How can one force an overriden methods base method to be called from the overriden method? | I have an class:
class MyCoolBean {
public:
virtual void toot(){
log("ooh la la");
}
}
And my derived class:
class MyCoolBeansBoy : public MyCoolBean{
public:
void toot()override{
log("oh yeah");
}
}
If I do:
MyCoolBeansBoy boi;
boi.toot();
The output is:
oh yeah
But I want the outp... | You don't.
(because it is not possible to do it reliably, the answer in your link is nice, but it only works with pointers which is quite a restriction)
Either you want the derived method to be the same as the one in the base, then you don't declare it as virtual, or...
If you want the derived classes to extend a base ... |
62,693,539 | 62,693,606 | Strange effect of passing parameter as `const` | Consider the following classes :
Bullet class
class Bullet : public sf::Drawable {
public:
Bullet(const sf::Vector2f& pos, const sf::Vector2f& dir,
const float& speed, const float& time, const float& life_time);
~Bullet();
bool collides(const Wall &wall);
priv... | You cannot call an non-const member function on a const object or a reference to a const object, simple as that.
class Wall : public sf::Drawable {
public:
void sample() const; // <---- you need this
};
Now it's up to you, either you make member functions that don't change the state be const, or get ri... |
62,693,736 | 62,695,494 | QFileDialog: force file name | I want to create a QFileDialog set to QFileDialog::AnyFile in which the file name is fixed (but the location can be changed).
So far I found the question QFileDialog - Saving a file with specified file name, which was not answered.
There is the pseudo-answer of choosing the directory directly instead, which is what I d... | I must admit that this what I got in mind is a dirty hack. On the other hand, the OP appeared somehow desperate to me. So, I post it (with some doubts in mind).
My idea raised due to the statement of OP:
QLineEdit* line_edit = dialog.d_func()->lineEdit();
(With dialog being of the derived class.)
This does not work, a... |
62,693,846 | 62,694,128 | c++17 filesystem::remove_all with wildcard path | I want to delete all files, folders and subfolders but not the parent folder.
So I tried to use filesystem::remove_all with a wildcard, but this doesn't seems to work.
filesystem::removeall("pathtofolder/*");
There is no exception, but it doesn't delete anything.
Are wildcards are not allowed?
Do I really need to cal... |
Are wildcards are not allowed?
There is no support for globbing (wildcards) in std::filesystem::remove_all:
Deletes the contents of p (if it is a directory) and the contents of all its subdirectories, recursively, then deletes p itself as if by repeatedly applying the POSIX remove. Symlinks are not followed (symlin... |
62,693,894 | 62,694,686 | double template parameter pack | Here is what my class looks like :
template<typename ...events_t, std::uint32_t ...stackDepth>
class Module {
protected: std::tuple<EventHandler<events_t, stackDepth>...> evtHandlers;
public: Module(std::tuple<EventHandler<events_t, stackDepth>...> _evtHandlers) :
evtHandlers{_evtHandlers}{ /* ... */ ... | A template variadic parameter, for a template class/struct, must be at the end of the list of template parameters. So, directly, you can use only one.
But you can wrap one (or both) your variadic packs with, by example, std::tuple, for types, and, std::integer_sequence, for integer values.
Unfortunately, you have to us... |
62,693,907 | 62,712,021 | Due to invalid ValidateRgn() childs windows do not get WM_PAINT messages | I have window with Button control, to drawing I use Direct2D, important WindowProc fragments:
LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
...
case WM_CREATE:
HWND button = CreateWindowExW(0, L"button", L"Send", WS_CHILD | WS_VISIBLE, 10, 10, 200, 100, hWnd, CONTROL_ID, ... | MSDN come in some help Child Window Update Region:
Each child window has an update region, (...) The system does not set the parent's update region when the child's is set. An application cannot generate a WM_PAINT message for the parent window by invalidating the child window. Similarly, an application cannot generat... |
62,694,351 | 62,702,823 | how does visual studio debug optimization work? | I tried to find the answer for this, on the internet but I couldn't find any.
what I'm trying to say here is that in visual studio there is an option inside the project properties called optimization that is by default set to enable in release mode an disable in debug mode. what does this option do exactly ? I mean it ... | Optimization is a compiler feature which tries to analyze the program and change it to be faster (or sometimes smaller).
When optimization is turned off, the compiler creates assembly code for exactly what you typed. When it's turned on, it changes it. This usually confuses debuggers and takes longer to compile, but th... |
62,694,544 | 62,694,584 | Is a static object inside a function re-initialized when its initialization value is dynamic | given the following code:
void some_class::some_function(void) {
static I2cU8U8RemoteRegister ctl(Registers::IND_ACC_CTL, *this);
..
}
does ctl get reinitialized if "this" changes, i.e. some_function is called with different object than it was called the first time?
Thanks for any help on this issue.
Kind regards,... |
does ctl get reinitialized if "this" changes, i.e. some_function is
called with different object than it was called the first time?
No.
Local static variables are initialized at most once, at the first function/method call.
|
62,694,579 | 62,694,742 | QT TCP socket connection exception. Too many arguments to function | Help, I looked everywhere where it is possible. If I create connections to the TCP server from the main class, then everything works. But if I create a separate class, it gives an error "Too many arguments to function".
Exception
Qt version 5.9.9
Using QTcpSocket
tcpclient.h
#ifndef TCPCLIENT_H
#define TCPCLIENT_H
#i... | The compiler found an ambiguity because it looks like you are trying to
call the method
void TcpClient::connect()
which is taking No args... so the solution is to "tell the compiler which method should be taken" i.e. you have to replace this:
connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(onReabyRead()));
with
Q... |
62,694,804 | 62,700,897 | Allocate memory space larger than SIZE_T/UINT dynamically (i.e. on the heap) | I have a requirement to allocate a block of contiguous memory space of size only storable in a LONGLONG (long long) container. A warning of type C4244 is thrown by the compiler when a LONGLONG value is used with the new statement or malloc() function, stating that there is a possible loss of data when converting from L... | The stated warning only persisted as the code was set to compile to the x86 instruction set, in which no more than 4 GB of memory can be used. As in any (and every) case/instance, it is impossible to allocate contiguous memory beyond the range of SIZE_T which makes the range of the size datatype of the x64 architecture... |
62,694,902 | 62,694,967 | Returning incorrect value from class | I have the following class:
class RequestBuilder : QObject
{
Q_OBJECT
public:
static RequestBuilder& getInstance()
{
static RequestBuilder instance;
return instance;
}
RequestBuilder(RequestBuilder const&) = delete;
void operator=(RequestBuilder const&) = delete;
void set... | What RequestBuilder::getInstance().url().toStdString() returns is a temporary object, which would be destroyed immediately after the full expression, after that the pointer val got from the temporary becomes dangled, any dereference on it leads to UB.
As you've showed when use a named variable, whose lifetime ends when... |
62,695,250 | 62,697,621 | fatal error: 'openssl/evp.h' file not found cmake + make | Operating system: macOS Catalina
I have a project that has a file called CMakeLists.txt. I ran cmake and then make, but the make command failed:
/Users/blablabla/Downloads/myproject/src/main.cpp:10:10: fatal error:
'openssl/evp.h' file not found
#include <openssl/evp.h>
I tried reinstalling OpenSSL via homebrew, link... | either openssl's dev library is not installed, or the g++ command that cmake generates probably is missing a -I.
try sudo apt-get install libssl-dev first and if that doesn't work, make sure the openssl include dir is provided to g++.
according to https://cmake.org/cmake/help/v3.6/module/FindOpenSSL.html, it creates an... |
62,695,276 | 62,695,706 | C++ OpenGL, why isn't the vertex array binding the vertex buffer? | I'm pretty sure that the vertex array is not binding the vertex buffer because if I comment out the line where I unbind the vertex buffer it works perfectly fine, which suggests that the vertex array isn't binding the vertex buffer properly.
Here is the code (there is some abstraction around the program and window but ... | A VAO doesn't store the buffer binding. It only stores which buffer is bound to which attribute. If you need the buffer binding itself (for example, for glBufferData), you have to bind the buffer yourself.
Also note, that glBindAttribLocation has to be called before the program object get's linked.
|
62,695,615 | 62,696,959 | detach a class method and run it asynchronously in C++ | I have an API call that informs the caller that a task has started and internally executes the task asynchronously since the task might take enough time.
I tried to describe my scenario using two classes
Manager class has the fire and forget method run_long_task, which now just contains a sleep call.
MyAPI class expos... |
how do I call Manager::run_long_task from modifyVarAndRunAsyncTask?
//first argument has to be "this" for the member function
std::thread t1(&Manager::run_long_task, manager_.get(), 50000);
t1.detach();
Although the constructor for std::thread takes a function and passes it's arguments, I think it is easier to just... |
62,695,744 | 62,696,752 | {fmt} library: How to use RegEx to add compile time string checking? | I am using the {fmt} library.
Unfortunately, my program crashed after a few days, as I had an invalid format string. Easily fixed - but what if there are more?
It is possible to do compile time checking of string formats, which would have caught this error:
// Replace this:
fmt::print("{}",42)
// With this:
fmt::print(... | In VSCode, this works:
Pattern: .*(fmt::print\()"\{\}"(,.*\)).*
Replacement: $1FMT_STRING("{}")$2
If you're a Python fan, this also works if you read the C++ script in as a string:
import re
pattern = '.*(fmt::print\()"{}"(.*\)).*'
fmt_snippet = 'fmt::print("{}",42)'
re.sub(pattern, r'\1FMT_STRING("{}")\2', fmt_snip... |
62,695,759 | 62,698,060 | C++ version of system header files cannot be found | with "... after adding sqlite.c in project" I should continue, because every thing was fine. Headers like cassert, cerrno, cstdio, let say, c* do exist and normally compiler do see them and compile.
After adding sqlite3.c into the project, now I imagine that .h version of those header files (assert.h, errno.h, etc.) ar... | The problem was because of precompiled header. When a .c file is introduced into project, then precompiled header was being compiled also as c-header file. Commenting out C++ part of the header for C-compiler resolved the problem:
#ifdef __cplusplus
#endif
|
62,696,383 | 62,696,805 | Why can I stored a variable at an address that is not a multiple of its minimum alignment? | According to this answer:
The minimal alignment is (on a given platform) the one which won't give crashes.
With GCC 8, there are two functions to get the minimal and the preferred alignment:
the standard alignof operator that gives the minimum alignment
the GNU __alignof__ function that gives the preferred alignment... |
The minimal alignment is (on a given platform) the one which won't give crashes.
Therefore, if I correctly understood the answer I quoted above, an application that store a double at an address that is not a multiple of 4, the program should crashes.
You are denying the antecedent.
Just because conforming to alignm... |
62,696,455 | 62,698,308 | Is there a way to find the median value of coefficients of an Eigen Matrix? | I was wondering if there was a more efficient way to do it than with manual for loops.
| EDIT: This answer requires the devel branch of eigen! I've been using that branch for so long, that I forgot that e.g. reshaped is not part of the stable branch...
There is a way. Median calculation typically requires sorting, so that's what I did here, too. If you have a mutable object/expression, its values are sorte... |
62,696,515 | 62,696,561 | having error function not declared in bubble-sort program | i am having some problem whlie compiling bubble sort program , it gives me
error: ‘bubblesort’ was not declared in this scope bubblesort(a,5);
#include<iostream>
using namespace std;
int main()
{
int a[]={12,34,8,45,11};
int i;
bubblesort(a,5);
for(i=0;i<=4;i++)
cout<<a[i];
}
void bubblesort(int a[],int n)
... | In c++, the lexical order matters, i.e. if you use a name, then that name has to be at least declared before it is used. (It can also be defined before it is used, of course).
So you need:
void bubblesort(int a[],int n); // declare
int main()
{
// ...
bubblesort(a,5); // use
}
void bubblesort(int a[],int n) //... |
62,696,596 | 62,703,680 | Correct/Fast Way to Change the Config of a Command-Line Qt5 Source Build | I'm building Qt5 (Qt 5.15.0) from source (the official source releases, not from repo) on Windows with MSVC.
I'm setting up the env. variables, the dependencies, etc. and then run configure with 16 million options, and finally jom and it works.
But I'm experimenting with the build, and have to run configure a lot. And ... | Use shadow build i.e. execute configure from one directory up level. Here is my command line which I used on Linux to build Static QT.
$ ../qtsrc/configure -opensource -confirm-license -release -static -no-pch -qt-xcb -prefix $PWD/_build -skip webengine -nomake tests -nomake examples
So in case you need to do another ... |
62,696,678 | 62,698,726 | Locating error in source which is boost related | I'm porting an old project from Boost 1.48 to Boost 1.61. The project is compiled using MSVC 2013. There are several reported errors during build which I think are boost related but unfortunately the bug reports are not very helpful at all.
3> entry.cpp
4>c:\program files (x86)\microsoft visual studio 12.0\vc\includ... |
@Eljay, does it have a human readable text option I could locate in the IDE? – SPlatten 43 mins ago
The thing you posted IS human readable text. It actually describes a warning with a reference to documentation. ¯\(ツ)/¯ Maybe you can just tell the compiler you don't want to receive warnings
In addition, you can use t... |
62,697,044 | 62,753,986 | Create MFC CBitmap from bmp file data | I have a void pointer to data that was read from a *.bmp file. The bmp file no longer exists (there is now one file that contains hundreds of these bitmap file datasets). How can I initialize an MFC CBitmap using this data?
I see the CBitmap::Create* functions (e.g., CreateBitmap(), CreateCompatibleBitmap(), etc), but ... | If using GDI+ is an option, you can construct an HBITMAP from an in-memory data buffer using essentially this answer, and finally attaching the returned HBITMAP to an MFC CBitmap. This is the original code:
#include <Shlwapi.h>
#include <atlimage.h>
#include <comdef.h>
#include <comip.h>
#include <vector>
#pragma com... |
62,697,249 | 62,701,681 | What is the meaning of this expression? | There's a discrete binary search article on topcoder where i met with this expression.
while(lo & lt; hi )
if(i + j & lt ; = x )
described below
I have never seen this expression ";" in a while loop and using & in it.
And Also, in general i want to know what AND & bit wise operator do(i know how it works in binary leve... | This is just bad formatting of the HTML for the "<" less than operator from wherever you found this code
The HTMLcode for < is <
Replace all sequences of < with < and you get:
while (lo < hi) {
int x = lo + (hi - lo) / 2;
int required = 1, current_load = 0;
for (int i = 0; i < n; ++i)... |
62,697,326 | 62,717,044 | How can I import a CLion C++ project into Visual Studio? | It seems like this should be easy and I've spent hours trying to find this answer online but haven't had any luck.
I can open the CLion folder path in Visual Studio, but that option doesn't give me the usual options to build and start the project. To do that, I need to open CLion as a Project/Solution, but I can't seem... | The link provided describes Visual Studio's CMake integration, which (similar to CLion) will install a version of CMake that Visual Studio will use. These instructions are pretty thorough and should provide everything needed to get your CMake project working in Visual Studio.
Now, you probably have two versions of CMak... |
62,697,732 | 62,697,911 | How to insert the new object to the map only if the object doesn't exist in the map using rust? | I'm transporting C++ code to rust.
Here is the original C++ code.
#include <map>
#include <string>
#include <cassert>
#include <iostream>
int main() {
std::map<std::string, int> m {
{ "A", 1 },
{ "B", 2 },
{ "D", 4 },
};
// *1
auto r = m.equal_range("C"); // *2
if (r.first =... | It looks like you want the Entry API?
In the rustification of your example, m.entry("C") would return an Entry enum which contains the information of whether the entry is present or not. You can then either dispatch explicitly or use one of the high-level methods e.g. BTreeMap::or_insert_with which takes a function (an... |
62,697,748 | 62,698,128 | Difference in the execution of the loop | Can anyone explain me the difference in the execution of both of the codes?
1)
#include <iostream>
using namespace std;
int main() {
// your code goes here
string code;
getline(cin,code);
for(int i=0;i<code.length();i++){
if(code[i]=='.'){
code.replace(i,1,"[.]");
}
}
... | We can do this and see what happens, for example with this input:
code = "google.com"
After a while, i will be equal to 6, and then it happens:
i code
6 google[.]com (and now there's a dot on place 7)
7 google[[.]]com (and now there's a dot on place 8)
8 google[[[.]]]com (and ... |
62,698,343 | 62,698,549 | Base virtual "binded to object" function is called when overridden exists | I would like the notifyAll to bind an overridden child method to the object stored as parent referrence. Despite inheritance, the base method is still performed. The compiler seems can't see the overload or treats vector elements as non-reference objects. I can't find my bad in the code below:
#include <iostream>
#incl... | First, don't use std::bind(). It is all but obsolete. (Prefer lambdas instead.)
Second, if you call it directly instead of std::bind(), it will work:
(observer.*eventMethod)();
See it live on Coliru, where the output is the desired:
virtual void Npc::onNewGame()
Alternately, if you have C++17 support, you could use s... |
62,698,889 | 62,699,112 | There is any difference between ascii and unicode at processing level? | Let assume I have a function like
template<typename charT>
void fun(std::basic_ostream<charT>& out, std::basic_fstream<charT>& file)
{
std::basic_string<charT> str;
file>>str;
out<<str;
}
Note: file is encoded as utf-8
I am not knowledgeable with Unicode. Can I use this function for both ASCII and Unicod... |
There is any difference between ascii and unicode
Yes. They are distinct encodings and not identical. As such, there are differences.
Can I use this function for both ASCII and Unicode
Yes. For UTF-8 (assuming size of byte is 8 bits).
The function does nothing that would require different handling between those enc... |
62,699,222 | 62,700,756 | How to pass signals and methods to .qml page, using QProperty? | Recently, I've been interested about how to create a simple general model with submodels and pass its data to .qml page. I got help and did it. But now I've got another problem. Now I can use roles, but I can't use signals or methods.
Here how my code looked like before
basemodel.h
class BaseModel : public QObject
{
... | To connect to signals using a Connections object, your code should look like this:
model: _baseModel.extra
Connections {
target: _baseModel.extra
onSelectedChanged: {
selectionChanged(selected, name, itemName)
}
}
EDIT:
To call invokable f... |
62,699,580 | 62,699,751 | In c++ there is a way to create a tree-like map that contains maps as a value? | In c++ there is a way to create a tree-like map that contains maps as a value?
map<string, map<string, map<string, map<...>>> name;
| For arbitrary depth, you're going to need some dynamic allocation.
struct Node
{
map<string, std::unique_ptr<Node>> children;
};
Node root;
Your bottom-most nodes will have no children.
We can't just write map<string, Node> children (even though the child Nodes will themselves be dynamically allocated within the m... |
62,700,026 | 62,702,134 | How to write a constructor with exception | I want to know how can I write a constructor with exception in it
I have a class Character
and another class Matrix<T>
template<class T>
class Matrix
{
T** data;
int col;
int row;
public:
//ctor of matrix
template<class T>
Matrix(const Matrix<T>& mat):data(new T*[mat.row]), col(mat.col), row(mat.... | for anyone who needs it the solution is:
Game(int height, int width):data((height<=0)||(width<=0) ? throw IllegalArgument() : Dimensions(height,width))
,height(height),width(width)
{
}
|
62,700,039 | 62,700,508 | C++ initialize array with another array and new values | I'm coming to C++ from python and would like to do the equivalent of this with arrays if possible:
both = [...]
a = [a1, a2] + both
[a1, a2, ...]
b = [b1, b2] + both
[b1, b2, ...]
| To do such a thing with arrays you might consider the following code
#include <iostream>
int main()
{
int both[] ={1, 2, 3};
std::cout << sizeof(both)/sizeof(*both);
int a[sizeof(both)/sizeof(*both) + 2] = {4, 4};
int b[sizeof(both)/sizeof(*both) + 2] = {5, 5};
f... |
62,700,177 | 62,701,111 | Create unique pointer inside a function | Is it possible to declare a unique_ptr inside a class (nullptr), then pass its raw value (with get()) to a function which create the instance it will point to?
I have to run an application with a Qt made interface. Qt needs the Qapplication to start in the same thread in which the UI will be updated. To do so, since I ... |
Is it possible to declare a unique_ptr inside a class (nullptr), then pass its raw value (with get()) to a function which create the instance it will point to?
You can, but the way you're going about this (from the limited code snipped you've posted) sounds convoluted. Why does threadfunc need to take in raw pointers... |
62,700,452 | 62,700,763 | (CLASS*)int to shared_ptr<CLASS>(int) not work | I want to convert the source to a smart pointer.
But I found one I don’t understand why it can’t.
How can this be solved with the code below?
Old code style:
bool PyTuple_GetTextInstance(PyObject* poArgs, int pos, CGraphicTextInstance** ppTextInstance)
{
int handle;
if (!PyTuple_GetInteger(poArgs, pos, &handle)... | Assuming that the original code is correct and that handle is really a pointer to a CGraphicTextInstance under the skin, then you need to replace this:
ppTextInstance=std::static_pointer_cast<CGraphicTextInstance>(handle);
with this:
ppTextInstance = std::shared_ptr <CGraphicTextInstance>
(reinterpret_cast <CGraph... |
62,700,637 | 62,700,845 | Why do fancy pointers exist? | I've always seen pointers as a specialization of iterators, used in the particular case where objects are stored contiguously in memory. However, I found out that the Allocator member type pointer (which then defines the same member type on iterators and containers) is not required to be a real pointer but it may be wh... |
I've always seen pointers as a specialization of iterators
Iteration of arrays is one of the uses of pointers. It is not their only purpose. They are also used as a "handle" to identify dynamic allocations.
why were [fancy pointers] introduced?
The page that you linked explains a reason for their introduction:
Suc... |
62,700,839 | 62,701,009 | Windows C++ -- Using DeviceIoControl to return a product string | I am trying to return the "product string" for a HID using DeviceIoControl in Windows. Here is my code:
for (int i = 0; i < nDevices; i++)
{
wchar_t* productString = new wchar_t[POINTER_DEVICE_PRODUCT_STRING_MAX];
HANDLE potentialUsbDevice = CreateFile(devInfoDataBuffer[i]->DevicePath, GENERIC_READ,
... | You need to pass the size of the output buffer (in bytes) to DeviceIoControl. You also need to pass lpBytesReturned as non-NULL:
DWORD bytes_returned;
DeviceIoControl (potentialUsbDevice, IOCTL_HID_GET_PRODUCT_STRING, 0, 0,
productString, POINTER_DEVICE_PRODUCT_STRING_MAX * sizeof (wchar_t),
&bytes_returned, 0... |
62,700,894 | 62,701,746 | 3-3. Write a program to count how many times each distinct word appears in its input | In this:
#include <iostream>
#include <string>
#include <vector>
using std::cout; using std::cin; using std::vector; using std::endl;
using std::string;
int main(){
cout << "enter strings: " << endl;
string s;
vector<string> in;
vector<string> out;
vector<int> count;
while(cin >> s)
i... | If you can't use std::map, you can associate the word with the frequency:
struct Info
{
std::string word;
int frequency;
};
//...
std::vector<Info> database;
//...
std::string word;
while (std::cin >> word)
{
// Find the word:
const size_t length = database.size();
for (unsigned int i = 0; i < ... |
62,700,901 | 62,701,030 | Reading an array of integers from a binary file | I am trying to read a binary file into an array of 16-bit integers. I used a for loop to read the data and it works properly. This is how I read the file:
int L = (End-Start)/2;;
int16_t* I = new int16_t[L];
int16_t s;
for(int i=1; i<=L; i++)
{
inFile.read((char*)&I[i], sizeof(s));
}
I was wondering if t... | Probably you do not wanted
for(int i=1; i<=L; i++)
but
for(int i=0; i<L; i++)
because the first index in an array is 0, not 1.
I was wondering if there is any way that I can read the whole array without using for loop?
you can replace :
for(int i=0; i<L; i++)
{
inFile.read((char*)&I[i], sizeof(s));
}
by :
... |
62,701,611 | 62,703,723 | c++ Use a class variable in a non-class function | I'm facing this novice issue. Assume the class MainFrame (the following code isn't going to compile - I'm trying to give a basic idea of what I'm doing because I think my problem is easy to solve by someone more knowledgeable than me) which lives on file gui.cxx along with other functions. Note that this is part of a l... | Your problem is you throw away the pointer to your MainFrame so you have no way to access it in start_gui_with_config() after you created the MainFrame.
One way to fix this is to change the signature of void start_gui(); to MainFrame* start_gui(); in your gui.h header.
In the gui.cxx change the implementation to
MainFr... |
62,701,692 | 62,711,815 | How to compile C/C++ native code in Android Studio 4 | I was trying to add C/C++ native code found in a project found in github (here is the link).
I first moved jni folder into src/main folder
I added below lines in my Gradle under android
externalNativeBuild {
ndkBuild {
path 'src/main/jni/Android.mk'
}
}
When I tried to sync with Gradle I get b... | I discovered that The project missed a library named Opus audio codec (here is their github repository).
I downloaded the source code of opus
I unzipped it. And placed all its files and folder under opus folder located at src/main/jni
I deleted the win32 folder and test folder
And it successfully built the project
|
62,701,945 | 62,702,033 | How to use functions of <strings.h> like strcmp() with object of <string.h> in c++ | i also noticed that functions of <strings.h> does not work with the object of <string.h>
for example in dev c++
#include<string>
#include<strings.h>
using namespace std;
int main()
{
string a="admin";
string b;
cin>>b;
if(strcmp(a,b)==0)
{
cout<<"Equal";
}
}
so the compiler shows error at line where strcmp() function ... | strcmp operates on c-strings, not std::strings.
To access the internal c-string of an std::string, use the c_str() method.
i.e.
if (strcmp(a.c_str(), b.c_str()) == 0) {
// ...
}
But you can also do the comparison directly
if (a == b) {
// ...
}
|
62,702,174 | 62,702,297 | Constructor consuming a variable number of rvalue references | I wish to create an object A that can be constructed by either copying or moving a variable number of B objects. Something like this:
class B {}
class A {
A(B&& operand1, B&& operand2, ... B&& operandk) {
// move construct A
}
A(B& operand1, B& operand2, ... B& o... | When you need an object to own, just take it by value. The caller can move-construct or copy-construct the arguments depending on whether they need to retain a copy of the objects they're going to give the constructor.
And -- even better -- this way they can move-construct some of the objects but not others.
In the co... |
62,702,295 | 62,702,407 | Time complexity of leetcode 394 | I was trying this problem on leetcode
https://leetcode.com/problems/decode-string/
I came across this particular solution. Code is below.
class Solution {
public:
string decodeString(string s) {
stack<string> chars;
stack<int> nums;
string res;
int num = 0;
for(char c : s) {
... | I guess, not so sure though, you're somewhat right. That would probably be considered O(N) though since those coefficients would not have much influence.
Just another version:
#include <string>
class Solution {
public:
std::string decodeString(const std::string &base_string, int &index) {
std::string decod... |
62,702,773 | 62,702,813 | Why is the code giving Segmentaation fault? | I was solving the climbing leaderboard problem in hackerrank but my function gives segmentation fault.
vector<int> climbingLeaderboard(vector<int> scores, vector<int> alice) {
vector<int> res,i;
auto ip= unique(scores.begin(),scores.begin()+scores.size());
scores.resize(distance(scores.begin(),ip));
fo... | Firstly, res[i] is accessed without allocating any elements in res.
vector<int> res should be vector<int> res(alice.size()).
Secondly, scores[curr] may be accessed before checking if curr<scores.size().
while(alice[i]<=scores[curr]&&curr<scores.size())
++curr;
should be
while(curr<scores.size()&&alice[i]<=... |
62,702,816 | 62,705,674 | Stringize operator on argument with spaces | I have
#define ARG(TEXT , REPLACEMENT) replace(#TEXT, REPLACEMENT)
so
QString str= QString("%ONE, %TWO").ARG(%ONE, "1").ARG(%TWO, "2");
becomes
str= QString("%ONE, %TWO").replace("%ONE", "1").replace("%TWO", "2");
//str = "1, 2"
The problem is that VS2019, when formatting the code (Edit.FormatSelection) interprets t... |
Is there a way at compile time to detect such arguments to a macro having space(s)?
Here's what I would do:
#define ARG(TEXT, REPLACEMENT) \
replace([]{ \
static constexpr char x[] = #TEXT; \
static_assert(x[0] == '%' && x[1] != ' '); \
return x; \
}(), REPLACEMENT)
|
62,702,980 | 62,703,195 | How do you access a class method that is hold by a shared pointer? | I am a new C++ student, so I probably don't fully understand smart pointers yet.
I thought that you can access a class-method through a shared_ptr (in this case, created through weak_ptr.lock()) with ->?
But, for some reason, the program seems to terminate in the process:
class Student{
string name;
public:
Student... | You access it like this:
o<<itr->second.lock()->get_name()<<endl;
Now why doesn't it work? Well, you didn't have any shared_ptrs pointing at your object any more. So it got deleted.
Since the object was deleted, itr->second.lock() returned a null pointer. Then you tried to use the null pointer, which crashed your pr... |
62,703,500 | 62,703,562 | Should I prefer two if statements over an if-else statement if the conditions aren't related? | So I know that generally speaking, I should prefer an else-if over and if if. But what if the two conditions aren't related? For example, these would be considered "related" conditionals:
if (line[a] == '{'){
openCurly = true;
}
else if (line[a] == '}'){
closeCurly = false;
}
Notice how the two conditionals in... | You should use an else-if statement. This is because an if-else construct only checks the second statement if the first one doesn't evaluate to true.
In the example you give,
if (line[a] == '{')
{
openCurly = true;
}
else if ((line[a] == ';' && !openCurly) || (line[a] == '}' && openCurly))
{
DoSomething(line);
... |
62,703,734 | 62,709,826 | Websocket++ error: handle_transport_init received error: TLS handshake failed | When I connected to localhost it worked. But when I'm trying connect to wss://echo.websocket.org it says:
[2020-07-03 00:24:19] [connect] Successful connection
[2020-07-03 00:24:20] [error] handle_transport_init received error: TLS handshake failed
[2020-07-03 00:24:20] [fail] WebSocket Connection 174.129.224.73:443 - ... | I solved this question. There was error with verifying certificates.
Code to fix it:
context_ptr on_tls_init(const char* hostname, websocketpp::connection_hdl) {
context_ptr ctx = websocketpp::lib::make_shared<boost::asio::ssl::context>(boost::asio::ssl::context::tlsv12);
try {
ctx->set_options(boost::a... |
62,703,739 | 62,703,786 | Shell Wrapper Handle / Execute Interactive Commands Pipes C++ UNIX | My Project is to Create a little Remote Shell for my Home Unix PC in C / C++. Its components are a server which sends commands to the client via socket connection, which executes the command and sends the output.
Now I would like to execute commands like "login" to authenticate myself on the client.
Is there any way ho... | You do this using so called pseudo terminals. The portable function for that is posix_openpt
|
62,703,952 | 62,704,198 | Default positioning of fill characters for streams | On the reference page for std::setfill, there is an example similar to the following program:
#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::setfill('*') << std::setw(10) << 42 << '\n';
}
which claims that it should print:
********42
This suggests that the default positioning of the fill ch... | setfill is defined in [std.manip] as
template<class charT, class traits>
void f(basic_ios<charT, traits>& str, charT c) {
// set fill character
str.fill(c);
}
so we need to look at what happens to an ostream's fill function and that is detailed in [ostream.formatted.reqmts]/3 as
If a formatted output function of ... |
62,704,021 | 62,704,107 | std::vector no instance of overloaded function matches the argument list | I'm trying to use the code below for my node editor, I'm using Visual Studio 2019, it errors out whenever I try to insert a node object
edit: forgot that push_back is the correct function, my bad
std::vector<Node*> nodes;
void Example(){
Node* s = new Node();
nodes.insert(s);
}
the full error:
no instance of ... | insert needs an iterator argument for the position where you want to insert an item. E.g.:
nodes.insert(nodes.begin(), s);
If you don't want to specify the position and just want to append an element to the vector, you could use push_back:
nodes.push_back(s);
|
62,704,151 | 62,704,736 | what is the scope of the overloaded operator? Does it affect the insert function for a set that is a class member? | I have a class defined for a data structure, where I have defined an overloaded operator< for the class. However, for the _positions, which is a std::set<size_t>, the insert() function no longer seems to do anything.
I am wondering if the overloaded operator for the class means it is not able to see if a position is in... | This has nothing to do with operator overloading, or with insert.
You're inserting into the wrong set.
Every single one of the below functions copies the member variable then acts on the copy, before discarding it.
void KmerClass::addKPosition(const size_t& kPosition, const uint& offset)
{
size_t kPos = kPosition +... |
62,705,161 | 62,706,774 | How much memory must be reserved for a C++20 coroutine frame? | First of all I want to predict the memory usage of my code, just as any responsible programmer should. This would apply even if I was not deciding to allocate my coroutine frames using placement new, as I am (see below pseudocode). Even supposing I change my mind about placement-newing all my coroutines, and thus I let... | This was debated at length during the standardization of C++20 coroutines. The layout and size of the coroutine frame cannot be determined until after the optimizer finishes its job, and making that information available to the frontend would require fundamental rearchitecturing of all existing compilers. Implementers ... |
62,706,026 | 62,706,290 | Why is my C++ program's assembly output full of .ascii with no assembly code? | I am compiling a C++ file into a static library with CMake and I am modifying the Makefile that CMake generates by adding the -S -fverbose-asm flags to the gcc command to get the assembly output, however the resulting .cpp.s file is filled with .ascii lines with what looks like hexadecimal data, and contains no assembl... | You probably compiled with Link Time Optimization enabled (gcc -flto), which makes "fat" object files that also contain GCC's intermediate representation of the program logic alongside regular asm. (So whole-program optimization can happen at link time, allowing inlining across source files and further optimizations t... |
62,706,873 | 62,707,358 | Does unnecessary C++ code end up in my completed program? | Let's say I'm including a header file that has tons of functions.
#include "1000Functions.h"
Function1(42);
Function2("Hello");
Function1000("geeks!");
But, I just want to use a few of the functions from the header. After preprocessing, compiling, and linking (for example, with g++), would my program include all 1000... | I found this article that was useful. Using objdump -tC ProgramName can show you the unnecessary code that ends up being loaded into .text when your program is loaded into the memory.
Link-time optimization was what I was looking for, which worked for me once I added both of these tags to the linking command, not just ... |
62,706,914 | 62,707,308 | Inheritance and friend functions, accessing protected members from base class | Let say that I have a big class Circle with a lot of members and functions. To proceed a large amount of data I decided to create class PotentialCirlce (with only 3 members - x, y, r), do most of preprocessing based on PotentialCirlce and in the last stage create objects Circle.
a) is it correct approach? do It influen... | There are not really a good approach to compare objects of different types as it make little sense in practice. What would be the purpose of such comparisons.
Now even if you have a single class, if the ordering is not intransic to the type, it would be better to use an external class for sorting.
class CircleDiameterL... |
62,706,936 | 62,707,040 | Nested for loop not looping through second array | How do I get the second array to be properly looped through? It is a simple matrix multiplication operation (using Visual Studio 2019) and arr is being looped through, but arr2 isn't being looped through completely. Only the first 2 elements are being multiplied by all elements of arr.
#include <iostream>
using namesp... | You make the same basic mistake in all of your loops -- that mistake being that you are not iterating over the rows correctly.
You are using the column count when you should be using the row count:
int** arr = new int* [r1];
for (int i = 0; i < c1; i++) { // <-- This should be i < r1, not i < c1;
arr[i] =... |
62,707,071 | 62,707,210 | Different Output while using and not using 'break' in switch case in c++ | I was solving the a question at HackerRank -
Question Link - https://www.hackerrank.com/challenges/maximum-element/problem
In one solution I used 'break' statement in switch-case, in another solution I didn't.
Solution was wrong when I didn't use break statement. What is the reason behind this ?
Input -
10
1 97
2
1 20
... | Consider the following code
switch (x) {
case 1:
std::cout << "one\n";
case 2:
std::cout << "two\n";
break;
case 3:
std::cout << "three\n";
}
If x is 1 it will print both one and two. It will then exit the switch block due to the break statement. Note that x will not be compared with 2 after prin... |
62,707,343 | 62,707,546 | How can I print map key/value with std::variant? | I'm trying to print the key of a certain value in my dictionary. I defined my map like this:
std::map<std::string, std::variant<float,int,bool,std::string>> kwargs;
kwargs["interface"] = "probe";
kwargs["flag"] = true;
kwargs["Height"] = 5;
kwargs["length"] = 6;
I tried to print the value normally but a (no opera... | I would use std::visit with a generic lambda that prints any type to std::cout, as follows:
std::map<std::string, std::variant<float,int,bool,std::string>> kwargs;
kwargs["interface"] = "probe"s;
kwargs["flag"] = true;
kwargs["Height"] = 5;
kwargs["length"] = 6;
for (const auto& [k, v] : kwargs){
std::cout << ... |
62,707,548 | 62,756,956 | Modifying registers with Intel PIN | I want to clobber all load instructions - essentially, I want to find all load instructions, and after the load is complete I want to modify the value in the register that stores the value that was read from memory.
To do so, I instrument all instructions and when I find a load I insert a call to some function that wil... |
If for instance, I load a 32 bit signed int from memory into a register, can I always assume that it would be stored at s_dword[0]?
Yes.
If you are in long mode and have, e.g., the RAX register, you have two DWORDs: the lower less significant 32 bits (index 0 in s_dword) and the higher most significant 32 bits (index... |
62,707,578 | 62,707,652 | A variable is reverting to a previous value after being assigned to with an assignment statement | I am writing a simple chip8 emulator.
I have a value called programCounter(PC).
The problem is that once I return from the Instruction1( which modifies PC), PC returns to the value it was before being modified by the method.
Example
Before Instruction1 assigns to PC, the value of PC is 203.
After Instruction1, the val... | You have two or more cpp files. Each forms a compilation unit. (A .h you include becomes part of each compilation unit separately; the notion of compilation unit applies after preprocessing is done.)
Static global variables are not linked between compilation units, they're private to the unit they're defined in.
stat... |
62,707,668 | 62,707,700 | How to access a vector securely on C++? | I have the followin vector:
std::vector<std::pair<std::function<void(iter_type, iter_type)>, bool>> functionList;
and at some point, a code is doing:
functionList[index].second = enable;
which is causing a crash
How can I safely verify if there's an object in this index so I can modify?
https://en.cppreference.com/w/... | Use .at(index) and catch the exception, or check index < vec.size() before calling [].
References in C++ are not null, they are aliases. Pointers can be null in C++.
|
62,707,910 | 62,723,389 | Troubleshooting Geeksforgeeks C Program: IEE 754 Notation to Decimal | I have tried troubleshooting this code but as I am new to the C language I haven't been able to crack it. I am pulling this program from this article Geeksforgeeks created: https://www.geeksforgeeks.org/program-for-conversion-of-32-bits-single-precision-ieee-754-floating-point-representation/
Every time I run this prog... | All I had to do to solve this question is remove the 'unsigned' in the following code:
unsigned int ieee[32]
= { 1,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0 };
Thanks again for all the input!
|
62,708,295 | 62,708,334 | Why does vector's random access iterator gives the same memory address unlike pointers? | vector<int>::iterator it;
for(it=v.begin();it<v.end();it++)
{
cout <<&(it)<<" ";
cout<<(*it)<<" ";
}
It outputs:
0x7fff6667cdf0 7 0x7fff6667cdf0 14 0x7fff6667cdf0 15 0x7fff6667cdf0 16
Note the address is same each time, the question is why?
| You're getting the address of the same object it, then you'll get the same address every time. The element pointed by the iterator changes, but the address of the iterator itself (it is an object and has its own address) won't change.
It's same for pointer variable too, if you're getting the address of the pointer itse... |
62,708,409 | 62,708,827 | Provide a operator== for std::variant | I am trying to create an operator== operator for an std::variant defined in the map like this:
struct anyType
{
template<typename T>
void operator()(T t) const { std::cout << t; }
void operator()(const std::string& s) const { std::cout << '\"' << s << '\"'; }
};
template<typename T>
bool operator==(const st... | You have a couple of issues in your code:
const &T t in your operator==, should be T const& t or const T& t.
You have forgotten to mention that you want to compare with a
std::string not with char array in your if statement(i.e. "linear"). Meaning you
need either of the followings:
if (kwargs["interface"] == std::str... |
62,708,778 | 62,709,941 | I am having problem with the error class undeclared in scope | I am compiling these programs. Complex.h, Complex.cpp, and project1_task1.cpp on centOS I compile this fine in visual studio, but I get the error in centOS. this is for a class.
Complex.h
#ifndef COMPLEX_H
#define COMPLEX_H
class Complex
{
private:
double realPart;
double imaginaryPart;
public:
Complex(dou... | Since linux filesystem are usually case sensitive, then do in
project1_task1.cpp
replace the
#include"complex.h"
with
#include"Complex.h"
|
62,709,310 | 62,709,723 | Customise button in QT | I need to create a toggle button in qt and it should look like the below image. It should show the ON image when it is turned on and remain at this state until it is toggled again. It should show the OFF image in the off case. Please help me on this.
| You can use images as an icon (sadly, it won't scale with button by default), create a class which would paint those images in the handler for paint event, or you can use those images in QSS stylesheet. QSS is CSS 2.0 analog for Qt's GUI elements.
Note that after using stylesheet all changes to visuals of said element ... |
62,709,663 | 62,710,822 | why am I getting runtime error for the following code and how to fix that? | I was solving this problem on Codeforces B. Ania and Minimizing and I got runtime error on test 9. I am new to c++ and I did not understand why this happened. Could someone help me fix this error? Thanks :)
Here is my code:
#include <iostream>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
... | As all of you guys pointed out I fixed my code. I was dumb and making the loop go out of bounds.
Here is the code:
#include <iostream>
using namespace std;
int main(){
int n, k;
string num;
cin >> n >> k;
cin >> num;
if(k==0){
cout << num << endl;
return 0;
}
if(num.s... |
62,709,990 | 62,710,905 | Memory error at lower limit than expected when implementing Sieve of Eratosthenes in C++ | My question is related to a problem described here. I have written a C++ implementation of the Sieve of Eratosthenes that hits a memory overflow if I set the target value too high. As suggested in that question, I am able to fix the problem by using a boolean <vector> instead of a normal array.
However, I am hitting th... | Turning the comment into a full answer:
Your operating system reserves a special section in the memory to represent the call stack of your program. Each function call pushes a new stack frame onto the stack. If the function returns, the stack frame is removed from the stack. The stack frame includes the memory for the ... |
62,710,316 | 62,714,182 | Is there an elegant and fast way to test for the 1-bits in an integer to be in a contiguous region? | I need to test whether the positions (from 0 to 31 for a 32bit integer) with bit value 1 form a contiguous region. For example:
00111111000000000000000000000000 is contiguous
00111111000000000000000011000000 is not contiguous
I want this test, i.e. some function has_contiguous_one_bits(int), to be portable.
... | Solution:
static _Bool IsCompact(unsigned x)
{
return (x & x + (x & -x)) == 0;
}
Briefly:
x & -x gives the lowest bit set in x (or zero if x is zero).
x + (x & -x) converts the lowest string of consecutive 1s to a single 1 higher up (or wraps to zero).
x & x + (x & -x) clears those 1 bits.
(x & x + (x & -x)) == 0 ... |
62,710,439 | 62,711,380 | Can lambdas be STL-adaptable? | "Make functor classes adaptable" - told Scott Meyers in Effective STL, item 40. There is a question - can lambda-functions be adaptable? (Lambdas doesn't provide access to the inheritance mechanism, right?)
| That item is not talking about inheritance, but about composition.
Prior to C++11, if you wanted to invert the output of a unary predicate, you would define argument_type and result_type member types, so you could wrap it in std::not1.
Or if you wanted to partially apply a binary operation, you would define first_argum... |
62,710,527 | 62,721,757 | Visual Studio: Design time build failed for project | I recently moved a C++ VS project from desktop computer to my laptop.
However when I open the solution, it gives me this error:
error : Designtime build failed for project 'C:\Coding_Projects\C++\Taxi\Taxi.vcxproj' configuration 'Debug|x64'. IntelliSense might be unavailable.
Set environment variable TRACEDESIGNTIME =... | Thanks for all the help guys.
The issue was the Visual Studio and QT on my desktop were updated to the latest versions available however my laptop's VS and QT were not up to date.
So all I had to do was update my Visual Studio and QT on my laptop, and then in the QT Project settings: Change the "Installation" to my upd... |
62,710,538 | 62,710,618 | C++ : "While" keep executed even if the condition isn't true | #include <iostream>
using namespace std;
int main()
{
int choose, num1, num2, result1, result2;
cout << "Type '1' for plus, '2' for minus\n";
cin >> choose;
if (choose = 1) {
cout << "Enter the first number :\n";
cin >> num1;
cout << "Enter the second number :\n";
cin >>... | Your while condition (choose != 1 || 2) is equivalent to ((choose != 1) || 2). Which evaluates to true because an int that is different than 0 is true true when casted to bool in c++. You need to change your condition to while (choose != 1 && choose != 2).
Here is a good answer that explains the int to bool: https://st... |
62,710,870 | 62,711,407 | Is clamping on iterators valid | I found the following in actual production code.
My suspicion is that it actually has undefined behavior into it, however, I couldn't find the related info on cppreference. Can you confirm this is UB or valid code and why this is UB/valid (preferably with a quote of the standard)?
#include <vector>
int main(int, char ... | Well, defining an iterator that is out-of-range is UB according to the Standard §5/5.7:
When an expression that has integral type is added to or subtracted
from a pointer, the result has the typeof the pointer operand. If the
pointer operand points to an element of an array object, and the array
islarge enough, the re... |
62,711,527 | 62,731,251 | How to prevent a Linux C++ library from crashing on an out-of-bounds read? | I am using a closed-source 3rd party Linux lib (.so) compiled for an older version of Linux on an older version of gcc.
Unfortunately, it crashes occasionally with a read of an invalid memory address.
This is certainly undesirable, and it would be fantastic to fix the library. But as that is absolutely impossible, and ... |
I am using a closed-source 3rd party Linux lib (.so) compiled for an older version of Linux on an older version of gcc.
Note that neither "older Linux" nor "older gcc" is the reason for the crash, a bug in the library is. A bug-less library compiled 15 years ago would still work perfectly fine today.
it would be fan... |
62,711,792 | 62,712,308 | How to convert CMSampleBufferRef/CIImage/UIImage into pixels e.g. uint8_t[] | I have input from captured camera frame as CMSampleBufferRef and I need to get the raw pixels preferably in C type uint8_t[].
I also need to find the color scheme of the input image.
I know how to convert CMSampleBufferRef to UIImage and then to NSData with png format but I dont know how to get the raw pixels from ther... | Some pointers you can use to search for more info. It's nicely documented and you shouldn't have an issue.
int convertCMSampleBufferToPixelArray (CMSampleBufferRef sampleBuffer) {
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
if (imageBuffer == NULL) {
return -1;
}
... |
62,711,866 | 62,711,978 | Why can I std::bind successfully with the wrong parameters? | #include <iostream>
#include <functional>
using callback = std::function<void(int, void*)>;
void AddCallback(callback cb) {}
void foo(int i) {}
int main() {
auto f = std::bind(&foo, std::placeholders::_1);
AddCallback(f);
}
I tried the code with g++ 9.3.0 and clang++ 10.0.0, they both compiled ends no errors.
... | It seems you can pass more arguments to the result of bind than necessary, and they will be silently ignored.
If some of the arguments that are supplied in the call to [the result of bind] are not matched by any placeholders ..., the unused arguments are evaluated and discarded.
— cppreference
|
62,712,012 | 62,724,796 | Nontype Template Array | Is it possible to pass an array as a nontype template argument?
e.g.
template<typename T, T> struct s;
template<typename T, size_t S, T A[S]> struct s<T[S], A>
{ };
| Yes, it is possible, here is an example which is valid in C++11 and later:
#include <cstddef>
template<typename T, size_t S, T A[S]>
struct s
{
static constexpr auto x = A[1];
};
static constexpr int a[3] = {10,20,30};
int f()
{
return s<const int, 3, a>::x;
}
f() returns 20, as seen here: https://godbolt.o... |
62,712,351 | 62,712,679 | Windows keyboard input c++ | I know for linux you can get the keyboard input by reading from /dev/input/eventX. Is there a similar way to get input in Windows? Like knowing when a key is pressed without any 3rd party library
| You can call GetAsyncKeyState, and check the bit 0x8000 in the return value:
#include <iostream>
#include <windows.h>
int main() {
while (1) {
if (GetAsyncKeyState('A') & 0x8000) {
std::cout << "'A' key is pressed\n";
} else {
std::cout << "'A' key is not pressed\n";
}
Sleep(250);
}
}
... |
62,712,790 | 62,713,124 | Does boost have an "compact optional" where presence is encoded by special value of type? | I am looking for space efficient implementation of optional (sizeof small_optional<T> == sizeof (T)).
So the emptiness is encoded using some special value of T, for example
small_optional<int, -1>
requires that I never store -1 in the small_optional so -1 can be used as magic value to determine if optional is empty o... | The markable lib was created for this sole purpose:
Markable 1.0.0
An alternative to boost::optional<T> which does not store an additional bool flag, but encodes the 'empty' state inside T using a special indicated value.
Usage
Do you want to store a possibly missing int? Can you spare value -1?
You can use it like th... |
62,713,326 | 62,713,385 | Diffrence between node *temp; and node *tmp = new node; | struct node
{
int data;
node *next;
} * save;
Can anyone explain what's the difference between below declarations, does stack & heap-based memory allocation is the only difference between them or any other?
Can we call both of them as object pointers?
node *temp;
and
node *tmp = new node;
| The new operator denotes a request for memory allocation on the Free Store. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.
Syntax to use new operator: To allocate memory of any data type, the syntax is... |
62,713,716 | 62,714,288 | Create QLabel besides the constructor | I have a vector of labels, declared in the MainWindow class:
QVector<QPointer<QLabel>> labels;
And a function:
void MainWindow::testFunc()
{
for(int i = 0; i < 5; ++i) {
labels.push_back(QPointer<QLabel>(new QLabel(this)));
labels.back()->setGeometry(QRect(50 * i, 0, 50, 50));
labels.back()... | QMainWindow alwayd should have a centralWidget that contains other chilrens. when using forms, centralWidget is automaticly created. you may manage labels in a horizontal layout and then add them to the centralWidget:
QPointer<QHBoxLayout> hBoxLayout (new QHBoxLayout);
for(int i = 0; i < 5; ++i) {
labe... |
62,713,725 | 62,713,831 | how do functions read pointers? | im new to c++. I made this simple program using classes which does simple stuff like change instances of objects and copying objects.
But I'm confused how functions like std::strlen() read pointers.As far as i know pointer is just an address to another variable.If i pass in derefrenced pointer in std::strlen(*c) i get... | std::strlen receives as an argument a pointer to the beginning of the string:
std::size_t strlen( const char* str );
Returns the length of the given byte string, that is, the number of characters in a character array whose first element is pointed to by str up to and not including the first null character. The behavi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.