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 |
|---|---|---|---|---|
71,092,308 | 71,092,336 | c++ test if random number is positive or negative | I have school work with C++ and Im new to it. I have to generate 17 random numbers and then test if they are positive/negative/equal to zero. I can't seem to find a way to take the random generated number from the for loop to test it in the if/else if loop. Heeeeelp please :D (The b variable is just there from tests)
#... | Easy enough, first assign the value to b, so you can then compare it. The current cout just outputs it.
b = rand()% 20 - 10;
cout << "Skaitlis: " << b << "\n";
|
71,092,448 | 71,092,605 | How can I fix my OpenCV4 installation on Ubuntu | I need some help. I want to install Opencv4 on my computer (which runs on Ubuntu) and use it with VSCode.
A lot of tutorial explains how to do it, so here is one of thoses I followed: https://vitux.com/opencv_ubuntu/
I, next, took a program my teacher sent me to check installation:
#include <iostream>
#include <string>... |
I am interpreting this as: the inclusion made by the modules are not reading at the good place. My program actually recognize the location of highgui.hpp, but that module does not recognize the good location for core.hpp
nice & correct analysis, for a noob !!
your teacher's test program is already incorrect
#include ... |
71,092,531 | 71,094,275 | Cartesian product of list of templates and list of types to instantiate them with | Not sure if title is descriptive, but what I would like is this:
input:
list of templates(in my case containers) taking 1 (required, can be more optional) type arguments
list of types
output:
"cartesian product" where each template in first set is instantiated with every type in second set.
example:
template_list<std... | As in my answer on he linked question, with Boost.Mp11, this is a short one-liner (as always):
using templates = mp_list<mp_quote<std::vector>, mp_quote<std::set>>;
using types = mp_list<int, double>;
using result = mp_product<
mp_invoke_q,
templates, types>;
static_assert(std::same_as<
result,
mp_lis... |
71,093,821 | 71,093,969 | c++ Extract parameter type list from function pointer | Im trying to get the argument types from a function pointer
This should be the working end product
std::function<void(TestAppObject*, MemberFuncArgs<decltype(&TestAppObject::TestMethod)>::InputArgs)> func = &TestAppObject::TestMethod;
Current MemberFuncArgs class
template<typename T>
struct MemberFuncArgs;
template<t... | The compiler say the you can't define a single type InputArgs
typedef Args InputArgs;
given that Args is a variadic list.
Maybe you can define a type base on a tuple
using InArgsTuple = std::tuple<Args...>;
so you can extract the single types in Args... using std::tuple_element
So, with a little template meta-program... |
71,094,102 | 71,094,262 | Issue dispatching an overloaded operator to base in C++ | Please forgive me if I fundamentally misunderstand something about dispatch in C++!
The code as pasted below works as intended.
However, if I uncomment/add the additional operator<< method in Derived (which should handle a different agrument type), C++ is then unable to resolve the previously-working dispatch "*this <<... | The names in the parent class are hidden while building a lookup set for the unqualified name lookup. You may bring the parent's operator to a child lookup set by using directive. I can't find the duplicated question, but I'm pretty sure the duplicated question exists.
class Derived : public Base {
public:
void met... |
71,094,868 | 71,094,945 | How can you redefine a POD type such that it is considered a distinct type while maintaining the semantics? | Imagine the following scenario where we have a pod container type that applies to many different scenarios:
struct vec2 {
float x, y;
};
Some of these scenarios might be storing a velocity, a position, an acceleration, etc. Now suppose we want to be able to handle all these scenarios independently while putting the ... | Something along these lines, perhaps.
template <typename Tag>
struct vec2 {
float x, y;
};
using position = vec2<struct PositionTag>;
using velocity = vec2<struct VelocityTag>;
position and velocity would have similar behavior, but are distinct types.
|
71,095,274 | 71,096,721 | Overload resolution between two constructors from std::initializer_list | In following program, struct C has two constructors : one from std::initializer_list<A> and the other from std::initializer_list<B>. Then an object of the struct is created with C{{1}}:
#include <initializer_list>
struct A {
int i;
};
struct B {
constexpr explicit B(int) {}
};
struct C {
int v;
const... | The wording could be clearer (which is unsurprising), but GCC and MSVC are correct here: the relevant rule ([over.ics.list]/7) checks only that
overload resolution […] chooses a single best constructor […] to perform the initialization of an object of type X from the argument initializer list
so the fact that the ini... |
71,095,280 | 71,132,352 | OpenGL texture gets worse when moving camera away from object | The texture gets generally worse more I move the camera away from the object. I need to be really close to the object for the texture to be fine. Does anyone know what would cause it and how to fix it?
this is how I load the texture
stbi_set_flip_vertically_on_load(1);
m_Local_buffer = stbi_load(path.c_str(), &m_width,... | Problem was that the faces in the model were too close to each other which caused Z-fighting and that caused flickering. It was not caused by texture or my or by OpenGL code like I originally assumed. When I changed the model that had not this issue it worked correctly without any fliggering.
|
71,095,487 | 71,095,622 | How do I do a forward declaration of a struct with a typename? | I am trying to do a forward declaration of a struct in c++ that has a typename. Something like this is entirely valid:
typedef struct foo foo;
struct foo{
int f;
};
My struct just instead has a typename, so I tried this:
template <typename T>
typedef struct mV<T> mV;
template <typename T>
struct mV{
//content... | You're describing a forward- declaration . (A future is something completely different in modern C++).
typedef aliasing structure tags is not needed, and rarely desired, in C++. Instead you simply declare the class type and be done with it.
// typedef struct mV mV; // not this
struct mV; // instead this... |
71,095,680 | 71,095,708 | C++ Overloading macro on undefined number of arguments | My command uses return codes and a string reference argument instead of exceptions to detect an error in the execution of a function.
We have some invariant checking that looks like this:
bool format(std::string &error, ...)
{
// call sprintf on "error" string with all passed arguments
return false;
}
bool fun... | C++20 made it possible to call #define F(x, y, ...) as F(1, 2), without the comma after the last argument.
If C++20 is available, the only change you need to do is to replace , __VA_ARGS__ with __VA_OPT__(,) __VA_ARGS__ to the remove the comma if no extra arguments are passed.
Otherwise, just combine format and ... par... |
71,095,751 | 71,204,808 | static lib not working in codeblocks project | I have build my own version of assimp as a static lib from scrach, since the makelist files provided with the lib are complete useles. It took me about a week, but at the end I was able to build the lib without error and assimp.a was created. The next step was to use this lib in my own project. I selected a console C++... | To be honest, I have no idea about the exact reason, but the problem was because I put the assimp folder and assimp.a file to my project folder. Puting assimp folder and assimp.a file to some other folder outside my project folder solved the problem. Years ago I had a similar problem with some dynamic lib and solution ... |
71,095,893 | 71,098,607 | Can an OpenAL source ever be 0? | Can an OpenAL source generated by alGenSources() ever be 0?
Because I would like to store NULL as source whenever the source has stopped playing.
It is stored as an ALuint.
I couldn't find it in the Programmers guide.
| Unfortunately, you cannot rely on 0 being reserved as invalid, as it is allowed id by specs (up to implementation to decide).
According to OpenAL 1.1 specs:
2.12. Requesting Object Names
OpenAL provides calls to obtain object names.
The application requests a number of objects of a given category using alGen{Object}s.... |
71,095,951 | 71,152,852 | How expressions designating temporary objects are xvalue expression? | From cppreference, I am trying to understand expressions that yield xvalues, and I ended up with this summary:
The following expressions are xvalue expressions:
...
any expression that designates a temporary object, after temporary
materialization.
Temporary materialization is:
A prvalue of any complete type T can... |
situation 3, 4 and 7.
7 (discarded expression) is the easiest:
42; // materialize and discard
std::string{"abc"}; // materialize and discard
3 (doing things to array rvalue) requires knowing how to make them
using arr_t = int[2][3];
int a = arr_t{}[0][0]; // have to materialize to be able to subscript
4 (making an ... |
71,096,066 | 71,096,217 | C++ Same include line in 2 files in the same folder: one works, another can't find the file | Windows 10
Eclipse IDE for C/C++ Developers
Version: Kepler Service Release 2
Build id: 20140224-0627
I'm trying to use imgui. Unfortunately, documentation is pretty shady about how to get it working.
So, in order to get it working, I think I need something called "glad". Whatever it is, the only source of it seems to ... | Eclipse separates the include paths for C and C++ files. If you have a program combining both C and C++ files, the correct include paths need to be set for both languages.
Navigate to the C/C++ General -> Paths and Symbols -> Includes tab. You will see both languages (and probably Assembly) listed under Languages. Pick... |
71,096,156 | 71,096,350 | Integer to pointer cast pessimism optimization opportunities | The from_base function returns the memory address from the base to a selected
value in a program. I want to retrieve this value and return it in a function, however, I am getting a warning that says integer to pointer cast pessimism optimization opportunities.
DWORD chat::client() {
return *reinterpret_cast<DWORD*>... | If a program performs a computation like:
char x[10],y[10];
int test(ptrdiff_t i)
{
int *p = x+i;
*p = 1;
y[1] = 2;
return *p;
}
a compiler would be reasonably entitled to assume that because p was formed via pointer arithmetic using x, it could not possible equal y+1, and thus the function would always return... |
71,096,299 | 71,096,646 | Definition of struct template value in constructor / member function | I'm working with a Pascal library that uses UCSD Strings. I created this template struct for making working with them easier:
template <std::size_t N>
struct DString {
unsigned Reference, Size = N;
char String[N];
};
#define MAKE_STRING(X) DString<sizeof(X)>{ 0x0FFFFFFFF, sizeof(X) - 1, X}
auto foo = MAKE_STRI... | If you can use at least C++17... using a delegate constructor and CTAD...
You can add in DString an additional template constructor (maybe private), otherwise you can't initialize, directly, a char[] with a char const *
template <std::size_t ... Is>
DString (std::index_sequence<Is...>, char const * s, unsigned r)
: R... |
71,096,432 | 71,096,498 | C++ Vector of Object searching for which object contains a specific last name error C2678 binary '==': no operator found | C++ is not really in my skills, so I have vector of objects which is obviously several copies of a class.
My class is named "Contact", and my function I am property passing in my vector objects as reference.
As soon as I try to add in this find, I guess an error
void Contact::searchContactByLastName(string name, vector... | Since you probably don't want to implement the == operator to match Contract and std::string, it's a good idea to std::find_if allowing you to pass the matching functionality as parameter.
if (std::find_if(allContacts.begin(), allContacts.end(), [&name](Contract const& contract) {return name == contract.getLastName();}... |
71,096,602 | 71,096,760 | Splitting QString on spaces and keeping the space in QList - best or 'canonical' way | As in the title, I would like to ask what is the best way to split a QString on spaces and - where relevant - keep the spaces as parts of the resulting QList elements. I'm interested in the most efficient method of doing this, considering modern C++ and Qt >= 6.0 paradigms.
For the purpose of this question I will repla... | Consider myString.split(QRegularExpression("(?<= )") The regular expression says "an empty substring preceded by a space", using the positive look-behind syntax.
|
71,096,924 | 71,096,989 | Initialize an array in a struct | Is there already a way where I can initialize an array directly in a struct? Like this:
struct S
{
int arr[50] = {5};
}
I know this only initializes the first element of the array, but is there any way to write something similar with g++ but that can initialize all elements of the array with 5?
I've read that with... | Since a struct object needs to have its constructor called when being initialized you can just perform this assignment inside the constructor, e.g.:
struct S
{
int arr[50];
S() {
for (int& val : arr) val = 5;
}
};
Or similarly you can use std::fill from the algorithm header
#include <algorithm>
struct S
{
... |
71,097,047 | 71,109,385 | LibTorch sizeof tensor | I would like to know how I can get the size in bytes of the data type of a torch::Tensor.
I saw somewhere online that sizeof(tensor.dtype()) should work, but for my float32 tensor it prints out 1.
| I found it myself finally.
torch::elementSize() returns the size of the given ScalarType.
To convert from tensor.dtype(), which has type caffe2::MetaType, to a Scalar, I had to use this converter torch::typeMetaToScalarType(tensor.dtype())
Therefore, the size of a tensor in memory can be calculated like this:
tensor.nu... |
71,097,211 | 71,097,285 | Best way to create virtual registers in C++ | I'm trying to create a barebones VM that can only execute x86 assembly code for a highschool project, and I figured to create all of the registers using structs. I have all of the instructions, opcodes, and operand logic implemented already, but I'm worried that this kind of botching of creating CPU registers won't be ... | I wrote a PDP11 emulator in c++ recently I did this
uint16_t registers[8];
uint16_t &PC = registers[0];
uint16_t &R1 = registers[1];
.....
ie create an array of registers so I can save them as a block or whatever but create references with the well known names for each register
|
71,097,511 | 71,097,534 | Pass a variable number of arguments into a function | I know how to use variadic templates and ellipses to accept a variable number of arguments, but how do you pass a variable number of arguments into a function?
Take the following code for example:
#include <iostream>
struct A {
A(int a, int b) : x(a), y(b) {}
int x, y;
};
struct B {
B(int a, int b, int c) :... | You can expand the array using a std::index_sequence
#include <iostream>
#include <utility>
struct A {
A(int a, int b) : x(a), y(b) {}
int x, y;
};
struct B {
B(int a, int b, int c) : x(a), y(b), z(c) {}
int x, y, z;
};
template<typename T, typename... TArgs>
T* createElement(TArgs&&... MArgs) {
T*... |
71,097,760 | 71,097,805 | How to resolve circular dependence in the following case? | #include <iostream>
#include <set>
struct ContainerOfA;
struct StructA
{
StructA(ContainerOfA* ptr) : m_b_ptr(ptr)
{}
void CleanMe()
{
m_b_ptr->RemoveStructA(this);
delete this;
}
ContainerOfA* m_b_ptr;
};
struct ContainerOfA
{
void RemoveStructA(StructA *a_ptr)
{
m_set_a.erase(a_ptr);
... | Just move the problematic code to a point where the class is defined.
struct StructA
{
// ...
void CleanMe();
// ...
};
struct ContainerOfA
{
// ...
};
inline StructA::CleanMe()
{
m_b_ptr->RemoveA(this);
}
By the way, that's a real code smell having an object know what container it's part of. You should ... |
71,097,765 | 71,102,418 | Boost Serialization, need help understanding | I've attached the boost sample serialization code below. I see that they create an output archive and then write the class to the output archive. Then later, they create an input archive and read from the input archive into a new class instance. My question is, how does the input archive know which output archive its r... | Like others said, you can set up a stream from existing content. That can be from memory (say istringstream) or from a file (say ifstream).
All that matters is what content you stream from. Here's you first example modified to save 10 different streams, which can be read back in any order, or not at all:
Live On Coliru... |
71,097,831 | 71,098,027 | Issues converting Hex to Short getting the wrong value | I have a function that converts 2 char values into an unsigned short:
unsigned short ToShort(char v1, char v2) {
unsigned short s = ((v1 << 8) | v2);
return s;
}
It works most of the time, but occasionally I get a number that is not correct. As we can see, some of the numbers in my output file are around 65000... | char gets a sign extension when OR'ed. Instead of v2 you could do:
(v2 & 0xFF)
unsigned char would be feasible, too.
|
71,097,924 | 71,097,963 | Compiler error - is private within this context - Line 31 | #include<iostream>
#include<string>
using namespace std;
class Item{
private:
string type;
string abbrv;
string uID;
int aircraft;
double weight;
string destination;
public:
void print(){
cout << "ULD: " << type << endl;
cout << "Abbreviat... | #include<iostream>
#include<string>
using namespace std;
class Item{
private:
string type;
string abbrv;
string uID;
int aircraft;
double weight;
string destination;
public:
Item(string t, string a, string u, int aC, double w, string d){
type... |
71,098,373 | 71,099,144 | Regex for capturing a block of variable assignments | I have tokens that I need to parse and would like to have a regex that captures them. Here is how the tokens look
EVAL
INPUT A = 5;
INPUT B = 6;
...
INPUT LongVariableName = 10;
I want to validate that every EVAL block is formatted correctly for parsing. A naive approach I have is to take these tokens and build a s... | For validation you can match the string to the following regular expression to determine which blocks are formatted correctly:
^EVAL *\r?\n(?:INPUT +[a-z][a-z\d]* += +\d+; *\r?\n)+
Demo
For formatting replacing matches of the following regular expression with a space will get you close:
\r?\n(?!EVAL\b)
Demo
If the st... |
71,098,653 | 71,098,754 | The variable declared in for-loop of c++ is not initialised | #include <iostream>
#include <Windows.h>
void selection_sort(int*,int);
void output_array(int*, int);
int main() {
using namespace std;
int numbers[] = { 4, 6, 8, 2, 7, 5, 0,1, 3, 9 };
int length = 10;
selection_sort(numbers, length);
output_array(numbers, length);
Sleep(10000);
return 0... | void selection_sort(int* start, int length) {
for (int i = 0; i < length; i++) {
int max = *start;
int max_i = 0;
for (int j = 1; j < (length - i); j++) {
//find out the maximum
if (max < *(start + j)) {
max = *(start + j);
max_i = j;
... |
71,099,358 | 71,099,478 | move assignment from newly constructed object to *this in a member function | Implementing a reset() method, which uses some of the members from this to construct a new object and then move-assign that object to *this.
Questions:
Does this cause any problems? UB or otherwise? (seems fine to me?)
Is there a more idiomatic way?
Destructor and move-assignment operator only implemented to prove wh... |
Does this cause any problems? UB or otherwise? (seems fine to me?)
As long as the move assignment and the constructor are implemented in such a way that it does what you want, then I don't see a problem.
Is there a more idiomatic way?
I would invert the direction of re-use.
explicit Thing(std::size_t size_) : s... |
71,099,803 | 71,100,697 | can ranges split be used with a predicate? | Can this double loop be rewritten using ranges views split() ?
#include <vector>
#include <span>
struct MyPair
{
int a;
char b;
};
vector<MyPair> path = {{1,'a'},{1,'z'},{2,'b'},{2,'y'}};
vector<span<MyPair> > spans;
for (int i=0; i < path.size();)
{
auto r = path | ranges::views::drop(i) | views::take_... |
Can this double loop be rewritten using ranges views split() ?
Since you're not using a range as a delimiter to split the original range, instead you're using a predicate to split the range, views::split doesn't actually solve the problem.
However, C++23 adopted views::chunk_by, and according to its description in [... |
71,099,900 | 71,102,215 | How to use vertex dentifiers in Boost graph of size int64_t | I am trying to add edges to a Boost undirected graph using boost::add_edge(...). The graph is defined as:
using osm_id_t = int64_t;
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS,
// vertex properties
boost::property<boost::vertex_index_t, osm_id_t,
boost::property<bo... | Using vecS the vertex index is implicit. They correspond to the index in the vertex storage container, which is vector.
This means that using vertex index 1810014749 on g would be Undefined Behaviour if you have fewer than 1810014750 vertices. "Luckily" (?) for you add_edge is smart enough to detect this and resize the... |
71,100,119 | 71,100,269 | Should constructor call init or vice versa? | In a case where I want to allow initializing a class directly in the construction, as well as allowing an empty instance (either default-constructed or that has had some kind of close() method called on it) to be initialized, is there any reason to prefer either of these two options for avoiding code duplication?
init/... | I would argue neither. Except in rare instances where you want a two step construction process, I'd argue against having an "init" method at all.
Your first option "init calls constructor" actually uses an assignment or move operator for the initializing process. But it hides the fact that is does so. Why?
Wouldn't thi... |
71,100,425 | 71,100,731 | C++ Esp32 functional infinite loop | So I've such of a code:
void B();
void C();
void A() {
Serial.println("Looping");
B();
}
void B() {
C();
}
void C() {
A();
}
void setup() {
Serial.begin(115200);
A();
}
void loop() {
};
and it works just fine, but when I want to add a condition, like this:
bool flag = false;
void B();
void C();... | Calling functions like that will cause an infinite recursion, exhaust the stack and make the whole thing crash.
You could call all the functions from inside loop() and other functions just return which function should be called next.
char A() {
Serial.println("Looping");
if(flag)
return 'B';
else
return '... |
71,100,494 | 71,106,802 | list changed function names or signatures with git diff (c++) | I'm working on a git diff parser. The main task is to find all changed function signatures. Sometimes in the chunk line with @@@ .... @@@ contains these information but sometimes not.
Last time I changed in greet() cout message and it is visible on first image as changed line and it is correct, but above in @@@... line... |
Sometimes in the chunk line with @@@ .... @@@
Git calls this a hunk header (after other diff software that also calls it that).
... contains [the function name] but sometimes not.
What Git puts in the function section of a diff hunk header is produced by matching earlier lines against a particular regular expressio... |
71,100,549 | 71,334,432 | GPU Heightmap sculpting in shader | i have successfully done the sculpting implementation on CPU,
throw some guide on how to do this on GPU kindly …
i have moved the sculpting code to vertex shader but the sculpting is not accumulating in vertex shader and cant modify position in vertex shader… kindly tell me how …
if (SculptMode.x == 1)//Raise
{
fl... | changed implementation to completely different method, this wont work as i think this quantization is happening because there are vertex which are shared among triangles and sculpting adjustment is applied multiple times to same vertex, that is why spikes…
|
71,100,772 | 71,100,956 | How to require child class method to call parent class method? | Let's say I have a parent class A.
class A
{
public:
A() {}
void MyMethod()
{
printf( "A\n" );
}
};
And I have a child class B.
class B : public A
{
public:
B() {}
void MyMethod()
{
printf( "B\n" );
}
};
Now, I would lik... | Non-Virtual Interface idiom has the base class define a public
non-virtual member function, and a private virtual member function that
is an override point for derived classes.
The public non-virtual member function acts as a public facing API.
The private virtual member function acts as a class hierarchy
facing API.
S... |
71,100,809 | 71,219,765 | Source engine - Acceleration formula | I was going through the player movement code for the source engine when I stumbled upon the following function:
void CGameMovement::Accelerate( Vector& wishdir, float wishspeed, float accel )
{
int i;
float addspeed, accelspeed, currentspeed;
// This gets overridden because some games (CSPo... | My Interpretation
I think author make wishspeed simply act as scaler for accel, so the speed of currentspeed reach the wishspeed linear correlated to magnitude of the wishspeed, thus make sure the time required for currentspeed reach the wishspeed is approximately the same for different wishspeed if other parameters st... |
71,100,867 | 71,101,093 | Is it better to add two numbers to a new variable or adding them together while displaying? | Which is better:
int sum = a + b;
std::cout << sum;
std::cout << a + b;
In terms of performance and efficiency?
|
Is it better two add two numbers to a new variable
No, it's not better in general.
or adding them together while displaying?
No, it's not better in general.
Either is usually fine. The intermediate local variable has advantages such as ability to give an understandable name, and it reduces the complexity of individ... |
71,100,874 | 71,101,153 | How to install external library from source for cmake to find it? | Say I am writing a library my_project that uses some other library dependency_lib.
What I'm currently doing during development is: I've cloned the code of the dependency to some normal, human accessible directory in my file system. I've built that library according to the instructions from its developers, and now I hav... | Mostly, developers add SDKs folder to let others use the required SDKs. It may be because they did minor/major changes inside the library and it became a custom build version and special for them. So, it means, they have to pack it inside the project since others can't find the modified version of that library. And I ... |
71,101,365 | 71,101,492 | How to achieve the following? C++ "advanced" map/list/array? | I am trying to create some sort of list, map or what ever may be suggested that does the following
something [] = {
mainvalue1 = 2001 {
value2 = 1905
value3 = 2000
result = 500
value2 = 1910
value3 = 2030
result = 700
}
... | I find your structure utterly confusing, but it's possible to make the lookup nearly like you want it:
#include <iostream>
#include <map>
#include <vector>
int main() {
std::map<int, std::map<std::vector<int>, int>> something{
{2001, {
{{1905, 2000}, 500},
{{1910, 2030}, 700}
... |
71,101,451 | 71,101,565 | Placement New Operator | #include<iostream>
using namespace std;
int main() {
int buf[2];
int *p=new (buf) int(2);
int *q=new (buf+1) int(6);
for(int i=0;i<2;i++)
cout<<buf[i]<<" ";
return 0;
}
I was trying placement new operator with the following example. For the above code I get the output as:
trial.cpp:7:2... | This is a GCC bug affecting versions 8 to 10 and fixed in 11, see bug report.
The code is fine, the warning a false-positive.
|
71,101,585 | 71,101,646 | How to use C++20 concepts to do different things based on return type of a function? | I want to make a generic print(x) function, which behaves different for different types.
What I have so far works for all container types, including the one I wrote myself. However, either the "wrong" function is getting called or it won't compile due to ambiguity.
Here is my code:
#include <iostream>
#include <concept... | Given an integer (or lvalue to one), would you not agree that it is convertible to a char? The constraints check exactly what you have them check for the types in your question.
One way to tackle it would be by constraint subsumption. Meaning (in a very hand wavy fashion) that if your concepts are written as a conjugat... |
71,101,695 | 71,294,930 | Failing to compile project using CUDA 11.0, Python 3.8, Torch 1.8 | I am trying to compile DiffDVR, a differentiable renderer. This requires running cmake first, so I had to install some dependencies. I want to use the same dependencies as the ones in the repo. I'm on Linux Mint 20.3, which is based on Ubuntu 20.04.
In order, I have installed:
CUDA 11.0 (using the official runfile)
cu... | Update: specifying all the paths manually worked. In my case, this was:
cmake .. -DTORCH_PATH=/home/andrei/miniconda3/envs/py38torch18/lib/python3.8/site-packages/torch -DTorch_DIR=/home/andrei/miniconda3/envs/py38torch18/lib/python3.8/site-packages/torch/share/cmake/Torch -DPYTHON_LIBRARY=/home/andrei/miniconda3/envs/... |
71,101,701 | 71,101,899 | How to get an element in a map and change it | How to get an element in a map and change it? For example, if I have:
{'a', 100}, {'b', 200}, {'c', 300}, {'d', 400}, {'e', 500}
I want to get to the value of 'a' and change it from 100 to 105.
| map<char, int>::iterator it = m.find('a');
if (it != m.end() {
it->second = 105;
|
71,101,911 | 71,106,956 | Framebuffer not completing on GL_DEPTH_ATTACHMENT render to texture | I'm attempting shadow mapping in OpenGL, and have been unable to render specifically GL_DEPTH_ATTACHMENT to a frame buffer. glCheckFramebufferStatus does not return complete but only when targeting the depth attachment - it works fine for color attachment0.
glBindFramebuffer(GL_FRAMEBUFFER, ShadowMapFrameBuffer);
... | It turned out to be a twofold issue. At some point I'd made a type in glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, LightMapResolution, LightMapResolution, 0, GL_FLOAT, GL_FLOAT, NULL); The first instance of GL_FLOAT should've been GL_DEPTH_COMPONENT. This caused the incomplete framebuffer.
The second error was fo... |
71,102,284 | 71,102,578 | c++ : Why does my boolean store a value greater than 1? | I'm learning C++ and am right now starting with the concept of classes. And I learned that a new created object (without constructor) will have randomized attributes. So I wanted to test that and wrote a short code:
#include <iostream>
#include <vector>
class Person;
class Person {
public:
bool const isHungry() {
... |
And I learned that a new created object (without constructor) will have randomized attributes.
This is wrong. The uninitialized members will have indeterminate values until they are assigned to. Trying to read an indeterminate value causes the program to have undefined behavior, which means that there will be no guar... |
71,102,678 | 71,102,817 | Accessing private members of surrounding class | I have two classes like this:
#include <iostream>
class A {
public:
class B {
public:
void printX(void) const { std::cout << A::x << std::endl; }
};
private:
int x;
};
Obviously this piece of code doesn't work because B can't access x, but is there a way ... | According to the C++ 17 Standard (14.7 Nested classes)
1 A nested class is a member and as such has the same access rights as
any other member. The members of an enclosing class have no special
access to members of a nested class; the usual access rules (Clause
14) shall be obeyed.
The problem with the provided code ... |
71,102,939 | 71,104,079 | Can't create recursive type `using T = vector<T::iterator>` | I'm trying to create a vector that contains its own iterators as elements, and I find it impossible to fully expand the type declaration.
using MyVectorType = std::vector<std::vector<...>::iterator>;
// Trying to fill in the ... ^^^
Another approach that fails is:
using MyVectorType = std::vector<MyVec... | I do not think that it is possible by the standard.
To achieve what you want you must be able to refer to std::vector<T>::iterator while T is incomplete.
Before C++17 T was required to be complete to instantiate std::vector<T> at all, so it cannot work there.
Since C++17 the standard allows instantiating std::vector<T>... |
71,104,242 | 71,104,267 | std::basic_string<T>::size_type causes compile error in C++20 mode | Here is a simple code that MSVC 2022 compiles in C++17 mode, but fails in C++20 mode:
template <typename T>
void foo()
{
std::basic_string<T>::size_type bar_size; //This fails to compile in C++20
}
The error being reported in C++20 mode does not help explain the reason: error C3878: syntax error: unexpected token ... | Use
typename std::basic_string<T>::size_type bar_size;
The name size_type is a dependent name.
|
71,104,285 | 71,104,431 | problem in my int main when i am passing the values to the function | The whole program is working its just not showing name after running
#include<iostream>
#include<string.h>
using namespace std;
class employee{
private:
char profession;
int dob,sallery;
public:
int hour;
char names;
void display(int hour,char names[20]){
... | If you are trying to take string as input, better to use string data type.
Instead of
char x[20];
int y;
cout<<"enter your name here"<<endl;
cin>>x;
Try changing it to
string x;
int y;
cout<<"enter your name here"<<endl;
cin>>x;
And in your void display() function
Change from
void display(int hour,char names[20]){
... |
71,104,428 | 71,108,481 | C++ ofStream: "<<" vs "put" | Being new to C++, I am confused about what << and put() means while using ofstream to write to a text file. I tried to experiment with the two following styles as follows:
Approach 1:
void writeTester() {
std::ofstream oFile("Resources/tst.txt", std::ios::out | std::ios::trunc);
std::vector<int> v{ 1,2,3,4 };
... | Simply put, using the '<<' operator means certain overloads can be used, which means writing integer values (as in your case) will mean they're converting to their string representations before being written to the file.
Using put, however, will write a single byte to the stream. This means your 4 byte int will be trun... |
71,104,545 | 71,104,867 | Constructor and destructor in c++ when using the pimpl idiom | I come from Java that has a different way in handling what's private and has to be hided regarding a class implementation and it also has a garbage collector which means there is no need for a destructor.
I learned the basics of how to implement a class in c++ but I need to better understand how to implement a class, i... | This is an example of a correct way to implement PIMPL idiom in modern C++:
foo.hpp
#pragma once
#include <memory>
class Foo {
public:
Foo();
~Foo();
Foo(Foo const &) = delete;
Foo &operator=(Foo const &) = delete;
Foo(Foo &&) noexcept;
Foo &operator=(Foo &&) noexcept;
void bar();
private:
class i... |
71,104,721 | 71,104,800 | How can I stop cin from skippping a line? | I was trying to make a program where the user is asked to give an input and it gives output with answered questions. Everything looks alright except that cin skipped my last question about school.
This is the original code:
//this program fills my data in profile
#include <iostream>
#include <string>
using na... | It seems the problem is related to entering a boolean value.
Here is shown how to enter boolean values
#include <iostream>
#include <iomanip>
int main()
{
bool is_student;
std::cin >> is_student; // accepts 1 as true or 0 as false
std::cout << is_student << '\n';
std::cin >> std::boolalpha >> is_st... |
71,104,954 | 71,105,239 | Round trip through cv::dft() and cv::DFT_INVERSE leads to doubling magnitude of 1d samples | I'm playing with some toy code, to try to verify that I understand how discrete fourier transforms work in OpenCV. I've found a rather perplexing case, and I believe the reason is that the flags I'm calling cv::dft() with, are incorrect.
I start with a 1-dimensional array of real-valued (e.g. audio) samples. (Stored ... | The inverse DFT in opencv will not scale the result by default, so you get your input times the length of the array.
This is a common optimization, because the scaling is not always needed and the most efficient algorithms for the inverse DFT just use the forward DFT which does not produce the scaling.
You can solve th... |
71,105,685 | 71,107,053 | How to build CMake Debug version using different target name for executables? | I am building using cmake -DCMAKE_BUILD_TYPE=Debug ..
And I am using set(CMAKE_DEBUG_POSTFIX d) to add a d to the end of the filename.
This is working for static libraries and I expected it to work for executables as well. But, at least in my case, it is compiling all the static libraries using *d.a and the executable ... | You are not missing anything. As the documentation says (emphasis mine):
When a non-executable target is created its <CONFIG>_POSTFIX target property is initialized with the value of this variable if it is set.
See: https://cmake.org/cmake/help/latest/variable/CMAKE_CONFIG_POSTFIX.html
By the sounds of it, though, yo... |
71,105,841 | 71,105,996 | First login attempt works if it's correct, but if it's incorrect then other correct attempts don't work | void __fastcall TFormLogin::btnLoginClick(TObject *Sender)
{
UnicodeString query = "select * from admin where korisnickoIme = '" + editKorisnicko->Text +
"' AND lozinka = '" + editLozinka->Text + "'";
AnsiString ansiQuery = query;
ADOQuery1->ConnectionString = "Provider=SQLOLEDB.1;Inte... | This line:
ADOQuery1->SQL->Add(ansiQuery);
adds the ansiQuery to the end of the SQL collection for ADOQuery. When you click the button a second time, the new query is added to the end, but the original incorrect query is still at the start of the collection, so it is run first.
Solution: Clear out the collection on e... |
71,106,566 | 71,106,578 | Understanding const reference returned from a function | I have a function
const std::string& getRecordingJobToken() { return getToken(); }
const std::string& getToken() const { return m_Token; }
std::string m_Token;
I am able to call it as below
const std::string jobToken = getRecordingJobToken();
However when I do this,
const std::string jobToken;
jobToken = getRecordin... | Initialization and assignment are different things. jobToken is const, it could be initialized, e.g.
const std::string jobToken = getRecordingJobToken(); // copy-initialization
but can't be assigned (modified) later, e.g.
const std::string jobToken; // default-initialization
jobToken = getRecordingJobToken(); /... |
71,106,869 | 71,106,989 | how to convert string to vector<int> c++ | I would like to convert an string into a vector, so that it looks like the following:
string number = "0110";
vector < int > Vec;
with the result:
Vec[0] = 0
Vec[1] = 1
Vec[2] = 1
Vec[3] = 0
My problem is that the number starts with a 0, so using % doesn't seem to work if i first transform my string to an int
| I noticed that the question is modified to make it answerable:
#include <string>
#include <vector>
int main(){
using namespace std;
string number = "0110";
vector < int > Vec;
for(char& digit : number){
Vec.push_back(digit - '0');
}
}
|
71,107,158 | 71,107,965 | Does Explicit Object Parameter Allow Convertible Types? | From §4.2.7 of the proposal http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p0847r7.html#pathological-cases
It said that:
These are even more unlikely to be actually useful code. In this example, B is neither convertible to A nor int, so neither of these functions is even invocable using normal member syntax. ... | For your first question:
struct A { };
struct B {
operator A() const noexcept;
void foo(this A);
};
B{}.foo(); // will work?
Yes. Candidate lookup will find B::foo, which more or less evaluates as foo(B{}), which is valid due to the conversion function. This is explicitly called out in the note you cited, in [ove... |
71,107,282 | 71,108,180 | Unknown module(s) in QT: webenginewidgets |
Hi. I want to connect QtWebEngineWidgets. To do this, you need to write(https://doc.qt.io/qt-5/qtwebenginewidgets-module.html) in .cpp file
#include <QtWebEngineWidgets>
and
QT += webenginewidgets
inside .pro file.
The problem is that when writing to a .pro file, I get the error - Unknown module(s) in QT: webengin... | It turned out that it was necessary to install a newer version of Qt. For example, since version 6.2.3.0 and newer, the installer contains the "WebView" item. I'm installing it now and I'll see if it helps. Thank you.
|
71,108,064 | 71,109,571 | Implementing linked list | I am creating a linked list but after printing it I am only getting the last element in an unending loop here is the code
I guess there is some error in creating the Linked list how to solve it
Link to my code my linked List
#include<iostream>
using namespace std;
struct node{
int data; // for data component
... | You have used same reference; that's the reason your code always updates the same memory location value and finally gives last value.
#include<iostream>
using namespace std;
struct node{
int data; // for data component
node* next; // to hold addr of next
}*head_first=NULL;
void create(int* a, int n) // ... |
71,108,226 | 71,108,860 | How can I use string instead of char* buffer to read the file data into string? | I am using standard file-handler API to read the file , currently I have used a char* buffer to read the data, but I want to use string so I can avoid calloc() use. I tried to pass the string address to the ReadFile() function, but it's not working. Could you please help me???
l_FileHandle = CreateFileA(inputFilePath.c... | You can't pass in the address of the string itself, but you can pass in the address of its internal character buffer. Just make sure it has been allocated first.
l_FileHandle = CreateFileA(inputFilePath.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
l_FileSize = GetFileSize(l_FileHandl... |
71,108,289 | 71,108,761 | Why codecvt can't convert unicode outside BMP to u16string? | I am trying to understand C++ unicode and having this confused me now.
Code:
#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
using namespace std;
void trial1(){
string a = "\U00010000z";
cout << a << endl;
u16string b;
std::wstring_convert<codecvt_utf8<char16_t>, char16_t> co... | std::codecvt_utf8 does not support conversions to/from UTF-16, only UCS-2 and UTF-32. You need to use std::codecvt_utf8_utf16 instead.
|
71,108,948 | 71,109,167 | Crash when using erase–remove idiom | When i execute the code below containing erase–remove idiom , i get a crash (segmentation fault). Id like to know what is the problem.
class One
{
public:
One() {}
void print(){ std::cout << "print id: " << id << "\n"; }
void setId(int i) { id =i;}
int getID(){ return id;}
private:
int id;
};
int... | This line of code:
v.erase((std::remove(v.begin(), v.end(), v2[2]), v.end()));
is the equivalent of this:
v.erase((some_iterator, v.end()));
where some_iterator is the return value of the call to std::remove.
That now becomes the equivalent of:
v.erase(v.end());
The reason why is that the parentheses enclosed this s... |
71,109,109 | 71,109,194 | I made this to print "Hello World !", but now I want to know other ways to print "Hello World !" in C++, simplify it if can | I made this, but now I want to know other ways to do this, and simplify it.
#include <iostream>
#include <stdio.h>
int main()
{
char* a[50] = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "!"};
std::cout << a[7] <... | If you "want to do thing differently" by addressing the letter by array index, yet want to simplify the array notation, I suggest this:
#include <iostream>
#include <string>
int main(){
using namespace std;
string a="abcdefghijklmnopqrstuvwxyz!";
cout<<a[7]<<a[4]<<a[11]<<a[11]<<a[14]<<" "<<a[22]<<a[14]... |
71,109,951 | 71,110,670 | There are always line breaks after an enum declaration | I have the following BraceWrapping options:
BraceWrapping:
AfterEnum: false
AfterStruct: false
SplitEmptyFunction: false
AfterControlStatement: "Never"
AfterFunction: false
AfterNamespace: false
AfterUnion: false
AfterExternBlock: false
BeforeCatch: false
BeforeElse: false
BeforeLambdaBody: false
... | The one option I could find that seems to fix this formatting for you is outside the BraceWrapping section and that is setting
AllowShortEnumsOnASingleLine: true
even though the description of that option doesn't mention it:
true:
enum { A, B } myEnum;
false:
enum {
A,
B
} myEnum;
|
71,110,341 | 71,110,479 | Correct declaration of constructor of class in namespace | I have a class which I want to be in a namespace. I have been doing it like
namespace ns {
class A;
}
class ns::A {
...
public:
A();
};
and I define the constructor in a separate file like
ns::A::A() {
...
}
My question is about the correct way of defining the constructor. Is that the correct way, or... |
how is the constructor defined in a separate file?
You can do it as shown below:
header.h
#ifndef HEADER_H
#define HEADER_H
namespace NS
{
//class definition
class A
{
public:
//declaration for default constructor
A();
//declaration... |
71,110,672 | 71,115,178 | Pointers used as values in map corrupted after function finishes | I'm trying to store a map of VALUE to Node* but after each addEdge, the value for the added keys (Node*) changes.
One example is if I call addEdge(u, v), the map shows all the data correctly within the lifetime. If another call is made to addEdge(u, w), the keys u, v are present but the values are "corrupted"? Here's a... | Your initial addEdge was taking the address of unnamed temporary objects, which is not valid C++.
Your updated addEdge has nodes point to the leaked Nodes that you new, not the Nodes that are in the map.
You don't have to test for presence in the map, map::emplace doesn't overwrite existing items, and the return value ... |
71,110,992 | 71,111,704 | Loading QML from QString variable | Is it possible to use QQuickwidget::setSource() with variable (QString or QByteArray)?
I know that I can load a file (or resource): ui->quickWidget->setSource(QUrl::fromLocalFile(":/qml/Example.qml"));
But if I have the qml code stored in a variable, I could only solve it by first writing to a file on disk and loading ... | Maybe with the Help of a Temporary file?
https://doc.qt.io/qt-5/qtemporaryfile.html
Something like this(i dont have much time so i just did something dirty):
QQmlApplicationEngine engine;
QString qmlFile =
QString("import QtQuick 2.15\n")
.append("import QtQuick.Window 2.12\n")
.append("import Q... |
71,111,065 | 71,111,432 | Why can a floating-point literal be cast to a char in C++ in this overload resolution error? | Why does the following lead to failed overload resolution?
#include <iostream>
using namespace std;
void print( char c ) { cout << "Char\n"; }
void print( float f ) { cout << "Float\n"; }
int main(){
print( 'a' );
print( 1.23 );
}
Recall that the floating-point literal is a double by default.
Q1: When I replace 1.23 b... |
What is the relevant difference between 1.23 and 1.23f
1.23 has type double, 1.23f has type float.
Why can a floating-point literal be cast to a char?
char is an integer type, has (at-least) 8-bits. Just like int a = 1.23; is converting 1.23 to int, the same does char c = 1.23, it's the same conversion, just char i... |
71,111,360 | 71,111,692 | C++ always use checked_cast instead of static_cast? | When I read about C++ casting operators, I see generally see 4 types of casts for example here:
Cast types
const_cast
dynamic_cast
reinterpret_cast
static_cast
But what about checked_cast as described here
checked_cast
Should we always use checked_cast instead of static_cast as a rule of thumb?
| checked_cast only replaces static_cast.
That article assumes that you never want a lossy conversion. If you have a float and want the largest int not larger than that, checked_cast is incorrect.
It also assumes that the conversion goes both ways. If it doesn't then it's ill formed.
|
71,111,670 | 71,112,883 | Why doesn't std::vector.size() work with MPI? | I've troubles using the method .size() of std::vector when data are sent/received through the MPI interface. I created a custom type named point
template<typename T>
struct point{
T data[ndim];
point() = default;
point(const T& a, const T& b): data{a,b} {} // not correct
point(const T&& ... | First of all, MPI doesn't know much about C++, you're really using the C interface. So receiving does not do a push_back: you give it a buffer that's large enough and it writes the elements in there. (And after all, you only pass it buffer.data() so MPI doesn't even know that the buffer is a std::vector.)
It is still p... |
71,112,204 | 71,112,278 | In a multi-level inheritance, does a grandchild require to implement a pure virtual method, if its parent has already implemented it? | class A {
public: virtual void start() = 0;
};
class B : public A {
public: void start();
};
class Ba : public B {
};
Do we need to redefine start() in Ba or the parent's B::start() would be enough?
| Parent's start() is enough.
You should though use the override keyword for B's reimplementation :
class B : public A {
public: void start() override;
};
It makes it clear that the method is an implementation of a virtual one and the compiler will enforce that it will always be the case, even with future changes on c... |
71,112,750 | 71,113,085 | Create a vector of pairs from a single vector in C++ | I have a single even-sized vector that I want to transform into a vector of pairs where each pair contains always two elements. I know that I can do this using simple loops but I was wondering if there is a nice standard-library tool for this? It can be assumed that the original vector always contains an even amount of... | Use Range-v3:
#include <range/v3/range/conversion.hpp>
#include <range/v3/view/transform.hpp>
#include <range/v3/view/chunk.hpp>
using namespace ranges;
using namespace ranges::views;
int main() {
std::vector<int> origin {1, 2, 3, 4, 5, 6, 7, 8};
std::vector<std::pair<int, int>> goal {{1, 2}, {3, 4}, {5, 6}, ... |
71,114,091 | 71,114,511 | glEnable(GL_ALPHA_TEST) gives invalid enum (seems to be depreciated - code works though - but why?) | Quick question - title says it all:
In my OpenGL-code (3.3), I'm using the line
glEnable(GL_ALPHA_TEST);
I've been using my code for weeks now and never checked for errors (via glGetError()) because it works perfectly. Now that I did (because something else isn't working), this line gives me an invalid enum error. Goo... |
Yes, I'm using discard in the fragment shader. Otherwise, I just used to code above, so I guess, only one depth value (standard?).
discard is the replacement for glEnable(GL_ALPHA_TEST);.
So, did I put something redundant in there?
Yes discard and glEnable(GL_ALPHA_TEST); would be redundant if you use a profile for... |
71,114,208 | 71,115,046 | Algorithm for cutting mesh with the plane | I'm trying to write an algorithm for cutting tessellated mesh with the given plane (plane defined with the point on the plane and unit normal vector). Also, this algorithm should triangulate all polygons and fill the hole after split.
I faced with a problem to find a polygon that lies on the plane (like the orange plan... | Identify all edges that you cut by the indexes (or labels) of the endpoints. Make sure that every edge belongs to exactly two faces and is cut twice. Also make sure to orient the edge that results from the intersection consistently with the direction of the face normal.
Now the intersection edges form a chain that you ... |
71,114,212 | 71,118,045 | Avoid passing void expression, when pass from macro to function | I want to write a debugging macro which prints the name of the function called when there is an error. The catch is that some functions return values, and I would like to return any value back from the macro.
This is my attempt:
#define check(expr) _check_expr(#expr, expr)
extern bool check_for_error();
template <typ... | A void function can return a void expression. This also applies to lambdas:
#define check(expr) _check_expr(#expr, [&] () { return expr; })
extern bool check_for_error();
template <typename Fn>
inline auto _check_expr(const char *str, Fn fn)
{
auto check_ = [str]() {
if (check_for_error()) {
f... |
71,114,380 | 71,120,317 | How to make C++ accept ngrok address? | I’ve created a simple C++ program that uses sockets to connect to my other machine. I don’t have windows pro so can’t open port 3389 and I don’t want to download other third party applications as I genuinely want to complete what I have finished.
I’m paying for an ngrok address in the format of: 0.tcp.ngrok.io:12345
Th... | inet_addr() only works with strings in IP dotted notation, not with hostnames. So, inet_addr("0.tcp.ngrok.io") will fail and return -1 (aka INADDR_NONE), thus you are trying to connect to 255.255.255.255:12345. But it will work fine for something like inet_addr("196.168.#.#") (where # are numbers 0..255).
You need to ... |
71,116,990 | 71,117,065 | I don't understand why I have a dangling pointer | I have written this method:
std::string Utils::GetFileContents(const char* filePath)
{
std::ifstream in(filePath, std::ios::binary);
if (in)
{
std::string contents;
in.seekg(0, std::ios::end);
contents.resize(in.tellg());
in.seekg(0, std::ios::beg);
in.read(&contents... | The function returns an object of the type std::string
std::string Utils::GetFileContents(const char* filePath)
You are assigning a pointer with the address of the first character of the returned temporary string
const char* code = Utils::GetFileContents(path).c_str();
After this declaration the returned temporary ob... |
71,117,107 | 71,234,687 | Should I group all my code and move into DLLs? | Will I get better performance if I break my code into pieces put them in DLLs?
Is there something wrong with having multiple DLLs in terms of performance or is it better? Or does not have any affect?
My project is quite large and I heard that DLLs are not suitable for cross-platform apps. Is it true?
| DLLs can have positive and negative impact on performance. As with all performance questions you should get data before committing to a strategy.
Huge headers / huge code / slow compilation does not mean slow performance. It's often the other way around: that slow compilation is because you've given the optimizer a lot... |
71,117,428 | 71,125,988 | Is possible create QString at compile time? | Consider below code:
static constexpr QString FOO = QStringLiteral("foo");
but can not compile this line because QString has not default destructor.
How I can do something like this?
| In Qt 6.2 you can use the new u"my string"_qs syntax. https://doc.qt.io/qt-6/qstring.html#operator-22-22_qs
|
71,117,618 | 73,726,711 | Detect white or black high contrast mode in Windows C++ | The MS App Assure team reported to me an issue where my app's notification area/system tray icon is nearly invisible on white high contrast themes (or near-white like Windows 11's "Desert" theme).
I already have a dark icon I use when the (normal, non high-contrast) Windows light theme is on so I would like to use it i... | First, check if High Contrast mode is on:
HIGHCONTRAST info = { .cbSize = sizeof(info) };
if (SystemParametersInfo(SPI_GETHIGHCONTRAST, 0, &info, 0) && info.dwFlags & HCF_HIGHCONTRASTON)
{
// it's on
}
Then, you check the relative luminance of GetSysColor(COLOR_WINDOWTEXT). If it's lower than or equal to 0.5, then... |
71,117,785 | 71,117,868 | Is there a technique for named instances of an anonymous struct to reference functions inside the enclosing class? | I have a CRTP class where for API clarity during refactoring, I want to have a named anonymous struct containing methods, instead of having all methods at class scope. The problem is, these methods need access to the outer scope. For example:
template<typename T>
class sample_class {
public:
struct {
void d... | A class in another class has no implicit pointer to the enclosing class's this pointer.
If you want it to have the pointer to an instance of the enclosing class, explicitly store it.
struct {
void do_something() {
auto& result = p_sample->get_ref().something_else(); //get_ref() out of inner struct scope
...
... |
71,117,898 | 71,118,488 | using "new" and "delete" inside class function | I want to be sure that using new and delete to free heap memory is done as needed.
Following function returns a char *. Inside each function I use new for the returned value, and I delete afterwards.
Is it the right way to free heap memory for function return?
const char *myIOT2::_devName()
{
char *ret = new char[M... | At least as I see things, you really only have two sane choices here. One is for the caller to handle all the memory management. The other is for the callee to handle all the memory management.
But what you're doing right now (callee handles allocation, caller handles de-allocation) is a path to madness and memory leak... |
71,118,349 | 71,118,448 | How to handle and iterate through this list? | I have this type of list:
std::list<MyClass*>*
I want to iterate through this list and I also want to call the methods of MyClass, I want to do something like this:
std::list<MyClass*>* elements;
for (?)
{
std:: cout << elements[i]->Membermethod(); << std::endl;
}
How can I do it?
| std::list<MyClass*>* elements;
for (auto it = elements->begin(); it != elements->end(); ++it)
{
std::cout << (*it)->Membermethod() << std::endl;
}
note that its highly recommend not to put raw pointers in collections, use std::shared_ptr or std::unique_ptr
Much cleaner (also in c++11) is a 'ranged for'
for (auto p... |
71,118,564 | 71,118,789 | Check if folders name starts with certain string | Hello so basically what i want is to loop through all folders in a given directory and find a folder which contains 4p in it´s name
for (const auto& folderIter : filesystem::directory_iterator(roaming))
{
if (folderIter.path() == folderIter.path().string().contains("4p") != std::string::npos)
{
filesyst... | Since you told:
im trying to find a folder which starts with the name 4p. Nothing more
Does this meet your demands?:
#include <iostream>
#include <vector>
using namespace std;
int
main ()
{
std::vector < std::string > _strings;
// adding some elements to iterate over the vector
_strings.emplace_back ("4p_path"... |
71,118,715 | 71,119,538 | Is there an elegant way of parsing a byte buffer of dynamic length into a struct? | Background
As sketched up here https://godbolt.org/z/xaf95qWee (mostly same as code below), I am consuming a library that offers a shared memory ressource in form of a memory-mapped file.
For statically sized messages the read method can very elegantly return a struct (that matches the buffer's layout) and the client h... | A example of how i handle it in my code.
class packet
{
public:
packet(absl::Span<const char> data)
{
auto current = data.data();
std::memcpy(&length_, current, sizeof(length_));
std::advance(current, sizeof(length_));
vec_.reserve(length_);
vec_.assign(current, current + length_);
}
/... |
71,119,125 | 71,120,027 | #include recursion with template | I have problem like there Why can templates only be implemented in the header file? (and there Correct way of structuring CMake based project with Template class) but with include recursion.
Code:
A.h
#pragma once
#include "B.h"
struct A
{
B b;
void doThingA() {}
};
B.h
#pragma once
struct A;
struct B
{
... | When you have types that are this tightly coupled, the simplest solution is to put them in a single header file.
#pragma once
// forward declaration of A
struct A;
// declare B, since A needs it
struct B
{
A *a;
template<typename T>
void doThingB();
};
// now we can declare A
struct A
{
B b;
void... |
71,119,635 | 71,125,240 | How to accurately multiply a COleCurrency by a double? | I have a COleCurrency object that represents a unit price. And I have a double value that represents a quantity. And I need to calculate the total dollar amount to the nearest penny.
Looks like COleCurrency has built in multiplication operators, but only for multiplication with a long value.
I can multiply COleCurrency... | Finite binary floating point values form a proper subset of finite decimal values. While any given floating point value has an exact, finite representation in decimal, the opposite isn't true. In other words, not every decimal can be represented using a finite binary floating point value. A simple example is 0.1 that p... |
71,119,662 | 71,119,700 | Why is my input validation function not working? (C++) | I'm writing a program that calculates the cost of a purchase based on user input. If the user uses negative or otherwise invalid values for price and quantity the program should print an error and ask again.
#include <iostream>
#include <string>
#include <cmath>
#include <limits>
#include <algorithm>
using namespace s... | std::cin << string by default reads up to the first whitespace. Note that if you print str inside validatePrice(), it won't be the full input you specified.
You should use std::getline() instead to read an entire line.
|
71,119,822 | 71,120,354 | Every partition of a number using recursion | While doing some backtracking exercises, got stuck here:
Write a recursive algorithm that generates all partitions of a given n
numbers. Of the partitions that differ only in the order of the
members, we need to list only one, the last from a lexicographic point
of view. Write the solutions lexicographically in ascend... | When you get more practice programming, you'll learn how to keep things simple:
#include <iostream>
#include <vector>
void decompose(int n, std::vector<int> prefix = {}) {
if (n == 0) {
for (int a : prefix) { std::cout << a << ' '; }
std::cout << std::endl;
}
else {
int max = prefix.size() ? std::min... |
71,119,882 | 71,119,976 | Can std::filesystem::permissions change secure file permissions | I have been experimenting, with the std::filesystem and I came across the permissions function, which allows you to change the access permissions that users have to files. This seems almost like it could be a bad thing though because anyone can run a program and gain access to files that they shouldn't. Is this how it ... | The operating system kernel is responsible for enforcing access control, and such enforcement applies to all programs, regardless of what APIs they use. On a Unix-like operating system, a process can only change file permissions if:
the process's effective user ID matches the file's owner, or
the process has the CAP_F... |
71,119,956 | 71,124,648 | Passing the standard output of function A as the argument of function B in C++ | I'm starting C++ and I'd like to code a linker
I first did a tokenizer executable that takes as an input a file and print in the standard output the list of its tokens
%./tokenizer input_file
Token 1 : 3
Token 2 : X
token 3 : 10
etc
...
Then, I programmed a linker executable that takes as an input a token file and pri... | A simple way would be to use streams
You have to change
void getTokens(char* file[]) {
string token;
ifstream _file (file);
doStuff(_file);
// ....
cout << token << endl;
// ....
}
into
void getTokens(std::istream& in, std::ostream& out) {
doStuff(in);
// ....
out << token << endl;
// ...... |
71,119,987 | 71,120,036 | How references can bind to prvalues? | cppreference says that: a temporary object is created when a reference is bound to prvalue. Do they mean const lvalue references and rvalue references?:
Temporary objects are created when a prvalue is materialized so that it can be used as a glvalue, which occurs (since C++17) in the following situations:
binding a r... | The only references that are allowed to bind to object rvalues (including prvalues) are rvalue references and const non-volatile lvalue references. When such a binding occurs to a prvalue, a temporary object is materialized. Temporary materialization thus occurs in both of the OP's examples:
const int &x = 10;
int &&x2... |
71,120,169 | 71,125,539 | Bit shifting a half-float into a float | I have no choice but to read in 2 bytes that make up a half-float. I would like to work with this in the form of a 4 byte float. Ive done some research and the only thing I can come up with is bit shifting. My only issues is that I dont fully understand how to grab only a few bits and put them into the float. I have th... | Here is code demonsrating the 16-bit floating-point to 32-bit floating-point conversion plus a test program. The test program requires Clang’s __fp16 type, but the conversion code does not. Handling of NaN payloads and signaling/non-signaling semantics is not tested.
#include <stdint.h>
// Produce value of bit n. n... |
71,120,672 | 71,120,707 | Returning a generated vector in C++ | Three C++ functions that create a vector and return:
vector<int> generate_vector_v(int n) {
vector<int> foo;
for (int i = 0; i < n; i++) {
foo.push_back(i);
}
return foo;
}
vector<int>* generate_vector_p(int n) {
static vector<int> foo;
for (int i = 0; i < n; i++) {
foo.push_ba... | generate_vector_m The behaviour of the program is undefined, and it returns a bare owning pointer which would probably lead to a memory leak, and it is slow due to unnecessary use of dynamic memory. Don't use it.
generate_vector_p appends more and more elements into a single static vector on every call. That's not ofte... |
71,120,714 | 71,120,797 | Linking with jack using qmake | I have two similar projects on the same machine. Their difference is that one is using GUI (Qt and Qwt) and the other is not. As the result, the one that has Qt is using qmake to compile and the other one cmake.
The project itself is about signal processing and working with audio. I decided to use RtAudio for capturing... | To let qmake know where to find the lib please add
LIBS += -L"where-you-have-jack-lib" -ljack
|
71,121,321 | 71,166,169 | Making RtAudio use jack for audio capture | I'm trying to use RtAudio in Linux. To start, I've compiled it with jack enabled:
$ ./configure --with-alsa --with-jack
$ make
$ make install
Then I found a small example to test RtAudio out:
#include "RtAudio.h"
#include <iostream>
#include <cstdlib>
#include <cstring>
int record( void *outputBuffer, void *inputBuff... | For anyone else who might be dealing with the same problem, here is how I fixed it:
$ ./configure --with-alsa --with-jack --with-pulse
$ make
$ make install
|
71,121,474 | 71,126,795 | How to implement C++ Task Scheduler | I Know the following code is not Task Scheduler Perhaps
However, trying to get your valuable comments in understanding the scheduler
I am trying to understand & come up with a bare minimum code which can be called as TaskScheduler.
I have the following code but am not sure if it suffices as scheduling.
Could someone pr... |
I have the following code but am not sure if it suffices as scheduling.
Why not just do this?
void run_packaged_task()
{
cout << "\n Res: " << factorial_loc(4);
}
Maybe you think that my version of run_packaged_task() is not a scheduler. Well, OK. I don't think so either. But, as far as the caller can tell, my v... |
71,121,527 | 71,121,645 | How to get correct number from args? | I write an application, which get a number from args.
ex:./app --addr 0x123 or ./app --addr 123
I don't know which api can identify if the parameter is hex or decimal and come up with the correct data?
Thanks.
| One way of getting the arguments is through argc and argv in
int main(int argc, char* argv[]) {
// Some code here.
return;
}
This will give you an array with all the arguments as strings. For example:
#include <iostream>
int main(int argc, char* argv[]) {
for (int i{ 0 }; i < argc; i++)
std::cout ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.