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,170,217 | 65,170,581 | Stb Image not loading in data correctly | Im using the stb_image.h library and my goal is to get the rgb data for each of the pixels of a jpg. But when I call the load function, it only gives me a bunch of weird symbols and not actual numbers. Could this be due to the image or is my code just wrong?
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#in... | The output stream (std::cout in this case) will interpret 'char' types as characters. If you want to see the numerical values, you can cast the values to an appropriate type. For example:
unsigned char const value = 'c';
std::cout << value << std::endl;
std::cout << static_cast<unsigned int>(value) << std::endl;
... |
65,170,262 | 65,170,412 | Using pointers to muliply numbers bigger then intMAX | I have 2 very big numbers that are stored in pointers, for example the number:1234567891234567891234567890 is stored: 123 456 789 012 345 678 901 234 567 890. With to of those big number I need to do multiplication and store it in another pointer.
A cijfervakje is one of those groups of 3.
gg&object, is the adres too t... | Okay, some of your question doesn't make sense. First, don't use pointers to do math. I don't think that's actually what you're doing, though.
You're using pointers to objects of type cijfervakje, but you don't provide that code, so we have no idea what that does.
Do you know about the different types of integers in C+... |
65,170,338 | 65,170,358 | Why std::invoke_result_t gives other return type for a callable than a trait? | Snippet:
#include <functional>
template <typename T>
struct CallableTrait;
template <typename R, typename... Args>
struct CallableTrait<std::function<R(Args...)>>
{
using ReturnType = R;
};
template <typename Callable>
using CallableTraitT = CallableTrait<decltype(std::function{std::declval<Callable>()})>;
cons... | Because that's how the language works.
A function's return type can be nominally const-qualified (and that's what you're getting out of CallableTrait), but the actual result of invoking such a function (i.e. the expression containing the function call) has the const stripped off if it's a built-in type (for being usele... |
65,170,364 | 65,171,625 | Is it possible to return an exit code from a thread in C++? | I'm learning C++ and I'm currently working on a program with two concurrent threads. In the debug window in Visual Studio, it's always telling me that:
The thread x has exited with code 0 (0x0).
I want to return an exit code from my thread so that visual studio can display the exit code in the console like it does wi... | You'll need to use platform-specific threads instead of std::thread.
In Windows you would use CreateThread. In Visual Studio there is _beginthread and _beginthreadex (use the later only, _beginthead is not recommended), that should be used instead of CreateThread, although currently there's no much difference. When usi... |
65,170,605 | 65,172,366 | I copy/pasted/modified a dependency in my project. This was not a smart dependency management strategy. How do I step back? | Context:
MainProject depends on a header-only dependency Module.
Both MainProject and Module are:
still under development and subject to modifications
modern CMake projects
independent repositories on Github
controlled by me
Problem:
Few months before, I tried without success to manage this dependency using CMake and... | Your Module project literally is a Git submodule: an independently-updated history, from which your MainProject builds use specific revisions.
Developing MainProject led to add features and modify interfaces in the Module local copy. Now there are two diverging Module
Quickest: from a clean checkout of your current M... |
65,170,766 | 65,170,848 | STD function to return the first iterator where a subsequence begins | Is there a way to return a distance between the first iterator of a sequence, which yields the start of a subsequence in case it is contained within the sequence?
I know there is std::includes which returns true if a sequence is a subsequence of another. And it can take a Compare object.
My first guess was to have an o... | It seems you are looking for std::search.
|
65,171,011 | 65,172,854 | Use DPC++ oneAPI to improve performance | I am new to OpenCL/OneAPI. How can I change this nested loop to use oneAPI GPU:
try {
for (int i = 0; i < count; i++) {
for (int j = 0; j < count; j++) {
if (a_array[i] * a_array[j] == max) {
p_found = a_array[i];
q_found = a_array[j];
... | Here is how an OpenCL kernel for the task would look like:
#define count 1024
#define max 1.0f
kernel void find(const global float* a_array, gloabl float* pq_found) {
const uint n = get_global_id(0); // parallelized across nested double loop
cosnt uint i=n/count, j=n%count;
const float a_arrayi=a_array[i], ... |
65,171,520 | 65,171,699 | how can i use aggregation while separating my classes into a .h and .cpp files? | Context
My professor gave me a task to make a program using aggregation between 2 classes while also separating the classes into a .h and .cpp files.
My solution
The header file containing the class declaration:
#include <iostream>
#include <string>
using namespace std;
class medicalCompany {
private:
string ceoNa... | You can either:
replace void origin::address(){cout << country.location;} by void origin::address(){country.location();}
or by void origin::address(){cout << country.locate;} if you put the locate member as a public variable.
Also, few remarks:
Generally you would prefer avoiding exposing private members, so the f... |
65,171,700 | 65,172,613 | expected primary-expression before ‘.’ token cpp | I am only starting with cpp and trying to use custom structure.
which looks like this :
typedef struct ws2811_t
{
uint64_t render_wait_time; //< time in µs before the next render can run
struct ws2811_device *device; //< Private data for driver use
const rpi_hw_t *rpi_hw; ... | Here bulk and basic transcription C -> C++ of your code.
struct is class with all public by default.
struct ws2811_t{
uint64_t render_wait_time; //< time in µs before the next render can run
struct ws2811_device *device; //< Private data for driver use
const rpi_hw_t *rpi_h... |
65,171,926 | 65,171,982 | Tagged pointer CRTP accessor class | I am about to implement tagged pointer which uses unused address bits to hold a payload. I am searching for effective way to access the payload. The declaration is as follows:
template<typename T, template<class> class PAYLOAD, DeleterType DELETER = DefaultDeleter<T>, size_t ALIGNMENT = alignof( T )>
class tagged_ptr;
... | template<typename T, template<class> class PAYLOAD>
class tagged_ptr : public PAYLOAD<tagged_ptr<T,PAYLOAD>> {};
Live example.
|
65,171,984 | 65,172,156 | Rendering and testing, does the driver matter? | I am developping a rendering engine (a tiny one ahah)
I want to write regression test, to be sure that I don't introduce bug when I add a new feature.
If I develop a compute shader, or something that transfer data from a buffer to a buffer, test is easy. We fill the first buffer, and we check if, after transfering, the... | Neither Vulkan nor OpenGL provides any guarantees about binary identical results across different implementations. Even a driver update for the same card can produce different results.
The best you can do for something like that is get a result that is "close" to the expected result.
|
65,172,234 | 65,172,377 | Why QList is not working as model to QML GridView? | I have problem setting the model to GridView in QML from C++ side. From the documentation about setting Model to GridView in qml it says:
If a C++ model class is used, it must be a subclass of
QAbstractItemModel or a simple list.
In my case my data is numbers in matrix (9x9), so I thought easiest way would be using s... | One possible solution is to use QVariantList:
QVariantList test;
test << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 11;
engine.rootContext()->setContextProperty("gridModel", test);
On the other hand, the conversion of QList<int> and QList<QString> to the QML Array in a transparent way is valid, that can be verified because th... |
65,172,350 | 65,172,460 | Is it possible to explicitly redefine a local variable | I have a macro for calling a function and logging that the call was made
#define LogHandle(message,function) {Log(message + #function); function;}
The function also returns if it was successful or not, i can use a member variable like
#define LogHandle(message,function) {Log(message + #function); m_lastLogHandleResult... | I would implement it using a combination of macros and functions.
A macro so we can get the function "name", which calls a function passing the "name" and which returns the result to be tested.
Perhaps something like this:
#define LogHandle(message, function, ...) LogHandleHelper(message, function, #function, __VA_ARGS... |
65,173,053 | 65,222,577 | b2 install command does not run | I want to install Boost.Build, but if I want to run this command like in the tutorial:
D:\boost_1_74_0> ./b2 install --prefix=C:\BoostBuild
Then I get this error message:
D:/boost_1_74_0/tools/build/src/tools\gcc.jam:164: in gcc.init from module gcc
error: toolset gcc initialization:
error: provided command '-w64-ming... | I forgot to edit "user_config.jam", which is in %HOMEDRIVE% or %HOMEPATH%.
|
65,173,097 | 65,173,631 | When an object’s destructor in C++ would be called? | (C++ related questions)
Select each of the following instances in which an object’s destructor would be called.
1.Static variable goes out of scope (Correct Answer)
2.When delete is called on a pointer to an object (Correct Answer)
3.Dynamic variable goes out of scope
4.When the garbage collector is called
I know for 4... | When does an object's lifetime expire and its destructor is called?
Depends on the objects Storage Duration type:
Automatic: When execution exits the scope the variable is declared in.
Dynamic: When delete is called on the pointer.
Static: In reverse order of creation after main() exits.
thread: In reverse order of ... |
65,173,505 | 65,173,713 | Use constructor parameters outside constructor in constexpr class | I am trying to implement matrix-like class, using an std::array to actually store the data. All of the data is known at compile-time.
I want to be able to use initializer-lists to initialize the Matrix. Something along the lines of
Matrix m = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
I also want to be able to s... | Before C++17 there is no deduction of template arguments for a class template, so this is not possible.
From C++17, you can write this deduction guide:
template<int m, int n>
Matrix(float const (&)[n][m]) -> Matrix<m, n>;
and add an extra pair of braces when constructing the Matrix:
Matrix m =
{
{
{1, 2, 3},
{4,... |
65,173,629 | 65,502,126 | What loop should I use for the Question posted down below? | Question is how to get the program to ask for input until a valid choice (4-20) is given by the user? I just need to know how to repeat a question. So if a user inputs the wrong number then it will ask the user to input a valid number until the user enters a correct number between 4-20.
#include<iostream>
#include<cstd... | Try this
while(1)
{
cout << "Please enter a number between 4 and 20: ";
cin >> num;
if (num >= 4 && num <= 20)
{
//mods random number
//do something
break;
}
}
|
65,173,668 | 65,173,690 | C++ Use alias for 'typename'? | I'm working with templates, and it's getting kinda tedious to write "typename" multiple times.
Is it possible to assign an alias to it? I understand that the below doesn't work, is there any other ways?
typedef typename tn;
| You might use MACRO
#define tn typename
|
65,173,696 | 65,174,742 | Qt disconnectFromService() not actaully disconnecting bluetooth device? | I'm connecting a pair of bluetooth headphones to my windows pc using Qt's QBluetoothSocket class as follows:
device->connectToService(QBluetoothAddress(device1Info[1]), QBluetoothUuid(QBluetoothUuid::SerialPort));
and to disconnect the headphones I use:
if (device->state() == QBluetoothSocket::ConnectedState) {
de... | The disconnection doesn’t disconnect the device, it just disconnects the socket. It’s just as if you closed a network socket - it won’t disconnect your PC from the network :)
I can’t reproduce the connection succeeding though - not unless your headphones do offer a serial port service for debugging or something.
My gue... |
65,173,800 | 65,173,881 | Different behaviour of unique_ptr vs raw pointer | I am struggling to understand the difference in behaviour of a raw pointer and a unique_ptr. I have class A with a variable x and class B with a pointer to an instance of A:
class A
{
public:
int x;
};
A::A(int y) : x(y)
{
}
class B
{
public:
B(A &);
A *p;
};
B::B(A &a)
{
p = &a;
}
This behaves as I... | make_unique creates a fresh object, one that that unique_pt has exclusive access to. So in the second example you have two objects, not one and when you set change the value of a.x in the first object it doesn't effect the other object held by the unique_ptr.
|
65,173,858 | 65,174,682 | Detecting overloaded method from parent class | I have been using this utility below to detect if a member method has been defined in a class, which works in most of the cases in my framework.
template <typename C, typename TInput>
class HasHandle
{
template <class T>
static std::true_type testSignature(void(T::*)(const TInput&));
template <class T>
... | Removing template for testSignature makes all compilers happy:
template <typename C, typename TInput>
class HasHandle
{
static std::true_type testSignature(void(C::*)(const TInput&));
template <class T>
static decltype(testSignature(&T::HandleEvent)) test(std::nullptr_t);
template <class T>
static... |
65,174,128 | 65,174,240 | Arduino: undefined reference to `Class::attribute' | I am developing a library Button to handle some functions of buttons and a class ButtonManager handling the query of the states of those buttons. I don't want to have to create an object for the ButtonManager class so I figured I had to use the static keyword for every attribute and method. In addition I am using a thi... | static ButtonListItem* head = NULL;
If you want to use static data members you must also define them. Declaration of such a member is not a definition.
Put this line at the top of your .cpp file (below #include):
ButtonListItem* ButtonManager::head = NULL;
You may need to also remove = NULL from the declaration in th... |
65,174,329 | 65,174,373 | Print numbers with 4 decimal places on a single line | Is there a way to print numbers in a single line and regardless of anything?
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
double r;
double n = 3.14159;
cin >> r;
cout << "A=";
cout << std :: fixed;
cout << std :: set... | With std::cout, you can just combine them with the << operator like this:
cout << "A=" << std :: fixed << std :: setprecision(4) << n * r * r << "\n";
|
65,174,661 | 65,174,947 | C++ : Assigning 2 constructors with 2 different variables doesn't work | I wrote 2 contructors in my program with 2 different variables . However when calling them in main() I get an error saying :
main.cpp:23:11: error: no match for call to '(Basis) (const char [5])'
a("test");
This is my program :
#include <iostream>
using namespace std;
enum Test{Mo,Di};
... | Well I guess this here answers my question . Dunno why no one mentioned it .
Just had to add a void operator to my public class
#include <iostream>
using namespace std;
enum Test{Mo,Di};
class Basis
{
public:
Basis(Test a)
{
cout << a;
}
void operator()(s... |
65,174,699 | 65,174,805 | char tab is setting tab[0] to 0 | I have this code:
#include <iostream>
#include <cstdlib>
#include <stdio.h>
int main()
{
std::string napis = "Inhibitor";
int length = napis.length();
char hex[256];
std::cout << "Original: " << napis << '\n';
for (int i = 0; i < length; i++)
{
char buffer[2];
itoa(napis[i], b... | The itoa function will write a terminating nul character into the buffer. In your code, this it will write 2 or 3 characters (depending in the ASCII value of the character in the string), which can exceed the array bounds.
The solution is to increase the size of buffer by at least 1:
char buffer[4];
Even better is to ... |
65,174,872 | 65,175,358 | Qt: .pro file missing? | I tried to create a C++ project with Qt I stumbled across different kinds of guides which all refer to a special '.pro' file inside the project where I have to adjust a setting so the SQL part takes effect.
My problem: whenever I create a new project - doesn't matter whether its with qbs, qmake, or cmake - the project ... | TL;DR: Use cmake. Forget about qbs and qmake.
Whenever I create a new project - doesn't matter whether its with qbs, qmake, or cmake - the project structure/ folder is lacking the '.pro' file.
A qmake project will have the .pro file, since that's the project file for qmake. Maybe you're looking in a wrong place? A qb... |
65,175,336 | 65,176,531 | No matching function for call to a member function in class | I am new to C++ and trying to make a program to calculate bond price, the original code works well but I have difficulties transferring it to OOP. mode. The program uses two arrays and a integer to do calculation. I used a loop in constructor to initialize data members (learned from stack over flow). it looks fine but ... | There are two problems in your code.
Definition does not match call. You defined Bcalculator as:
void Draft::Bcalculator(int sizeofArray, double term[], double cFlow[])
But then you call it without arguments:
Draft::Bcalculator();
To be able to call Draft::Bcalculator() you need to add static in the definition:
stati... |
65,175,812 | 65,175,825 | How to simplify checking if a pair of numbers is (1,2) or (2,1)? | I need to make sure that a pair of numbers is either (1, 2) or (2, 1). Both x and y are always positive. The code I am using right now:
if ((x == 2 && y == 1) ||
(x == 1 && y == 2)) {
return 1;
}
It looks a little bulky, and I feel like it can be simplified. However, everything I tried resulted in false positi... | This is the most direct way to make this comparison.
It is also more readable than any alternative you may come up with, so no need to change it.
|
65,176,399 | 65,177,746 | Setting up Qt for use in a project in Visual Studio | I am trying to use Qt to make a simple GUI program in C++ using Microsoft Visual Studio. It's for a school project, but my professor has given very little guidance on how to get the Qt library working in Visual Studio, and I can't seem to follow the information given on the website. I know it's a big ask, but would any... | I recently installed and used QT at home using VS19 Community and latest QT Open Source.
The following YouTube video should help you get started.
Configure VS19 to create QT5 Apps
The Summary:
Install QT: Choose advanced, and install the latest version of QT + the support for version of Visual Studio you are using.
... |
65,176,497 | 65,211,527 | C++ static data member initialization error in Eigen | I'm using gcc-10 and Eigen 3.3.9 on Ubuntu 18.04. This snippet compiles and runs fine:
struct S {
static inline Eigen::Vector3f u{1, 1, 1};
};
int main() {
Eigen::Vector3f u(1, 1, 1);
}
but the latter version of initialization when applied to static data member, fails to compile:
struct S {
static inline Eigen:... | As discussed in the paper that added the feature, it was desired that default member initializers support forward lookup for consistency with (constructors’) member initializers. However, member function parameter lists are not such a complete-class context. That leads to ambiguity between function and variable decla... |
65,177,399 | 65,178,320 | Alignment of multiple CRTP base classes | In CRTP, the base object can return a reference to the derived object via static cast.
Is this also true in the case of multiple inheritance? The second base and beyond might be at addresses different from the derived object. Consider for instance:
#include <iostream>
#include <string_view>
template<typename Derived>
... | Yes, this is defined, your code is OK. Multiple inheritance is the rare case in which the casted pointer differs from the original.
If you go to the Source:
[expr.static.cast.11] A prvalue of type “pointer to cv1 B”, where B is a class type, can be
converted to a prvalue of type “pointer to cv2 D”, where D is a
comple... |
65,177,439 | 65,177,943 | c++ std::bind universal reference can't compile | #include <functional>
#include <iostream>
#include <type_traits>
using cb_t = std::function<void ()>;
template<typename CB_T, std::enable_if_t<std::is_constructible<cb_t, CB_T>::value, bool> = true>
void
on_my_write(int a, int b, CB_T&& cb) {
std::cout << "on_my_write:" << a << ", " << b << std::endl;
}
templa... | Yes, this is slightly tricky. std::bind is of course not magical, it has to store the bound parameters somehow and it stores them as values by default, unless requested with std::ref argument.
Meaning that in the callstd::bind(...,std::forward<CB_T>(cb)), the cb is used to construct the bound member variable properly u... |
65,177,843 | 65,177,949 | Vector of new vectors | Suppose I have a vector of dynamically allocated vectors, something like:
std::vector<std::vector<double>*> map;
Do i have to deallocate each of the vectors inside map manually or are they deallocated automatically by the vector destructor itself?
If I have to do it manually is this a good way to go:
for(auto& t : map... | You would need to free them with delete not delete [] because a vector is not an array.
But I wouldn't see any reason why you wouldn't use
std::vector<std::vector<double>>
This way you wouldn't need to worry about the allocation of the vector
|
65,177,850 | 65,178,573 | Qdebug, QDialog, QMainwindow in visual studio 2019 | i'm new to c++ and QT programming and this question could be super stupid for you..
I'm trying to run a third parties program with visual studio 2019..it uses opencv, boost and QT libraries... through windows power shell and vcpkg I've successfully installed all the opencv and boost libraires but i'm not able to fix th... | You need to download qt,qt is a is a development tool,after you installed qt , you can configure in vs, add the qmake and others qt tools.
|
65,178,460 | 65,182,291 | C++ - Sorting strings in a vector in a specific way | I'm currently attempting to sort strings in a vector, but I'm unsure on how to go about doing it a specific manner. The game engine I am working with requires strings to be sorted case-insensitively (which I have been able to accomplish). It also sorts these file names with underscores coming before letters.
For exampl... | Use std::sort with lambda.
If original strings are not to be modified then:
std::sort(vec.begin(), vec.end(),
[](std::string s1, std::string s2){
std::transform(s1.begin(), s1.end(), s1.begin(),
[](char c){ return std::tolower(c); });
std::transform(s2.begin(), s2.... |
65,178,703 | 65,178,753 | C++ Floating Point Addition (from scratch): Negative results cannot be computed | I am implementing a floating point addition program from scratch, following the methodology listed out in this PDF: https://www.cs.colostate.edu/~cs270/.Fall20/resources/FloatingPointExample.pdf
The main issue I am having is that addition works when the result is positive (e.x. -10 + 12, 3 + 5.125), but the addition d... | At step 5, you’ve already added the mantissas. To determine whether the result is positive or negative, just check the sign bit of that sum.
|
65,178,772 | 65,239,294 | QTableView in a popup on a QPushButton click | Click the button, a table control appears next to the button, click the blank space or the content in the control to close.
I have two ideas:
With the popmenu, can click the blank space or the content in the control to close the control, but it does not meet my needs for a table-type control
New a tableview, but I don... | If you can make all of this in the same window, it's simple...
To position the QTableView below the QPushButton you will use Qt Designer, and setup the QTableView to hide();. And when the QPushButton is clicked, he setup the QTableView to show();.
An show(); example:
QTableView *nametable = ui->tableView;
nametable->sh... |
65,178,981 | 65,254,559 | How to minimize window with x11 c++? | I have QQuickWindow * _mainWindow and in OS Windows I just write
::ShowWindow(reinterpret_cast<HWND>(_mainWindow->winId()), SW_MINIMIZE);
and it's works! But I do not know how it make in OS linux, I googled about x11 library, but don't understand how use it. Please help.
I try minimize application window because in QML... | #include <X11/Xlib.h>
#include <QX11Info> // from qt q11extras
// function for minimze your app
XIconifyWindow(QX11Info::display(), _mainWindow->winId(), QX11Info::appScreen());
|
65,179,034 | 65,179,790 | Convert HEX MAC-Address to WCHAR Array in C/C++ on a WinCE 6 Device using wprintf() | The last days, I've been searching and reading through several dozens of questions on ere that sound similar to my problem, but I have not yet managed to get any solution to work.
Consider the following, simple scenario:
I am programming a C/C++-App for an HMI-Device running on Windows CE 6.0. For our custom sources to... | In your example you use wprintf with a target buffer, I think you want swprintf. wprintf will use whatever is in your macString as a format and your format will be a parameter as it is written above.
|
65,179,312 | 65,179,573 | How dynamic-linking know where to find the linked files? | I read from some book which says this fact about dynamic-linking:
For example when executing this command:
gcc main.o lib.so.
The main.o doesn't copy any infomation of lib.so.
Instead, the ld-linux.so copy infomations about lib.so into ld-linux.so.
main.o only try to linking files when execute main.out, then it turn to... | It is well described in the man 8 ld-linux.so man page (links to proper upstream, Linux man-pages project).
In short, simplified a bit (ignoring preloaded libraries, ELF DT_RPATH/DT_RUNPATH, and various options in the binary itself that needs those dynamic libraries):
ld-linux.so looks the library up in the directories... |
65,179,332 | 65,179,423 | Invalid operands of types 'float*' and 'float*' to binary 'operator*' | I don't know why I get this error. It's like a*a treats the a* as a pointer (float* to float* is it the same as float to float ). Apparently the problem is kind of resolved when I declare a in the sub classes, but the point is that I want my sub classes automatically to have that from my parent class.
One more thing wh... | You have undefined behavior as f is not initialized:
GeometrijskaFigura *f;
int x;
std::cin >> x;
f->setA(x); // UB: use uninitialized f.
Should be
int a;
std::cin >> a;
Jednakostranicni j;
j.setA(a);
std::cout << "Jednakostranicni-P: " << a.P() << " O: " << a.O() << std::endl;
Kvadrat k;
k.setA(a);
std::... |
65,179,398 | 65,179,658 | The syntax for smart pointer | In this declration for a unique pointer
std::unique_ptr<SDL_Window, void(*)(SDL_Window*)> window_;
I could not find any resource with this kind of decration so my guess is that we create a pointer and pass it to the function and the return value is stored in window_
| No, this is just declaring the variable window_, it doesn't initialize it at all.
The resource you're looking for is here:
template<
class T,
class Deleter = std::default_delete<T>
> class unique_ptr;
It's just declaring a unique ptr with a non-default deleter: the void(*)(SDL_Window*) part is the type of a func... |
65,179,735 | 65,180,536 | modulo operation not returning correct value | I'm trying to solve a problem in leetcode, I have cracked the algorithm for that specific problem, written pseudo code, and implemented the code in C++. Just one flaw remains in the solution, modulo 1e9+7 the result.
The problem statetment : Given an integer n, return the decimal value of the binary string formed by co... | Your main problem was that you use log instead of a logarithm in base 2: log2.
Besides, it is generally better to avoid floating point calculations in such a situation.
In the following code, I have included a corrected version of your code,
and a new simple version without any floating point calculation
#include<cmat... |
65,180,078 | 65,180,449 | Why does my corner-widget not show up in QTabWidget? | I have a QTabWidget and I would like to have two push buttons in the top right corner.
I use this code to add a vertical Layout as the corner widget and add two buttons to it:
QWidget* cornerWidget = new QWidget();
QVBoxLayout* vbox = new QVBoxLayout();
QPushButton* button1 = new QPushButton("Button 1");
QPushButton* b... | Cause
The place for the corner widget is restricted. You use a vertical layout and its contents margins move the buttons down, out of sight.
Solution
Use a horizontal layout and set the contents margins to 0.
Example
Here is an example I wrote for you to demonstrate how the proposed solution could be implemented:
auto ... |
65,180,148 | 65,195,047 | How to upload file through HTTP protocol with C++? | I'm going to upload files with C++, to a Java spring boot web server.
I constructed the protocol looks like below (in plain text):
POST /gallery/multimedia/uploadvideo HTTP/1.1
Host: 192.168.0.133:8981
Content-Type: multipart/form-data; boundary=------boundary1804289383
Connection: keep-alive
--------boundary180428938... | Firstly, thanks for @strupo 's suggestion.
By turning on --trace option of curl and viewing the output log file, I finally fixed this problem.
In curl, it posts file by several packets:
The header:
POST /gallery/multimedia/uploadvideo HTTP/1.1
User-Agent: curl/7.29.0
Host: 192.168.0.133:8981
Accept: */*
Content-Length:... |
65,180,303 | 65,199,134 | C++ when i try get string, it always empty, lambda | I have object of class
class MenuItem {
public:
void updateInputText(string text)
{
this->text += text;
}
string getText() const {
return this->text;
}
void trigger(Event event)
{
switch (event) {
case ENTER:
this->onEnterAction();
... | Surt gave me a hint... Scope.
All MenuItems pushed to vector, and when i use this function
next.onEnterAction = [&] () {
Log::write("IP: " + IP.getText());
};
I try to get text from empty variable, when i changed function to
next.onEnterAction = [&] () {
auto selectedIP = std::next(currentMenu.begin(), 0);
... |
65,180,347 | 65,180,609 | Getting an uncopyable object out of a try | I have the following class:
class ShaderProgram {
private:
GLuint shaderProgram;
std::string getCompilationError(GLuint shader);
std::string getLinkingError(GLuint shaderProgram);
public:
// ! Might throw exception !
ShaderProgram(const std::string &vertexShaderPath, con... | If you just want to terminate when the exception occurs you can use a immediately invoked lambda expression to initzialize the object. As a simplified example:
#include<iostream>
#include<cmath>
struct ShaderProgram {
ShaderProgram(const ShaderProgram&) = delete;
ShaderProgram() {
throw 1;
}
};
in... |
65,180,554 | 65,180,927 | Why can't a bit field be split between different underlying types? | Why does the sizes of these two structs differ?
#pragma pack(push, 1)
struct WordA
{
uint32_t address : 8;
uint32_t data : 20;
uint32_t sign : 1;
uint32_t stateMatrix : 2;
uint32_t parity : 1;
};
struct WordB
{
... |
Why can't a bit field be split between different underlying types?
It can in the sense that standard allows it.
It wasn't because that's what the language implementer (or rather, the designer of the ABI) chose. This decision may have been preferred because it may make the program faster or the compiler easier to impl... |
65,180,599 | 65,186,765 | How do i extract dragged & dropped filenames from a DROPFILES struct | I have a window with no controls with WS_EX_ACCEPTFILES enabled and the event triggers successfully when dragging files from explorer. What I need to do is extract the files to a vector. From what I've read, the wParam is supposed to contain the location of the files within a DROPFILES struct but I don't know how to ac... | Per the WM_DROPFILES documentation:
Parameters
hDrop
A handle to an internal structure describing the dropped files. Pass this handle to DragFinish, DragQueryFile, or DragQueryPoint() to retrieve information about the dropped files.
lParam
Must be zero.
Simply type-cast the wParam to HDROP and call the drag-drop func... |
65,180,619 | 65,180,885 | std::filesystem:file_size send me an incoherent value | In order to read a file in my code, I use std::filesystem::file_size (https://en.cppreference.com/w/cpp/filesystem/file_size) to get his size. I use this code :
template <typename TYPE>
inline void read_binary_file(const fs::path filename, std::vector<TYPE>& result)
{
std::ifstream file(filename, std::ios::in | std... | There is a bug that will be corrected in recent versions of MinGW. cf:
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=95749
But event that, should replace
size_t filesize;
by
std::uintmax_t filesize;
according the function's signature :
std::uintmax_t file_size( const std::filesystem::path& p );
|
65,180,953 | 65,181,140 | If char *name = "Emma", why is &name not the same as &name[0]? | I've been following CS50 and I'm pretty sure I keep hearing that a pointer is just an address
And that the address of an array is just the address of the first item in that array
But when I run the following code:
// we can also just create strings we need by using char * like this
char *name = "Emma 123";
char *anothe... | char *name = "Emma 123";
name stores the address of first element ('E').
&name is the address of name. It is a pointer to pointer.
&name[0] = &(*(name+0)) = (address of first element) = name
|
65,181,027 | 65,184,945 | debugger wont show the pointed variable | I am debugging a code and there are 2 issues.
the debugger showed me the inner fields of each pointer, but suddenly it just wont, I dont know what changed or what did i click, but when i try to acsses the inner fields (like writing something into the pointed variable) it indeed shows me the correct variable, so it is ... | I have no idea about the first part of the question, but for the second part:
for some reason my program runs on debugging mode but encounter some sort of an unkown infinite loop when i run it regularly. Howcome?
This is very common.
In 99.999% of instances this happens because your program exercises undefined behavi... |
65,181,116 | 65,182,004 | Why multithreading in c++ DLL get error C3867 when building? | I am using VS2019
Trying to call a thread in DLL. to run two executables simultaneously with detach
following threads worked when I Run a normal c++ program
I get error
Error C3867 'myClass::runexeone': non-standard syntax; use '&' to create a pointer to member myGateway C:\Users\user\Downloads\Demo\myGateway\mypl... | As MSalters already mentioned, you provided the wrong data type for the functor for std::thread. If you cannot make the method static (which you can actually at least for the current state of your code, but to let this not be unstated here), you can do this
void onStart()
{
std::thread(std::bind(&myClass::rune... |
65,181,266 | 65,184,551 | IDL file containing template methods | Is it possible to include a parametrized method in an IDL file like this:
runtimeclass A
{
A();
T f<T>();
};
What are the alternatives?
| The Windows Runtime type system only supports a fixed set of generic types, namely the types in the Windows.Foundation namespace (such as IAsyncOperation<T> and EventHandler<T>) and those in the Windows.Foundation.Collections namespace (such as IVector<T>). Even these generic types must be specialized with a concrete t... |
65,181,463 | 65,181,706 | Cannot get name of running processes in windows | I just want to display all running processes on the console.
#include <iostream>
#include <windows.h>
#include <tlhelp32.h>
using namespace std;
int main(){
PROCESSENTRY32 pe32;
HANDLE snap = CreateToolhelp32Snapshot(
TH32CS_SNAPPROCESS, 0
);
if(snap == INVALID_HANDLE_VALUE) {
cout <<... | You're probably trying to print a WCHAR* to std::cout. You might need std::wcout. In general, Windows (since 2000/XP) uses Unicode/UTF-16.
|
65,182,051 | 65,186,330 | Why not use std::memory_order_acq_rel | I am learning the code of cppcoro project recently. And i have a question.
https://github.com/lewissbaker/cppcoro/blob/master/lib/async_auto_reset_event.cpp#L218
https://github.com/lewissbaker/cppcoro/blob/master/lib/async_auto_reset_event.cpp#L284
if (waiter->m_refCount.fetch_sub(1, std::memory_order_release) == 1) //... | Because this is not how memory orders work.
We add a memory barrier to our atomic operation in order to achieve two things:
to prevent relaxed atomic operations and non-atomic operations from being reordered.
to synchronize non atomic data across threads
I wrote an answer here that explains these two points more cle... |
65,182,150 | 65,182,272 | C++ make new thread function with default parameter | Heyo everyone,
I'm currently playing around with threading in C++ and stumbled upon one quirk i couldn't quite find an answer to:
in my programm is a worker class which handles creating, and talking about a thread which does X.
worker::start(string filename){
thread t(&worker::readfile,this,filename,10);
t.detach... | In C++, there's a difference between default parameters and overloads, even though they can achieve similar effects. For instance, you could have written this instead:
class worker {
void readfile(string filename, int LinesToRead);
void readfile(string filename) { readfile(filename, -1); }
// ...
This overload achi... |
65,182,174 | 65,182,830 | Match regex multiple times in one std::string | From today's advent of code we had input that could be a list of several bags.
A string like "3 drab lime bags, 1 drab plum bag, 2 vibrant tomato bags, 1 plaid blue bag."; was for example in my input.
What I did to solve this: split it among the ',', and then apply std::regex bag_regex("([0-9]+) (\\w+ \\w+) bag"); to e... | You could use the last parameter in regex_token_iterator as an array of subgroups (considering 2 groups (number and color) you want).
The following snippet doesn't do any error checking and assumes you input string is valid:
using Pair = std::pair<int, std::string>;
Pair p;
const int subgroups[] = {1,2};
std::vector < ... |
65,183,129 | 65,184,827 | compare two c-style strings without strcmp() and operator overloading |
Modify class Date in Fig. 10.10 to have the following capabilities:
a) Output the date in multiple formats such as:
DDD YYYY
MM/DD/YY
June 14, 1992
b) Use overloaded constructors to create Date objects initialized with dates of the formats in part (a).
I am stuck in part b of this problem; For the third format, I m... | If you are not allowed to use strcmp or the c++ string library,
you could either do the raw loop your self:
bool string_compare(const char* a, const char* b)
{
if (bool(a) != bool(b)) return false;
if (!a && !b) return true;
while (*a != '\0' && *b != '\0') {
if (*a++ != *b++) return false;
}
... |
65,183,266 | 65,183,593 | Wrong assignment to struct | I have structs like this:
typedef struct ws2811_channel_t
{
int gpionum; //< GPIO Pin with PWM alternate function, 0 if unused
int invert; //< Invert output signal
int count; //< Number of LEDs, 0 if channel i... | In your second example, try ws2811_channel_t channel{}; and ws2811_t test{}; - e.g. add the {}.
If you do this, then you'll zero initialise all the members. The key difference between your first (working) version, and the second (broken) version is that first version will zero things like gamma whilst the second versio... |
65,183,550 | 65,185,346 | P/Invoke runtime STD error not redirected to file | I am working with a C++ DLL that I access with P/Invokes from C# code. The problem is I cannot redirect the std error that happens in the unmanaged side to a file. This works well if the build is in DEBUG but when the build is in RELEASE the STD logfile-unmanaged does not contain the error but contains and does not clo... |
This works well if the build is in DEBUG but when the build is in RELEASE the STD logfile-unmanaged does not contain the error
It's probably optimized out, since you don't use the result of the division by zero. Try something like this instead:
extern "C" __declspec(dllexport) int DoException()
{
fprintf(stderr, ... |
65,184,133 | 65,184,134 | Embed / Include Python.h into C++ [Full Guide] (Python 3.9) (Windows) (Qt 5.15) | When I was trying to embed a Python script into my Qt C++ program, I run into multiple problems when trying to include Python.h.
The following features, I would like to provide:
Include python.h
Execute Python Strings
Execute Python Scripts
Execute Python Scripts with Arguments
It should also work when Python is not i... | (This answer and all its code examples work also in a non-Qt environment. Only 2. and 4. are Qt specific)
Download and install Python https://www.python.org/downloads/release
Alter the .pro file of your project and add the following lines (edit for your correct python path):
INCLUDEPATH = "C:\Users\Public\AppData\Loc... |
65,184,255 | 65,184,466 | template non-type template parameter | I am trying to write a constexpr constant concisely using C++20 features.
#include <utility>
template <template <typename T, T ... Ints> std::integer_sequence<T, Ints...> I>
static constexpr long pow10_helper = ((Ints, 10) * ...);
template <std::size_t exp>
static constexpr long pow10 = pow10_helper< std::make_index_... | You cannot directly reference arguments to template template parameters. They are not in scope. But you could do something like this:
#include <utility>
template <class>
class pow10_helper {};
template <template <typename T, T ...> class IntSeq, class T, T ... Ints>
struct pow10_helper<IntSeq<T, Ints...>> {
static ... |
65,184,865 | 65,185,455 | How use signature pattern for hooking | I like to replace the static function address:
AddressOfHookSoundFunction = (DWORD)GetModuleHandleA("myfile.exe") + 0x0F3B65; // good: 4406117 (integer)
using signature pattern becouse is more flexible:
SigScan Scanner;
AddressOfHookSoundFunction = Scanner.FindPattern("myfile.exe", "\x55\x8B\xEC\x83\xEC\x14\x53\x56\... | The problem seems to be that you're not differentiating between pointers and integers. The return value of FindPattern is a DWORD, but what you actually return is a broken address base + i. I'm saying "broken" because on Win64 this loses the top 32 bits of the address.
Regardless, since the returned value is an address... |
65,185,208 | 65,185,364 | Adding together two arrays and print into third array | Before I start I must notice that I am a begginer in C++.
I have a code (see below), In this code I have two arrays with 10 random numbers but In tab_A numbers are the same like in tab_B - I don't know how to solve this. Also I don't know how to merge/add/sum these two arrays in new array tab_C and print result.
#inclu... | In the code, you have called srand twice with the same seed. Hence, the numbers that will be randomly generated will be the same. If you want to generate random numbers it is advisable to set seed only once.
Also, there seems to be an issue in the code. C++ has 0-indexing. Hence, the lines
sumAB=tab_A[10]+tab_B[10];
ta... |
65,185,273 | 65,199,484 | declaration requires an exit-time destructor [-Werror,-Wexit-time-destructors] | What I am trying is to compile WebRtc Library for android and I am getting this mind blowing error. Please if someone could assist me in this matter. I have these implementations:
stream_buffer.h
#ifndef AUDIO_STREAM_BUFFER_H_
#define AUDIO_STREAM_BUFFER_H_
#include <array>
#include <cstdint>
#include <iostream>
#inc... | You can create your map dynamically. Something as, simplified:
class X
{
static std::map<int, int>* ptr_;
public:
static std::map<int, int>& buffer()
{
return *ptr_;
}
static void finalize()
{
delete ptr_;
}
};
std::map<int, int>* X::ptr = new std::map<int, int>{};
... |
65,185,435 | 65,190,126 | AudioQueue doesn't produce any sound. What the problem can be? | I've written a small c++ app for testing AudioToolbox Queue. I am filling the buffer with some random data just to check it works.
static void HandleOutputBuffer(void* inUserData, AudioQueueRef queue, AudioQueueBufferRef inBuffer) {
memset(inBuffer->mAudioData, rand() % 256, inBuffer->mAudioDataByteSize);
throw... | The only problem your code has is that it is not enqueueing enough buffers. AudioQueues seem to like having at least two:
AudioQueueBufferRef buffer;
for (int i = 0; i < 2; i++) {
throwExceptionIfError(AudioQueueAllocateBuffer(queue, 1024, &buffer));
buffer->mAudioDataByteSize = 1024;
throwExceptionIfError(... |
65,185,742 | 65,213,160 | Can you compare nullptr to other pointers for order? Is it always smaller? | This question is based on code that I found that monitors possible memory leaks, so it contains some code that you probably don't want to see in regular programs like ordering pointers.
However, I saw that a pointer was set to nullptr and then the pointer was compared to a maximum address. Is it guaranteed by the C++ s... |
nullptr is always smaller than other pointers for operator<
No, compare a nullptr with a pointer by a relational operator is not supported by the standard.
To compare the operands of a relational operator, the following rule will first be applied to both operands, that is
expr.rel#2
The usual arithmetic conversions ... |
65,186,151 | 65,186,370 | Conversion from lambda to non-scalar type requested | I created this class so I could have a value of any type which is either fixed or recalculated everytime it's used:
template<typename T>
class Value {
private:
bool fixed;
union {
T value;
std::function<T()> get;
};
public:
Value(const T& value) : fixed(true), value(value) {}
... |
Why does assigning work for T and not std::function<T()> and how can I make it so it does?
Your code does not use assignment, but copy initialization and
In addition, the implicit conversion in copy-initialization must produce T directly from the initializer, while, e.g. direct-initialization expects an implicit con... |
65,186,257 | 65,186,514 | Why isn't this std::string_view a constant expression? | I'm relatively new to constexpr programming and am trying to do some basic manipulation of string_view objects in a constexpr context. In my case, all of the strings start as literals in my source code, so it seems like they should be constant expressions. I found that I can construct a constexpr string_view from a str... | A constexpr object's value is required to always be a compile-time constant. Since the function foo doesn't have any control over what arguments are passed to it, the parameter sv cannot be considered a constant expression (the caller may pass a non-constant-expression argument) and thus cannot be used to define it as ... |
65,186,451 | 65,186,607 | Move a QGraphicsPixmapItem through a function | I'm creating a chess game with Qt and now I'm going to add the AI to play against the computer, but I have a big problem... I used the mouseReleaseEvent() function to move the pieces by drag and drop, so now I don't know how to move them without it. Surely I have to create a function that takes the coordinates in which... | You need to retain the pointers to the pieces in MainWindow. Something like:
class MainWindow : public (whatever, most likely should be QWidget not QMainWindow) {
Piece *pieces[8*4] = {}; // so they are null be default
...
};
void MainWindow::start()
{
scene.setSceneRect(-400, -250, 1024, 768);
for (auto... |
65,186,662 | 65,413,068 | Passing dependency in allocator | I've been making interpreter for prototype-based language .
And i found problem i dont know how to solve .
Objects are splited into actual object and object map with slots. Both of them are allocated into heap that is under control of GC.
Implementation of operator new in Object and ObjectMap are practically same:
void... | Ok only way to do this is using factory method to create objects
Objects::Object* Objects::Object::create(Memory::ObjectSpace* memory, unsigned char numberOfSlots){
return new(memory) Object(memory, numberOfSlots);
}
I will pass memory object that i want use and static method will pass it into allocator and construc... |
65,187,042 | 65,187,217 | I keep getting a std::bad_alloc error in C++ | So I am making a program for Project Euler #14 and I have this
#include <iostream>
#include <vector>
using namespace std;
vector <int> CollatzSequence (int n)
{
vector <int> numbers;
int currentNumber = n;
while (currentNumber != 1) {
numbers.push_back(n);
if (currentNumber%2 == 0) {
... | std::bad_alloc is thrown when allocation of memory fails, in your code this happens when allocating memory for std::vector returned. std::vector requires contiguous memory, in your code, the size to be allocated might be causing the problem.
as @WhozCraig said in the comments, the function has no need to return the vec... |
65,187,527 | 65,188,082 | Defining template function with std::is_invocable_v outside of class | I have this class:
template <typename T>
class Value {
private:
bool fixed;
union {
T value;
std::function<T()> get;
};
public:
Value(const T& value);
template <typename F, typename = std::enable_if_t<std::is_invocable_v<F>>>
Value(F&& get);
Value(const T* pointer);
... | template <typename F, typename = std::enable_if_t<std::is_invocable_v<F>>>
Value(F&& get);
Here, std::enable_if_t<std::is_invocable_v<F>> is a default template argument (default value of the second template argument) and you have already specified it in the declaration inside the class. So, when you add an imp... |
65,188,192 | 65,188,332 | SFINAE code to detect whether operator<< is implemented for a type behaves differently on Clang and gcc | I'm just playing around with some SFINAE code and I can't get it to work. I'm using Xcode 12.2 with -std=c++17.
godbolt reveals that Clang does indeed choose the false_type variant no matter what, whereas gcc uses the true_type variant if both template parameters are identical and the operator is implemented, as I woul... | If you replace the whole sizeof construct with 42, both compilers give you an error about how sizeof isn't a bool and cannot be narrowed to one.
If you replace it with 1, there is no error (as 1 can obviously be narrowed to true).
With this in mind, let's pass a bool explicitly:
template<typename T>
struct has_ostream_... |
65,188,873 | 68,990,831 | Is it possible to create an ObjectWrap in node-addon-api with a private js constructor and that can be instantiated in c++ only? | I'm currently writing a node.js addon in c++ using the node-addon-api (Napi). From what I saw in the different docs and tutorials, every objet has to extend Napi::ObjectWrap to be considered as js object. Then the constructor can be called in js.
But what if I want this specific object to be only provided by an other O... | My solution was using the data argument of DefineClass to pass through my argument (in my case only one, but I guess you can pass an array/vector/whatever container with as much as you'd like). Then I created an instance of the "Provided" class and returned it. But an example is worth more than my explanation:
class Pr... |
65,188,998 | 65,189,529 | How to create an struct pointer in another class? | I have 3 classes: Book,Student,LibrarySystem and i need 3 linkedlists to store data, first linkedList is called Node which stores Students, second linkedList is called studenBookNode which stores the books reserved by specific student and my third linkedList is allBooksNode which stores the created book objects
here is... | studentBookNode is a member of class Student. Unless you are writing a member of class Student, this name can be only accessed as Student::studentBookNode.
|
65,189,197 | 65,189,364 | Calculate how many days are required for a snail to climb up a wall | I am trying to solve this problem:
Write a program to calculate how many days are required for a snail to climb up a wall. A snail climbs on a wall, it starts at the bottom and climbs up n meters a day. Regretfully, every night it slides m meters down. Given the height of the wall H, write a program to calculate how m... | Your error is that you are only checking if the snail has reached the top of the wall after it has climbed up and down. You even say this yourself. Instead you should check the height after the climb up only
Here's loop that does that.
for (;;) {
current_height += meters_per_day;
if (current_height >= wall_heig... |
65,189,335 | 65,191,072 | What type of C++ cast should be used to cast a pointer to a struct to its first member? | X is defined as the following:
struct X
{
Y y;
// more fields...
int a;
};
I have a variable of type X. However, I would like to cast it to the type of its first member, in order to pass that into a function. I know that the C Standard permits it (and I suppose the C++ one does so as well).
In C I would do... | I'd always recommend using static_cast instead of reinterpret_cast in any situation where the static_cast isn't rejected by the compiler. If possible try to avoid doing any casting at all - in this case you probably want: Y* y = &x.y.
To answer the comment:
In this case, I have a PROCESS_MEMORY_COUNTERS_EX
variable. H... |
65,189,451 | 65,189,615 | Why is the code that works correctly in Main works incorrectly inside the function ? (C++) | I'm trying to find the length of an array with the code below, but when I'm trying to run it inside of a function, it doesn't work right.
int nums1 []={1,2,3,4,5,6,7,8,9,10};
const int len1=sizeof(nums1)/sizeof(nums1[0]);
When I'm passing nums1 to the function and then trying to find the length of nums1, same code doe... | To rewrite the two examples
const int len1 = sizeof(int[10]) / sizeof(int)
and
const int len2 = sizeof(int*) / sizeof(int);
The first one takes the size of an int array, whereas the second one takes the size of an int pointer. In your architecture, an int is 4 bytes long, and an array of 10 ints is therefore 40 bytes... |
65,190,015 | 65,190,100 | C++ type loophole explanation | The silly question. Could anyone please explain to me how this code works? (from here https://alexpolt.github.io/type-loophole.html)
#include <string>
#include <type_traits>
template<int N> struct tag{};
template<typename T, int N>
struct loophole_t {
friend auto loophole(tag<N>) { return T{}; };
};
auto loophole(... | It causes instantiation of the template specialisation loophole_t<std::string, 0>.
As a class template with a friend function (and remember, friends aren't members), that also brings the function into scope in the global namespace.
That function could be spelt std::string loophole(tag<0> unusedParam);.
It's not directl... |
65,190,240 | 65,190,371 | open a file in a function and use it in main | I have a school project. The project requires me to write a function called openFiles. So I need to open a file inside the function and use it in main or other functions. How can I do that? Assumed my file is named "1"
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
void openFiles(string);
ma... | Because fstream has a move constructor, you can return your fstream object as the result of openFiles, like so:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
fstream openFiles(string);
int main() {
auto file = openFiles("1");
string str;
while(file>>str)cout<<str;
}
fstre... |
65,190,573 | 65,192,246 | CMake finds target and component but can't link against them | Context
I am trying to build and run this project: https://github.com/tay10r/libpx
I am running CMake 3.19.1 on MacOS 11 and the only thing I've changed from the project source that you can clone is the target OS for editor/BuildDesktop.cmake: I changed WIN32 to MACOSX_BUNDLE. In any event the issue below exists regard... | According to the documentation, find_package(OpenGL) defines the target OpenGL::OpenGL only if your system is GLVND-based. But GLVND is the Linux-specific vendor-neutral dispatch library, so there's no way it would be present on your macOS system. So:
find_package(OpenGL REQUIRED COMPONENTS OpenGL) will consider the "... |
65,190,606 | 65,191,240 | Iterate through variables as Base class objects while casting to Child classes and use their overriden methods in C++ | I am trying to do something that I feel should be more straightforward or maybe my Java knowledge is interfering, but I can't figure it out.
All I want to do is make a vector<A> as {aa, bb, cc} where bb and cc are child instances of the base class, A. Each Child class uses the same function name but has a different imp... | You are suffering from object slicing. Polymorphism only works when using pointers/references to objects, which you are not.
Also, this code:
if (typeid(B) == typeid(child)) {
...
B* child_b_p = static_cast<B*>(&child);
...
}
Should be written to use dynamic_cast instead of typeid().
Try this instead:
#inc... |
65,190,770 | 65,190,895 | C++ Segmentation Fault at Union Member Assignment | The following code produces a segmentation fault upon assignment to a union member. This must be a result of misunderstanding unions, but I cannot pinpoint my error.
Q1: Is it necessary to include some initialization for the appropriate union member variables in T1's constructor?
I have tried something similar to the ... | https://eel.is/c++draft/class.union#general-6
says that you can change the active member of a union via u.x = ... only if that assignment is a trivial assignment operator. std::string assignment operator is not trivial, and therefore the note applies
https://eel.is/c++draft/class.union#general-7
In cases where the ab... |
65,190,824 | 65,199,034 | C++ Template specializations for primary, templated, specialised and aliased template arguments | I'm trying to specialize a template to work with both primary types, templated types and specialised/aliased templated types. See the code example below.
It compiles but does not link.
How can I write a template specialization for zero() that I can call as zero<myvec>() and still be able to also call zero<double>, etc.... | Thanks again for the two excellent answers. I really like the variadic template solution ;-).
Turns out there is a simpler, albeit admittedly less generic, solution to the problem stated without replacing functions with structs. Just add a definition to the generic declaration of zero(), i.e. change
template <typename ... |
65,190,903 | 65,191,060 | Adding an object to a vector in the middle of an iteration error | Alright so, I'm in the middle of a loop that iterates all objects in a vector:
for (auto &itr : m_entities) {
itr.second->Update(l_time);
if (itr.second->m_isDead)
Remove(itr.first); //don't worry, it does not remove immediately so the vector size wont change
}
m_entities is a vector that process... | In a range-based for loop, you can't do anything that modifies the size of the container. In this case, since you are only adding elements, simply use a traditional index-based for loop instead, eg:
for (size_t i = 0; i < m_entities.size(); ++i)
{
auto &itr = m_entities[i];
itr.second->Update(l_time); // may i... |
65,191,028 | 65,191,300 | How to convert from bitset back to int | So I currently working on file compression so to compress the file I am converting my string of ints using huffman encoding
example:
1000011011010100011010100010001101111001001111010011000011011100001010010110011011
1001110011111000010110110101111111
to bit set like this :
int i = 0;
while (i < str.length())
{
bi... | If I correctly understand your question here is what you can do to perform a reversed operation:
constexpr int bits_num = sizeof(unsigned char) * CHAR_BIT; //somewhere upper in the file
//...
std::string outputStr;
unsigned char c;
while (inputFile.get(c)) //the simplest function to read "character by character"
{
... |
65,192,348 | 65,192,444 | How to initialize a array out of line? | How to initialize an array, out of the length definition line?
int a[5]; //this line fixed, only state the array name and size
a = {1,2,3,4,5}; //error: Array type 'int [5]' is not assignable
a[] = {1,2,3,4,5};//error: expected expression
What's the correct way (use one line) to fill {1,2,3,4,5} into a[5] out of the ... | 'Old-style' arrays in C++ cannot be assigned data en bloc, but they can be initialized when first declared, as you have pointed out.
However, the std::array container provided by the STL does allow its data block to be reassigned (with some caveats):
#include <iostream>
#include <array>
int main()
{
std::array<int... |
65,192,514 | 65,192,661 | What is the purpose of the `iterator-sentinel-pair` concept in [ranges.subrange]? | What's the purpose of the exposition-only iterator-sentinel-pair concept as defined in [range.subrange]?
template<class T>
concept iterator-sentinel-pair = // exposition only
!range<T> && pair-like<T> &&
sentinel_for<tuple_element_t<1, T>, tuple_element_t<0, T>>;
The only time it's used, as far as I can see, is... |
What's the purpose of the exposition-only iterator-sentinel-pair concept as defined in [range.subrange]?
No purpose anymore, they're removed as of LWG 3404 adopted at the previous plenary, and will shortly be removed from the draft. They're just vestigial oversight after the all the stuff that used them was removed i... |
65,192,594 | 65,192,899 | Is there an algorithm for copying neighboring pixel values stored in a 2D-Array? | I have a 2D array of greyscale pixel values that looks like
255 250 250 250 235 251 255 201
255 250 250 250 235 251 255 151
255 250 250 250 235 251 255 151
255 250 250 250 235 251 255 151
255 250 250 250 235 251 255 151
In implementations I have seen online and in other posts, the program will obtain neighboring pixel... | I wasn't planning on answering this, but I may as well now that I've written extensively in comments.
General advice is to simplify your loop by treating row and col as the top-left corner of your window instead of the center. This makes the math straight-forward (and therefore clearer to anyone reading the code), esp... |
65,192,993 | 65,193,019 | Why is vector of pointers not saved as a class member after using the constructor? | I wrote a weird example where I instantiate an object, give it a bunch of like objects and I try to call a function on the main object using the like objects.
I want to save a vector of pointers as a class member as in
#include <iostream>
#include <vector>
class A {
public:
virtual ~A() = default;
};
class B: ... | bees = bees;
This does nothing. It assigns bees to itself. It's likely to get optimized to nothing.
this->bees = bees;
This will explicitly assign the local variable to the instance field, which is what you're looking to do.
B(std::vector<B*> bees) : bees(bees) {}
However, this is the best practice, as it uses the c... |
65,193,350 | 65,193,534 | initialize std::array <struct, size> | I am trying to defined and initialize an array of struct.
#include <iostream>
#include <array>
int main() {
struct row{
double a0;
double a1;
};
//method 0: this way works
row c[2] ={{1.0,2.0},{3.0,4.0}};
//method 1: declare and initialization in same line
//std::array<row, 2... | The literals (without the doubled braces) you are trying to use to initialize/assign your std::array variables do not match the type of those arrays. You need to explicitly make each of the 'top-level' elements a row object, like this, for example:
int main()
{
struct row {
double a0;
double a1;
... |
65,193,521 | 65,197,480 | Does a call stack grow first in / first out in C++? |
Each time we call the function, the stack of activation records (usually just called the stack) grows with one record. Conversely, when the function returns, its record is no longer used and so on. The stack (also called the call stack) is a data structure that grows and shrinks at one end according to the rule first ... | Let me show you how a call stack works: imagine you have a program, which contains some functions and subfunctions, like f1(), f1.1(), f1.2(), f1.1.1(), f1.2.1() and f1.2.2(), and you have following pieces of code:
int f1(){
if (<condition>){ // B1
return f1.1();
} else {
return f1.2();
}
}
int f1.1(){... |
65,193,522 | 65,193,557 | Negative Subscript of an array in c++ | Lets say we have an int array "arr" of size 5 then &arr points to whole array of 5 int.
But when I do like &arr[-1] I don't get any error, Can somebody explain what does this means.
int arr[5] = {1, 2, 3, 4, 5};
std::cout << &arr << std::endl; // 0x61fea0
std::cout << &arr[-1] << std::endl; // 0x61fe9c (0x4 less than p... | This is because of the relationship that arrays and pointers share. A negative index might still point at an address within the bounds and won't result in an error
|
65,193,927 | 65,194,017 | Position of nearest and farthest set bit, Count of set bits of an integer | Problem: How to find the position of the nearest and farthest set bit and count of set bits of an integer?
E.g:
n - integer
Input: n = 10
Output: 1, 3, 2 (nearest, farthest, count) respectively
I tried this python script, are there any more efficient(time and space) ways to solve?
n = int(input())
near = far = count ... | The number of bits set is fastest found using a built-in function or inline assembler if your CPU supports it: e.g. __builting_popcount() (GCC for x86 population count instruction).
Whether - in your question - you intended "set" to apply to MSB or LSB is unclear. Trivially, bits are usually numbered from 0 as the LSB... |
65,193,941 | 65,195,872 | close mainwindows from QDialog | I've created two windows (a main window and a QDialog).
The dialog is created in the constructor of the main window. The problem is that the QDialog can be closed just by clicking the closing button so I'd like to do such that the main window closes too if I close the QDialog.
accueil::accueil(QWidget *parent) : QMainW... | you can show the dialog as modal, then connect to the close event to a slot/lambda and in that close the main window :)
|
65,194,182 | 65,194,381 | Is copy initialization identical to copy initialization of a copy? | The following two code segments presents the task of initializing variable b as a copy of a. The first code segment initializes the variable using copy initialization (initialization using =). Assume class Apple is simply defined as an empty class: class Apple {};
Apple a;
Apple b = a;
The second code segment initia... | Yes, in concept, for Apple b = Apple(a);, a temporary Apple is constructed from a firstly, then b is copy-initialized from the temporary. Because of copy elision, as the effect b is initialized from a directly.
Under the following circumstances, the compilers are required to omit the copy and move construction of clas... |
65,194,234 | 65,194,481 | class public function refer to private array | I was trying to build a class, which has a public function, that can access the private array members according to index.
#include <iostream>
#include <array>
class foo{
public:
int get_value_from_table(int row_number){
return table[row_number];
}
private:
constexpr static std::array<int, 2> table... | The posted code should work as-is with C++17 and later.
Before C++17 static constexpr members also required a definition outside the class declaration.
constexpr std::array<int, 2> foo::table; // still allowed but no longer required in C++17
Related insight and pointers can be found under constexpr static member befor... |
65,194,363 | 65,194,916 | error: C2661: 'std::array<uint,3>::array': no overloaded function takes 3 arguments | I'm receiving this error:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\include\xmemory0:881: error: C2661: 'std::array<uint,3>::array': no overloaded function takes 3 arguments
At this line of code:
template<class _Objty,
class... _Types>
static void cons... | As @kakkoko already pointed out:
indices.emplace_back(0, last, offs) calls constructor array<uint, 3>::array(0, last, offs) but array doesn't have such constructor;
Unfortunately, an additional pair of curly braces is not sufficient:
indices.emplace_back({ 0u, last, offs }); // Doesn't work! :-(
Output:
main.cpp: ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.