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 |
|---|---|---|---|---|
74,619,458 | 74,619,683 | Can a C++ constructor return a pointer to a cached version of an identical object? | Let's say I have a class Bitmap that has a static cache map textures that holds pointers to all images that have been registered.
class Bitmap {
public:
Bitmap(const std::string &filename);
// ... functionality ...
private:
// ... image data ...
std::string filename;
static std::map<std::string, std::... | By the time you're actually constructing an object, you're already outside the scope of controlling the object's allocation. The constructor is simply there to initialize the object.
One way to achieve this with minimal changes to your code is to make the constructor private and create a static method to perform the cr... |
74,619,489 | 74,620,581 | How may I bind a Toast progress bar with my C++ Win32 application? | I'm creating a c++ Win32 application which should show some Toast notifications. One of them contains a progress bar. I need to bind its value with my application in order to update it while the status changes in the currently running operation.
The Toast interface containing the progress bar is defined as follow:
<toa... | If a WinRT class can be created from C#, it means it's activatable (or it's associated with another "statics" class which is), which you can check if you go to NotificationData documentation:
[Windows.Foundation.Metadata.Activatable(262144, "Windows.Foundation.UniversalApiContract")]
[Windows.Foundation.Metadata.Activa... |
74,620,490 | 74,635,520 | I encountered the 10^9+7 problem but I can't understand the relation between the distributive properties of mod and my problem | Given 3 numbers a b c get a^b , b^a , c^x where x is abs diff between b and a cout each one but mod 10^9+7 in ascending order.
well I searched web for how to use the distributive property but didn't understand it since I am beginner,
I use very simple for loops so understanding this problem is a bit hard for me so how ... |
I use very simple for loops [...] this works for very small inputs, but large ones it exceeds time.
There is an algorithm called "exponentiation by squaring" that has a logarithmic time complexity, rather then a linear one.
It works breaking down the power exponent while increasing the base.
Consider, e.g. x355. Inst... |
74,620,649 | 74,620,879 | Multi-type container C++. Casting to derived template class | I am trying to implement a multi-type container in C++ without using std::any, std::variant, boost::any, etc. The add() function adds new objects (int, string, or other Structures) by wrapping them in the template element class and storing as Structure pointers:
using StructPtr = std::shared_ptr<Structure>;
class Stru... | You can't perform a static_cast inside of printElement() since you don't know what to cast to (dynamic_cast would have helped you with that), so the only solution is to make Structure::print() be virtual and have Element override it, eg:
class Structure{
public:
...
virtual void print(std::o... |
74,621,059 | 74,621,110 | vector data loss when exiting a loop | i did a very basic and small function to convert a number smaller than 256 to binary
void convertToBinary(short decimalNumber, vector<short> &binaryNumber)
{
short divisor = 128;
while (decimalNumber != 0)
{
short divised = decimalNumber/divisor; // 1
binaryNumber.push_back(divised);
... | you end up with divisor = 0
this works fine
while (decimalNumber != 0 && divisor > 0)
|
74,621,444 | 74,622,351 | Loop control inside void function keeps looping |
void getDay() {
bool repeat;
do
{
cout << "Enter the day code (first 2 letters): ";
cin >> weekDay1;
cin >> weekDay2;
weekDay1 = toupper(weekDay1);
weekDay2 = toupper(weekDay2);
switch (weekDay1)
{
case 'M':
... | The condition in the while loop is always true because you never set it to false in its body. You can do something like this:
void getDay() {
// Initializing while declaring is a good practice.
bool repeat = false;
do {
.
.
repeat = false;
.
switch(...) {
...
}
} while (repeat);
}... |
74,621,772 | 74,621,964 | How to launch the QMainWindow with a fading animation? | I tried launching my window this way:
#include "stdafx.h"
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
setWindowOpacity(0);
QGraphicsOpacityEffect* eff = new QGraphicsOpacityEffect(this);
QPropertyAnimation* ani = new QPropertyAnimatio... | Two issues I see. First, as originally written, your main function is going to exit immediately after opening the window. Add return a.exec(); at the end of main.
Next, you are animating QGraphicsOpacityEffect. As written, your example code has no connection between QGraphicsOpacityEffect and the window. Your animation... |
74,621,794 | 74,621,947 | Why can you cast a integer as a void pointer but can't with CString? | Just a heads up, I'm referencing from a working code, and I'm trying to implement the same method but with a CString.
The below method that works, casting an integer as a void pointer:
void **pParam = new void*[2];
pParam[0] = reinterpret_cast<void*>(this);
pParam[1] = reinterpret_cast<void*>(iTrayNumber);
_beginthread... | reinterpret_cast performs a number of specific casts, all of which are needed only in rather special circumstances. You shouldn't need reinterpret_cast for what you are doing here.
One of the casts allowed with reinterpret_cast is casting one object pointer type to another object pointer type. The effect of this depend... |
74,621,892 | 74,621,939 | Dynamic Programming: Why does the code fail when I break the if statement up into 2 lines? | I am working on this question https://structy.net/problems/min-change in which given a vector of coins and a target amount, I need to return the minimum amount of coins that satisfy the target amount.
The variable island size represents the minimum amount of change that should be given to the customer and currentSize r... | The conditional statement
if(currentSize != -1 && (islandSize == -1 || currentSize + 1 < islandSize))
{
islandSize = currentSize + 1;
}
could be rewritten as
if(currentSize != -1)
{
if (islandSize == -1 || currentSize + 1 < islandSize)
{
islandSize = currentSize + 1;
}
}
The two statements
if(... |
74,622,124 | 74,622,469 | Passing method with variadic arguments as template parameter for a function | Suppose to have the following definitions
struct Cla {
void w(int x){}
};
template <typename C, void (C::*m)(int)> void callm(C *c, int args) {}
template <typename C, typename... A, void (C::*m)(A...)>
void callmv(C *c, A &&...args) {}
int main(){
callm<Cla, &Cla::w>(&cla, 3);
callmv<Cla, int, &Cla::w>(&cla, ... | All parameters after a variadic parameter pack are always deduced and can never be passed explicitly. &Cla::w is being interpreted as the next type argument in the parameter pack A, not the non-type template argument. The error you get is the compiler complaining about &Cla::w not being a type.
Which means you have to ... |
74,622,227 | 74,642,091 | Avoid calling of function size_t Print::print(unsigned long long n, int base) if it is not implemented | I maintain an Arduino library which uses the following code (simplified) to print results received by infrared.
unsigned long long decodedData; // for 8 and 16 bit cores it is unsigned long decodedData;
Print MySerial;
MySerial.print(decodedData, 16);
Most of the 32 bit arduino cores provide the function size_t Print... | With C++11 you can do something like this:
#include <iostream>
#include <iomanip>
#include <type_traits>
// First implementation of printer
class Impl1 {
public:
static void print(uint64_t value, int base) {
std::cout << "64-bit print: " << std::setbase(base) << value << "\n";
}
};
// Second implemen... |
74,622,526 | 74,622,577 | Templatizing a parameter for a function in C++ | I'm a beginner for programming and read an example codes, while I was learning about algorithm with C++.
template <size_t N>
void print(const std::array<int, N>& arr)
{
for(auto element: arr)
{
std::cout << element << ' ';
}
}
Now I'm curious what the difference is for the templatizing like above a... |
Does work they same?
No, the second snippet with std::array<int, size_t> won't even compile because the second template parameter of std::array is a non-type template parameter of type std::size_t and so it expects an argument of type size_t(or convertible to it).
Thus, size_t is not a valid template argument for the... |
74,622,568 | 74,622,745 | Runtime GL_VERSION doesn't match glxinfo? | I need to use Tessellation in OpenGL, which means that my OpenGL version need to be 4.0 or upper. I get my OpenGL version with glxinfo | grep OpenGL in terminal. Output shows in the following:
OpenGL vendor string: NVIDIA Corporation
OpenGL renderer string: NVIDIA GeForce RTX 3090/PCIe/SSE2
OpenGL core profile version ... | Which context are you requesting at runtime? Almost sounds like you are requesting a 3.3 context? (or the windowing lib you're using is).
in glut:
glutInitContextVersion( 3, 3 );
glutInitContextProfile( GLUT_CORE_PROFILE );
in glfw:
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MIN... |
74,622,597 | 74,622,627 | Overloaded Constructor Throwing Redefinition Error | I have an assignment that requires me to write overloaded constructors for a class (Car) in c++. I keep getting a redefinition error but cannot pinpoint what's causing it. I feel that it could possibly have to do with the code being separated out between two separate files (Car.h, Car.cpp) but I'm not sure.
Here is t... | Car(){};
Car(string userMake, string userModel, double userPrice){};
These are defining the constructor bodies, not just declaring their signatures. Since it looks like you want to implement the constructors outside of the class in a .cpp file (which is good practice to do), just remove the braces. A prototype doesn'... |
74,622,645 | 74,636,953 | Why in CPP in some system the RAND_MAX is set to 32K while in others it is 2147483647 | In my CPP system whenever I generate a random number using rand() I always get a value between 0-32k while in some online videos and codes it is generating a value between 0-INT_MAX. I know it is dependent on RAND_MAX. So it there some way to change this value such that generated random number are of the range 0-INT_MA... | rand() is a very old function, going back to the earliest days of C. In those early days, an INT_MAX of 32k was common and well justified. Surely it's easy to see that RAND_MAX > INT_MAX doesn't make any sense.
As for why some compilers have updated their RAND_MAX in the intervening years and some have not, I would g... |
74,623,342 | 74,638,350 | cython cannot insert into deque using iterators | I am wondering if this is a bug or I am doing something wrong:
from libcpp.deque cimport deque as cdeque
cdef cdeque[int] dq1, dq2
dq1.push_back(0); dq1.push_back(1)
dq2.push_back(2); dq2.push_back(3)
dq1.insert(dq1.begin(), dq2.begin(), dq2.end())
The above code gives me 2 similar errors at compile time: Cannot con... | This was a bug in Cython versions prior to 3.0 (see this PR).
On an prior version, we have the following options
A: wrap insert, e.g.
....
cdef extern from *:
"""
template <typename T, typename It>
void insert(T& dest, const It& begin, const It& end){
dest.insert(dest.begin(), begin, begin)
}
... |
74,624,271 | 74,626,443 | Is `v[i] = ++i;` a well-defined behavior? | Reading ES.43: Avoid expressions with undefined order of evaluation, it states that the result of this expression
v[i] = ++i;
is undefined. I'm assuming that's another way to say we got undefined behavior (UB).
Reading SO posts on this topic, specifically Why is i = i++ + 1 undefined behavior in C++11? and Undefined b... |
Value computation of right operand is sequenced before value computation of left operand for assignment operator (N4835, §[expr.ass]/1.)
Not only value computation, also side effects. This rule was however added only with C++17.
This rule alone is enough to make your expression well-defined. But even if the side effe... |
74,624,695 | 74,624,727 | Why is my for loop not working properly when checking if a vector is sorted or not? | I'm trying to check if a vector is sorted or not with a for loop but it's not working properly
until I make a small change but the logic seem to be the same to me.
this is the code:
vector <int> is_list_sorted(vector <int> list_of_numbers){
bool list_is_sorted = true;
for(int i = 0; i < list_of_numbers.size(); i... | With the loop
for(int i = 0; i < list_of_numbers.size(); i++)
then list_of_numbers[i + 1] will be out of bounds for the last element.
If you go out of bounds you will have undefined behavior.
A different solution would be to change the loop to:
for(int i = 0; i < list_of_numbers.size() - 1; i++)
Then i + 1 will not b... |
74,624,925 | 74,626,248 | Redefine a Node of linked list: std::string | I am currently working on a school project, the material is new to me at the moment, basically, we are creating a Robot Guider that tracks their movement, distance, speed, etc... one of the functions that we are required to make is renaming a robot, however, they are stored in Node.
I have spent some time looking aroun... | The problem is the while loop.
Head is a pointer to the first element so !head is true only when the list is empty, which is not what you want. Head should not be modified because we will lose the start of the list, that's why we have the temp.
The loop should stop at the end of the list, we know we reached the end whe... |
74,625,015 | 74,625,115 | Multiple inputs in one line in C++ | I've newly started learning C++ and am stuck with this problem. I need to insert a (user inputted) number of elements in a single line with space separation. If the number of elements was known, I could just write cin >> var1 >> var2 >> ... >> varN;. But how do I do it with any number of elements (loop maybe)?
This is ... | cin>>arr[i] does not require the user to press enter after every input.
You just need to give whitespace between the integer inputs. It will scan the array normally.
|
74,625,288 | 74,625,344 | Returning an array with booleans c++ | Sorry if this is a duplicate in advance.
I am trying to return an array of booleans in a function in c++, where the array's size is declared as an argument to the array.
Could I do something like this?
bool returnBools(int size) {
bool returnValue[size];
// Do some stuff with array
return returnValue;
}
| It's not possible to return an array from a function in C++ (nor in C). The C++ solution is to use a vector.
#include <vector>
std::vector<bool> returnBools(int size) {
std::vector<bool> returnValue(size); // note () not []
// Do some stuff with vector
return returnValue;
}
When manipulating the vector ... |
74,626,140 | 74,626,558 | First element of array not showing | I was coding a function that squares every number and then sort the array in ascending order
But When I ran my code it is not showing the first element of the array
i.e. if the array is [1 2 3 4 5]
It is showing only [ 4 9 16 25 ]
Code:
#include <bits/stdc++.h>
#include<vector>
using namespace std;
void sortedSqu... | You are missing an equals sign in your "while" inside sortedSquaredArray function. It should look like this: while(leftPtr <= rightPtr).
|
74,626,322 | 74,626,541 | How to include a c++ library that only provides .h and .dll files (no .lib)? | I'm working on a c++ project where I need to include the IPE library. This is available here, and since I use Windows I download and extract the windows binary package. This provides an 'include' folder with header files, and a 'bin' folder with several .dll files, among them ipe.dll.
From what I understand (for exampl... | You need a .lib to link to. That .lib knows how to dynamically resolve the symbols in the .dll. If you don't have a .lib, you need to dynamically load the symbols yourself.
See: Dynamically load a function from a DLL
|
74,626,503 | 74,626,600 | How can I create a folder in C++ that is named using a string or char? | I'm trying to create a folder with a custom name for each user that will logged in but it doesn't work. Can you please help me? I'm a beginner and it's quite difficult.
#include <iostream>
#include <direct.h>
using namespace std;
int main() {
string user = "alex";
_mkdir("D:\\Programe\\VS\\ATM\\Fisiere\\" + us... | _mkdir is an older function which takes a C string as it's parameter. So you have to convert the std::string that you have into a C string. You can do that with the c_str method. Like this
_mkdir(("D:\\Programe\\VS\\ATM\\Fisiere\\" + user).c_str());
This code creates a std::string by appending the path with the user s... |
74,627,180 | 74,637,364 | Projection: Is it OK to take address of data member of STL container? | Let's take (as a demo example) a simple counting algorithm for getting the max count of characters in a string.
A typical C++17 implementation could be:
#include <iostream>
#include <unordered_map>
#include <string_view>
#include <algorithm>
#include <utility>
using Counter = std::unordered_map<char, std::size_t>;
usi... | The only restrictions I see in [namespace.std] are about pointers to member functions. I can't find anything that would disallow taking a pointer to a (public) data member of a standard library class.
This also makes sense, since the restrictions for functions are there to allow the standard library implementation to c... |
74,628,978 | 74,629,042 | How do I open a file txt in a specific folder using visual studio c++? | This is the part of code where I try to open the file f1.txt, it is complete path is C:\Users\Hp\Desktop\NSGA2-CDS\DataSet\f1.txt
ifstream fichier("C:\Users\Hp\Desktop\NSGA2-CDS\DataSet\f1.txt", ios::in);
The file cannot be opened and I don't know why?!
NSGA2-CDS is the folder that contain the visual studio solution
| You have to escape backslashes in the path string:
ifstream fichier("C:\\Users\\Hp\\Desktop\\NSGA2-CDS\\DataSet\\f1.txt", ios::in);
This has nothing to do with file I/O as such; it's a feature of string literals: \ is used to escape special characters (such as \n, \t), so when it appears in a string, it needs to be es... |
74,629,463 | 74,629,737 | Bubble sort refuses to run in application compilers, but runs on online compilers | So this is the code I wrote for bubble sorting a user defined list. It crashes (brings the error, 'main.exe has stopped working') when I use apps like DevC++, CodeBlocks and VSCode to run. but when I use a web compiler, it works perfectly.
(The apps only crash while running this code. They are able to run other pieces ... | Problem is numbers[n] with un initialised value of n. It takes some garbage value of n and tries to allocate space. It may work sometime and may fail sometime depending on what is the garbage value its taking.
If the garbage value of n is negative or too large, it will fail. Move array declaration after initialisation... |
74,629,665 | 74,629,835 | Why can't I create a reference to a const pointer? | int *pointer = nullptr;
const int *ponter2 = pointer; // working
const int *&referpointer = pointer; // error
const int *& const referpointer2 = pointer; // it is working;
I wonder why a plain pointer can initialize a reference to a constant pointer to a constant, but cannot initialize a reference to a pointer to a c... | If it did work, you could do this
int i;
int *pointer = &i;
const int *&referpointer = pointer;
const int const_i = 4;
const int *const_pointer = &const_i;
referpointer = const_pointer; // same as pointer=const_pointer; via the reference
*pointer = 5; // changes const_i
Then you would have found a way to change a con... |
74,629,674 | 74,629,719 | how to add a background sound in my program that does not stop until I close the console in c++ | The issue I'm facing is that the sound is not running in a loop, the whole sound is executed once, it does not repeat.
So basically, I have used this method:
#include <Windows.h>
#include <thread>
#include <iostream>
void play_music() {
PlaySoundA("sound.wav", NULL, SND_FILENAME | SND_LOOP);
}
int main(){
s... | From the documentation:
SND_LOOP
The sound plays repeatedly until PlaySound is called again with the pszSound parameter set to NULL. If this flag is set, you must also set the SND_ASYNC flag.
|
74,629,752 | 74,629,961 | Is there a way to write the following python If statement condition in C++? | Im in the process of trying to recreate a piece of python code for a simple calculator in C++,
in python i have the following piece of code thats located in a while loop
func = str(input("which function: add, sub, div, mult"))
if func in ("add", "sub", "div", "mult"):
#secondery if statment
else:
print("error")... | Here's a working snippet
#include <iostream> // std::cout, std::cin
#include <string>
#include <array> // one of the many STL containers
#include <algorithm> // std::find
int main() {
const std::array<std::string, 4> functions = {
"add",
"sub",
"div",
"mult"
};
std::string... |
74,630,061 | 74,630,554 | Matrix out of bounds but can't put condition to check bounds | I have a square matrix, 40 x 40, and a draw circle function that uses this formula.
I have another function that reads input from a file, the point itself (x0, y0) and the type of circle (0 or 1) and the radius.
void cerc(int x0, int y0, int r, int** matriceHarta, int tip, int n, int m)
{
if (r == 0)
return... | The issue is that you are testing for the out-of-bounds condition after you have already accessed potential out-of-bounds elements.
Let's break it down into separate lines:
if (xx + (y * y) <= rr && matriceHarta[x0 + x][y0 + y] == 0
&& // <-- This binds the conditions
(((x0+x) < n) && ((y0+y) < m)))
T... |
74,630,543 | 74,630,666 | Copy constructor throws null value error in C++ | (Been out of touch from cpp too long, wanted to brush up for the interview tomorrow).
Was revising Deep Copy v/s Shallow Copy. Wrote the code:
#include <iostream>
class MyClass {
public:
unsigned int* uivar = nullptr;
MyClass() : uivar(new unsigned int) {
*(this->uivar) = 3;
}
~MyClass() { d... | Your copy constructor is not correct, it would need to allocate its own pointer
MyClass(const MyClass& mCopy) {
uivar = new unsigned int(*mCopy.uivar);
}
|
74,631,498 | 74,636,318 | How to use [[(un)likely]] at do while loop in C++20? | do [[unlikely]]
{...}
while(a == 0);
This code can be compiled.
But is this the correct way to tell compiler that a is usually non-zero.
| Structurally, this is a correct way to say what you're trying to say. The attribute is placed in a location that tags the path of execution that is likely/unlikely to be executed. Applying it to the block statement of the do/while loop works adequately. It would also work within the block.
That having been said, it's u... |
74,631,663 | 74,631,794 | g++: crash when accessing ostringstream::str().c_str() | The code below fails on gcc 9.4.0. Is this just a bug, or have I done something stupid?
log declares an ostringstream object, writes a filename and a line number to it, and attempts to do something with the object's underlying str().c_str().
Valgrind shows this crashing at the pointer access. The output I get is:
foo.c... | std::ostringstream::str() returns a temporary string which will be destructed at the end of the line, this then means cptr is a dangling pointer.
Try:
std::string str = outstr.str();
const char *cptr = str.c_str();
cout << "cptr is at " << (void*) cptr << ", and is " << cptr;
|
74,632,788 | 74,632,824 | string relational operator comparison vs string::compare() in cpp | In short I am getting different output for string comparison using string::compare() vs relational operator '<' on std::string class objects.
string str = "100";
cout << str.compare("10")<<endl; //prints 1
cout << ("100" < "10") <<endl; //prints 1
Here's the demo url
lexicographically "100" is greater than "10" and he... | In this statement
cout << ("100" < "10") <<endl;
you are comparing two pointers of the type const char * to which the used string literals are implicitly converted. The result of such a comparison is undefined (At least in the C Standard there is explicitly stated that such operation is undefined).
In fact the above s... |
74,632,801 | 74,632,909 | How to get a function pointer to a member function | I was working on a project where I needed to get involved with function pointers, more specifically function pointer to member functions. I have read almost all the related questions, however none of them describing my specific problem. So, I will try to describe my problem by a simple example.
Let's assume that I have... | Since both Foo2 and Foo3 need the definition of Foo1, they should both #include "foo1.h". Without the definition of Foo1 the compiler will not be able to calculate the size of neither Foo2 nor Foo3.
Foo1 on the other hand does not need the definition of Foo2 and can therefore forward declare Foo2 to resolve the deadloc... |
74,632,916 | 74,633,153 | How to access and convert pair value? | vector<pair<int,char>> alpha;
for(int i = 0; i < 26; i++)
{
if (letter[i] > 0)
{
alpha.push_back(pair<int,char>(letter[i], (i+'A')));
}
}
sort(alpha.begin(), alpha.end());
for(auto& val : alpha){
string str = val.second;
}
I was trying to convert map value (which was char type) into string t... | You could do
string str;
for(auto& val:alpha){
str.push_back(val.second); // Append to back of string
}
If you want to just append chars to the string.
Or you could do
auto str = string s(1, val.second); // 1 is the length of the string,
// and val.second is the ... |
74,633,705 | 74,633,864 | Are two std::string_views refering to equal-comparing string literal always also equal? | I have an unordered_map which is supposed to mimic a filter, taking key and value as std::string_view respectively. Now say I want to compare two filters that have the same key-value-pairs: Will they always compare equal?
My thought is the following: The compiler tries its best to merge const char*'s with the same byte... |
Naturally, as std::string_view doesn't implement the comparison operator==(), the compyler will byte-compare the classes
That is never the case. If no operator== overload (or since C++20 a rewritten candidate overload of e.g. operator<=>) is available for a class type, then it is simply impossible to compare the type... |
74,634,570 | 74,639,506 | What can I replace with the sleep command in the Windows variant of ncurses? | #include <curses.h>
#include <unistd.h>
#include <iostream>
int main() {
initscr();
mvaddstr(10, 10, "Hello, world");
refresh();
sleep(4);
endwin();
std::cout << "DONE\n";
}
I'm working on a project and I need to take down the curses windows for a while just to write a path to directory in cmd ... | napms is the (portable) curses function to use instead of sleep
|
74,634,663 | 74,635,744 | Is there ever a reason to create elements dynamically inside of an already existing dynamic array? | This is more of a theoretical question, and a non-serious one at that, but one I couldn't find an answer to online that I'm moreso just curious about.
If I were to create some class in C++ (we'll just call it Object) and made a dynamic array of this object type:
Object* objectArray = new Object[someSize];
Would there ... | One use case would be if you derive other classes from Object, and want the array to hold instances of different types of objects. In that case, you would need to have the array store Object* pointers, and then you would create each object individually. For example:
struct Object {
virtual ~Object() = default;
};
... |
74,634,692 | 74,635,100 | Class templates with multiple unrelated arguments | I have a class template, that creates a class with two members:
template<typename coordinateType, typename ...DataTypes>
class Object{
public:
std::tuple<coordinateType, coordinateType, coordinateType> position;
std::tuple<std::vector<DataTypes>...> plantData;
};
The issue is, rather... | if you change the caller side a little, you can make track to return a new class.
template<typename T, typename...Us>
struct Object{
std::tuple<T, T, T> position;
std::tuple<std::vector<Us>...> plantData;
};
// you can also give it a different name, here I use a specialization instead
template<typename T>
stru... |
74,634,786 | 74,634,879 | Avoiding template parameter substitution completely | I have a class that can accept arithmetic types and std::complex. A simplified code of the class is
#include <complex>
template<typename T> struct is_complex : std::false_type {};
template<typename T> struct is_complex<std::complex<T>> : std::true_type {};
template<class T>
struct Foo {
void foo(typename T::value... | You're on the right track with is_complex: you'd like the same here, but with a different body of the type. For example,
template<typename T> struct complex_value_type {};
template<typename T> struct complex_value_type<std::complex<T>> { using type = T; };
template<typename T>
using complex_value_type_t = typename com... |
74,634,852 | 74,635,392 | How do I use a for loop to flash a single LED on and off? (c++) (Mbed Studio) (Nucleo Board) | I am a complete coding noob but I am trying to get all LED's to flash on and off 5 times while specifically using a for loop (it has to be a for loop).
The LED in question is attached to a bus (also has to be the case) with the integer assignment of 76.
EDIT: When I try a simple for loop with a counter of 5 and then tu... | Your outer loop is counting the quantity of pulses.
The contents of the loop determine the frequency that an LED is on or off:
for (int counter = 0; counter < 5; ++counter)
{
// Turn on the LEDs
traffic = 76;
// Wait while the LEDs are on.
waitus(1000000);
// Turn OFF the LEDs
traffic = 0;
... |
74,635,031 | 74,635,067 | Memory leak while destroying a BST | I'm trying to code a destructor for my BST so that I don't have to delete everything manually.
I've tried multiple destructors for my BST but I keep getting a memory leak when running with valgrind.
Here is my code (destructor at the end of code).
#include <fstream>
#include <iostream>
#include <string>
using namespace... | Count the number of new operators and delete operators in your code. They should match. But it your code you care only of the BST objects, and never delete the User.
Why don't you implement the destructor of BST that correctly deletes all the fields?
Update Ok, after deleting the User you have a problem of incorrectly ... |
74,635,051 | 74,635,964 | Why does clang have trouble with optimizing tail calls in destructors? | Here is a simplified singly-linked list, where each node owns the next, along with a function for destroying the list:
struct Node {
Node* next = nullptr;
~Node() {
delete next;
}
};
void Destroy(Node* head) {
delete head;
}
Clang 15.0.0 with -O3 (Compiler Explorer) gives recursive code for this that u... | It's worth calling out explicitly something I alluded to in the question: that the operations in ~Node are in the opposite order that they are in Destroy2. The destructor is something like this:
// Pseudocode
~Node() {
delete next;
free(this);
}
So the question is why the compiler can't reverse those two operation... |
74,635,124 | 74,635,673 | Convert custom type to QVariant | I have my custom type:
enum class MyType : int {
TYPENAME1 = 0,
TYPENAME2 = 1,
TYPENAME3 = 2
};
I need to convert MyType to QVariant. I tried qDebug() << QVariant::fromValue(value) but I received " " instead of property value.
| For QVariant to store a custom type, you need the type to be registered with the qt meta object system.
Q_ENUM or Q_ENUM_NS in the header of the type
qRegisterMetaType<MyType>() called sometime before you try to use the type with QVariant (usually setup somewhere that is called when your app starts)
|
74,635,859 | 74,635,907 | C++ What's the problem in this line? int [] a = new int[size]; | As the title suggests,
int [] a = new int[size];
constantly throws me an error.
I am not yet familiar with C++ so please help me tweak the code above to as closely similar to the syntax above (above was a given pseudo(?) code in a class) so I can create an array.
Thank you.
#include <iostream>
using namespace std;
//... | new is for dynamic allocation (of an array on the heap in this case), and returns a pointer to the new array.
[] in the declaration are for declaring it to be a stack array (and the brackets belong the right side of the variable name).
So the two legal approaches your code is mixing would simplify to either:
int a[10];... |
74,636,046 | 74,662,939 | How to start a new process as user "NT AUTHORITY\Network Service"? | I am trying to launch a new process as NT AUTHORITY\Network Service from a process that is running as NT AUTHORITY\System.
I have looked at other questions, such as the following, which does not provide a working example: CreateProcess running as user: "NT AUTHORITY/Network Service" without knowing the credentials?
And... | I came across a function LogonUser which can be used to create token for required user. The doc shows an example for creating token for NT AUTHORITY\LocalService like this:
LogonUser(L"LocalService", L"NT AUTHORITY", NULL, LOGON32_LOGON_SERVICE, LOGON32_PROVIDER_DEFAULT, &hToken)
I used the above in combination with C... |
74,636,242 | 74,636,578 | Is it worth initializing constants in the correct type? (I.e. 10UL for unsigned long) | As someone who isn't familiar with digging into post-compiled code, I'm curious if I am wasting my time for zero gain by initializing variables values to the correct type.
Suppose I have class with an unsigned long member.
class A {
public:
A()
private:
unsigned long my_val;
};
Let's suppose I'm going to initializ... | The short answer is that it makes no difference at all, whatsoever.
An integer constant's type is the smallest type that will fit it, but no less than an int. Assigning a value to a wider integer type automatically converts. So, pedantically, a 0 value that's an int gets converted to an unsigned long 0 and gets used to... |
74,637,105 | 74,637,293 | C++ accessing vectors in classes | i am a beginner in C++ and my question is:
why my vector in a class is empty when i try to access that vector elements in another class after i added elements to that vector?
i have a class for example class1 and this class has a vector of type string and a member function which adds elements to the vector with push_b... | mlj is a new local object in the check method, and it contains no words. All your words were input in the main function and are stored in vkk. So you need to pass that object to check.
To do that, modify the method to receive a reference
void check(const abc & mlj)
{
string k;
cout << "Enter word to check: ";
... |
74,637,613 | 74,645,865 | Building C++ solution in VIsual Studio 2022 Community adds a JSON schema folder to project | Visual Studio 2022 Community version 17.4.2
Visual Studio recently updated and now whenever I build my solution a folder appears that contains a massive JSON Schema at [Solution Folder]/JSON/Schemas/Catalog/https%003A%002F%002Fgo.microsoft.com%002Ffwlink%002F%003Flinkid%003D835884 of 600 entries and over 4000 lines.
Th... | The value for Configuration Properties > C/C++ > SDLChecks was set to Yes even though the default value is already Yes.
In order to fix the issue:
Clean all configurations of the project via Build > Batch build... > Select All > Clean.
Delete the JSON folder.
Set the SDL checks value to <Inherit from parent or project... |
74,637,747 | 74,638,059 | Reduce Image bit C++ | How can I reduce the number of bits from 24 bits to a number between 0 and 8 bits and distribute the bits for the three colors Red, Green and Blue
Any idea ?
| This is called "Color Quantization". You have 16.777.216 colors and you want to map them to a smaller number (2 to 256).
Step 1: choose the colors you want to use. First their number, then the colors themselves. You need to chose if the colors are fixed for all images, or if they change based on the image (you will nee... |
74,638,562 | 74,678,141 | Convert vector<wchar_t> to string c++ | I'm trying to convert a vector<wchar_t> to string (and then print it).
std::string(vector_.begin(), vector_.end());
This code works fine, except äöü ÄÖÜ ß.
They will be converted to:
���
I also tried converting to wstring and printing with wcout, but I got the same issue.
Thanks in advance!
| My Solution:
First I convert my vector<wchar_t> to an utf16string like this:
std::u16string(buffer_.begin(), buffer_.end());
Then I use this function, I found somewhere on here:
std::string IO::Interface::UTF16_To_UTF8(std::u16string const& str) {
std::wstring_convert<std::codecvt_utf8_utf16<char16_t, 0x10ffff,
... |
74,639,286 | 74,639,530 | How to calculate float value and then convert to uint8_t? | How to calculate float value and then convert to uint8_t?
As below, the current progress is 50, but overall just 50% completed, the correct value is 25, but I got 0.
#include <iostream>
using namespace std;
int main()
{
uint8_t remaining = 1;
uint8_t total = 2;
uint8_t progress=50;
float value=0;
... | The (C-style) cast has higher precedence than multiplication, so your progress = (uint8_t)value*progress statement is evaluated as progress = ( (uint8_t)value ) * progress;. Thus, the 0.5 in value (from the previous line) will be truncated to zero.
You need to put the multiplication in parentheses. Also, try to avoid u... |
74,640,398 | 74,667,072 | Migrating a Visual Studio C++ Project to Linux and CMake | I'm currently trying to move from Windows 10 to Linux (Pop!_OS), but I'm having trouble getting my C++ Project to compile and run correctly on the latter. My C++ project was created using Visual Studio, where I also specified the include folders, library folders, what should be linked, etc in the solution properties. I... | I have found the problem that caused my errors. The problem wasn't with CMake, it was with Windows and Linux specific details. I always received errors like "<foo\foo.h> no such file or directory", which led me to think that CMake couldn't find the include directory or the files in it. The problem, however, is with the... |
74,640,655 | 74,640,824 | How Do I Combine 4 bit values to get a single integer | I spent hours trying to figure this out.
I have four binary values that I want to combine into a single number.
I got it working with two numbers but I need to get it working with four.
int Index = ((Bitplane0_ROW[p] & (1 << N)) >> N) | (((Bitplane1_ROW[p] & (1 << N)) >> N) << 1); // Works
I am stumped.
Thanks in adva... | You can shift the bits manually or just use std::bitset:
#include <bitset>
// ...
std::bitset<4> bs;
bs.set(0, (Bitplane0_ROW[p] >> N) & 1);
bs.set(1, (Bitplane1_ROW[p] >> N) & 1);
bs.set(2, (Bitplane2_ROW[p] >> N) & 1);
bs.set(3, (Bitplane3_ROW[p] >> N) & 1);
unsigned long index = bs.to_ulong();
|
74,641,369 | 74,641,674 | Crash a thread in a Win32 application | I have an application which implements crash handling and reporting using Google Crashpad and Sentry.
The application implements a watchdog which checks for freezes on critical threads, and aborts the application if it detects such a case.
However, when the "crash" gets reported to Sentry, the thread that "crashed" is,... | You can set the trap flag to cause an EXCEPTION_SINGLE_STEP.
CONTEXT context = { 0 };
context.ContextFlags = CONTEXT_ALL;
if (SuspendThread(hThread) == (DWORD)-1)
handleError();
if (!GetThreadContext(hThread, &context))
handleError();
context.EFlags |= 0x100; // set trap flag
if (!SetThreadContext(hThread, ... |
74,641,491 | 74,641,516 | How can I convert a std::string to std::vector? | I have some code which I need to serialize a vector into bytes, then send it to a server. Later on, the the server replies with bytes and I need to serialize it back into a vector.
I have managed to serialize into bytes okay, but converting back into a vector is getting the wrong values:
#include <iostream>
#include <s... | Like this
std::vector<double>((double*)str.data(), (double*)(str.data() + str.size()));
Basically the same as your code, but I've added some casts. In your version the chars get converted directly into doubles (as if you had written rV[0] = str[0] etc) and the vector is sizeof(double) times too big.
|
74,641,809 | 74,641,884 | Add the elements of a file into a class object | I have this file that contains a name cost unit and qty of items that I need to read from and put it into a class object I want each line in the file to be a its own object the file
This is the constructor for my class
Cost::Cost(string name, double cost, string unit, double qty) : Item(name, unit)
{
this->getName(... | Your bug is here
vector<string> itemStr;
vector<Cost> itemObj;
while (inFile)
{
while (getline(inFile, line))
{
std::stringstream stream(line);
while (getline(stream, word, delim))
{
itemStr.push_back(word);
}
it should be
vector<Cost> itemObj;
while (inFil... |
74,642,027 | 74,644,083 | Python C++ API make member private | I'm making a python extension module using my C++ code and I've made a struct that I use to pass my C++ variables. I want some of those variables to be inaccessible from the python level. How can I do that?
typedef struct {
PyObject_HEAD
std::string region;
std::string stream;
bool ... | You should do nothing. Unless you create an accessor property these attributes are already inaccessible from Python. Python cannot automatically see C/C++ struct members.
|
74,642,496 | 74,642,669 | constexpr initialization std::array of std::array | The following code does not compile
#include <array>
#include <iostream>
#include <utility>
template <std::size_t N>
class A {
template <std::size_t... Ints>
static constexpr void get_phi_base_impl(std::array<std::array<double, N>, N>& res, std::index_sequence<Ints...>)
{ ( (std::get<Ints>(res).fill(0), std::get... | In C++17, a constexpr function must not contain "a definition of a variable for which no initialization is performed".
This restriction is removed in C++20.
In C++17, you can make your 2D array (I assume it's meant to be an identity matrix) like so:
constexpr double identity_matrix_initializer(std::size_t x, std::size_... |
74,642,765 | 74,643,704 | C++ classes in Header Files | I am a real beginner in C++ and am having some major problems with my current task. The goal is to implement basic Complex arithmetic in C++, but all the videos/webistes I used to get in touch with this topic did not include a .hpp (Complex.hpp) that we need to use to run our tests. But adding the Complex{...} class to... | real takes an argument of type Complex. I think you meant
double Complex::real(){ return this->re; }
change the declaration accordingly too.
|
74,643,322 | 74,648,055 | If a C++ module partition B imports module partition A, is anything imported by partition A also visible in partition B? | In one module where I have partitions, I noticed that if a partition imports another partition, everything the second partition imports is also visible in the first partition. Is this correct behavior or a bug in the compiler?
I am using VS2022.
Lets say we have some module Foo:
// Foo.ixx
export module Foo;
export v... | [basic.scope.namespace]/2 spells out whether a name used in one TU is in scope of a TU that imports it. The short version is that foo is visible if Bar:Part2 imports Foo.
So... does it?
Yes.
When a module partition unit imports another partition (which must be of the same module, since you cannot import someone else's ... |
74,643,334 | 74,644,996 | Why loop starts with i = n/2 for doing heap sort? | I need to change max-heap code to min-heap code. I changed some parts, but when I print, I get only the min-heap array by order, not sorted.
#include <iostream>
#include <fstream>
#define MAX_TREE 100
using namespace std;
typedef struct {
int key;
}element;
element a[MAX_TREE];
void SWAP(element root, element t... |
Why for statement starts with i=n/2?
This is the part I don't understand
This loop:
for (i = n / 2; i > 0; i--) {
adjust(a, i, n);
}
... is the phase where the input array is made into a heap. The algorithm calls adjust for every internal node of the binary tree, starting with the "last" of those internal nodes,... |
74,643,474 | 74,646,156 | How can I use multiple filters on a single sink with boost::log | I'm using a sink to log information and a file with information on the different levels I want for each tag I created like so:
sink->set_filter(logging::trivial::severity >= logging::trivial::warning && expr::attr<std::string>("Tag") == tag);
[...]
sink->set_filter(logging::trivial::severity >= logging::trivial::warnin... | If your list of tags is known and fixed at compile time, you can compose a filter using template expressions like this:
sink->set_filter
(
(expr::attr<std::string>("Tag") == tag1 && logging::trivial::severity >= severity1) ||
(expr::attr<std::string>("Tag") == tag2 && logging::trivial::severity >= severity2) ||... |
74,643,731 | 74,644,303 | Finding the actual type (float, uint32_t...) based on the value of an enum (kFloat, kUint32...) | I am reading data from a file and the type of the data is stored as a uint8_t which indicates the type of data I am about to read. This is the enum corresponding to the declaration of these values.
enum DataType
{
kInt8,
kUint16,
kInt16,
kUint32,
kInt32,
kUint64,
kInt64,
kFloat16,
kF... | You're trying to take a runtime value and map it to a compile-time type. Since C++ is a compile-time typed language, there's no escaping that, at some point, you're going to have to do something like a switch/case statement at some point. This is because each option needs to have its own separate code.
So the desire is... |
74,644,036 | 74,644,104 | i want to print a matrix into an txt file using a display function | i want to output a matrix into a txt file using a display function ( i tried to do it without the displayDor function and still didn't work)
the error is in the last line inside the function enregistrer line 48
and its saying :
[Error] no match for 'operator<<' (operand types are 'std::ofstream {aka std::basic_ofstream... | Your displayLaby writes to std::cout, if you want it to write somewhere else (like a file) then you have to pass the stream as a parameter to the function. Like this
void displayLaby(const laby &labyr, ostream& os){
for(int i=0;i<labyr.p;i++){
for(int j=0;j<labyr.q;j++){
os<<'['<<labyr.tab[i][j]... |
74,644,259 | 74,644,667 | Make a library with cmake that use the SDL | I am trying to create a library on the top of SDL2. For the compilation I'm using cmake.
First I had this CMakeLists.txt for the library :
cmake_minimum_required(VERSION 3.10)
project(SquareEngine)
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake/")
find_package(SDL2 REQUIRED)
find_packa... | I think you need to add the SDL include dirs to the SquareEngine library:
target_include_directories(SquareEngine PUBLIC ${SDL2_INCLUDE_DIRS} ${SDL2_IMAGE_INCLUDE_DIRS})
|
74,644,403 | 74,644,557 | no match for ‘operator<<’ in C++ | I'm new to C++ and I am trying to reproduce the following code from pybeesgrid repo (https://github.com/berleon/pybeesgrid/blob/master/src/beesgrid.cpp)
namespace beesgrid {
std::string getLabelsAsString(const Grid::idarray_t & id_arr) {
std::stringstream ss;
for (size_t i = 0; i < id_arr.size(); i++) {
... | The problem is that you haven't overloaded operator<< for boost::logic::tribool.
To solve this replace std::stringstream& operator <<( std::stringstream &os,const id& id ); with
//----------------------------------------------------------vvvvvvvvvvvvvvvvvvvvv--->replaced id with boost::logic::tribool here in the second... |
74,645,916 | 74,646,740 | How do I read inputs from file in c++ | is there a way to read inputs from txt file
6
0 1 1
2 3 1
1 2 1
3 0 1
4 0 1
4 5 1
3 4 1
5 3 1
for the part
int V = 6;
Graph g(V);
g.insertEdge(0,1,1);
g.insertEdge(2,3,1);
g.insertEdge(1,2,1);
g.insertEdge(3,0,1);
g.insertEdge(4,0,1);
g.insertEdge(4,5,1);
g.inse... | Simply use std::ifstream to open the file, and then use operator>> to read the values from it (it will handle skipping all of the whitespace in between the values), eg:
#include <iostream>
#include <fstream>
using namespace std;
...
int main()
{
int V, u, v, w;
ifstream ifs("filename.txt");
if (!ifs.is_o... |
74,646,460 | 74,646,516 | lvalue required as left operand of assignment 2 | #include <iostream>
using namespace std;
int main()
{
int g1, m1, s1, g2, m2, s2, x, y, z;
cin >> g1 >> m1 >> s1 >> g2 >> m2 >> s2;
x=g1+g2;
y=m1+m2;
z=s1+s2;
if(m1+m2>59) x+1 && y=y-60;
if(s1+s2>59) y+1 && z=z-60;
cout << x << y << z;
}
I'm new to c++ and don't know how to fix it, can... | The problem is that assignment operator = has the lowest precedence in your expressions:
if(m1+m2>59) x+1 && y=y-60;
if(s1+s2>59) y+1 && z=z-60;
Thus, the compiler sees the expressions like this:
(x + 1 && y) = (y - 60);
(y + 1 && z) = (z - 60);
And the result of (x + 1 && y) and (y + 1 && z) cannot be assigned, be... |
74,646,548 | 74,653,172 | How do I use conio.h and dos.h with gcc? | I want to learn C++ and I using YouTube, but there in code are modules conio.h and dos.h. But GCC don't knows them. Which whit the same functions I can use? (Any from another questions about this don't solving my problem)
I tried remove conio.h from code, but in the code, I have functions from it. That same with dos.h.... | This code here is a mix of the Windows API and old MS DOS libraries for the Borland Turbo compilers from 1989. You should be studying neither if your goal is to learn C++. gcc/mingw only supports Windows, not MS DOS nor 30 year old Borland-specific libraries.
General advise:
Don't search for knowledge or wisdom on You... |
74,647,130 | 74,647,197 | Why this template class works, despite using std::less oddly | This code works:
#include <iostream>
constexpr static auto less = std::less{};
#include <string>
std::string a = "1";
std::string b = "1";
int main(){
std::cout << ( less( 6, 3 ) ? "Y" : "N" ) << '\n';
std::cout << ( less( a, b ) ? "Y" : "N" ) << '\n';
}
According en.cppreference.com, std::less is implemen... | Since C++14 std::less is declared as
template< class T = void >
struct less;
and it has a specialization for void that has an operator() with the form of
template< class T, class U>
constexpr auto operator()( T&& lhs, U&& rhs ) const
-> decltype(std::forward<T>(lhs) < std::forward<U>(rhs));
This operator() deduces ... |
74,647,306 | 74,647,467 | How to move an object from one vector to another, without destroying any? | I have a vector of objects that represent GPU resources. I ended up with a pretty dangerous scenario: the objects can only be safely created or destroyed in a specific thread, but another thread still needs to be able to move them around between vectors.
As a safeguard, I deleted their copy constructor, copy assignmen... | Two vectors do not share an allocation (except if one is move-constructed/-assigned from the other).
Therefore moving between vectors implies creating a new object in the new vector's allocation and destroying the one in the old allocation.
Only node-based containers offer an interface to reassign elements between cont... |
74,647,368 | 74,647,462 | How to go (in a random order) through all the elements of a 2D array with a specific state | I have a simple 2D array in C++ like this:
Cell field[57][57];
enum State {foo, bar, baz};
Where each Cell is defined as
typedef struct Cell_t{
enum State state;
int value;
float temperature;
}Cell;
My goal is to go through the field and do something with all the cells which have their state currently set... | You can put all the coordinates of foo cells in an std::vector and std::shuffle it. That's what I would do:
#include <random>
#include <algorithm>
int main() {
Cell field[57][57];
std::vector<std::pair<int, int>> cellsToVisit;
for (int i = 0; i < 57; i++) {
for (int j = 0; j < 57; j++) {
if (field[i][... |
74,647,547 | 74,647,713 | Determinant of a Matrix, C++ code troubleshooting | main.c
#include <stdio.h>
#include <string.h>
#include "matrix.h"
int main(){
//Prompt the user for the size of matrix to be calculated.
printf("Welcome to the matrix determinant calculator!\n\n");
printf("Please select the matrix size you would like to input: \n");
printf("\t (A): 2x2 matrix\n");
printf(... | There is something wrong with your includes. You are trying to include 'iostream' in a .c file, while iostream is only used for c++. In c, you can import <stdio.h>, which gives you access to the 'printf' function. You are also importing 'string.h', which you are not using in your program. You also forgot to include <st... |
74,647,845 | 74,648,132 | Need a way to check template type and if not in the range of allowed types then have compile time error in C++ | I need to have a template class where each object adds itself to a vector and based on the template type parameter(allowed only: string, int, float) add to the corresponding container. I need a way to have compile time checks for the type and based on the check add to the corresponding container and if the type is not ... | Use specialization and a helper function, e.g.
template<typename T>
struct myClass;
inline std::vector<myClass<int>*> intVec;
inline std::vector<myClass<float>*> floatVec;
inline std::vector<myClass<std::string>*> stringVec;
template<typename T>
void add(myClass<T>*);
template<>
void add(myClass<int>* p) {
intVe... |
74,648,931 | 74,648,951 | Case statement saying it appeared before | I have these 2 case statements:
case SDLK_w && SDLK_a:
{
ball.posX -= mers;
ball.posY -= mers;
break;
}
case SDLK_w && SDLK_d:
{
ball.posX += mers;
ball.posY -= mers;
break;
}
The second SDLK_w gives me an error saying:
case label value has already appeared in this switch
It may be because c... | SDLK_w && SDLK_a is another way of writing 1 because they are both true.
SDLK_w && SDLK_d is also another way of writing 1.
Perhaps you meant this
case SDLK_w:
case SDLK_a: // two case statements in a row: both of them run the same code
{
ball.posX -= mers;
ball.posY -= mers;
break;
}
case SDLK_w:
case SDL... |
74,649,350 | 74,649,730 | Separate a float into 4 uint8_ts and then merge back together | I'm working on developing both the client(C) and server(C++) side of an RF connection. I need to send a float value, but the way the architecture is set up I have to arrange my message in a struct that limits me to 3 uint8t parameters: p0, p1, p2. My solution was to break the float into an array of 4 uint8_ts and send... | Unions are a very convenient way to disassemble a float into individual bytes and later put the bytes back together again. Here's some example code showing how you can do it:
#include <stdio.h>
#include <stdint.h>
typedef union {
uint8_t _asBytes[4];
float _asFloat;
} FloatBytesConverter;
int main(int argc, ... |
74,649,528 | 74,649,645 | Coroutines: Do co_yielded string_views dangle? | I want to mix up the co_yielding string literals and std::strings
Generator<std::string_view> range(int first, const int last) {
while (first < last) {
char ch = first++;
co_yield " | ";
co_yield std::string{ch, ch, ch};
}
}
However, I'm wondering about the lifetime of the std::string?
... | co_yield is a fancy form of co_await. Both of these are expressions. And therefore, they follow the rules of expressions. Temporaries manifested as part of the evaluation of the expression will continue to exist until the completion of the entire expression.
co_await expressions do not complete until after the coroutin... |
74,651,333 | 74,659,581 | Vulkan Validation Layers Not Available | I'm new to Vulkan, and I've been following vulkan-tutorial.com which has been a great resource so far.
However, one weird thing I've come to realize is that validation layers are supported on my device, but cannot be used without being overridden in vkconfig.
Following the tutorial, this is my C++ code at the moment:
a... | Your setting for VK_LAYER_PATH does not look right. The setup script should set a "layer path" environment variable for you and so you could try not exporting VK_LAYER_PATH after running the setup script. And if you were to set VK_LAYER_PATH, it should be something like $VULKAN_SDK/etc/vulkan/explicit_layer.d.
Note t... |
74,651,380 | 74,651,491 | Utilizing large data in a class that is instanated multiple times | I have the following class:
#include <map>
using namespace std;
class A {
const map<A, B> AToB = ;//... big data chunk
const map<A, C> AToC = ;//... big data chunk
B AsBType() {
return AToB.at(data);
}
//... same for AsCType, etc
Data data;
}
I'm currently concerned with how ... | When you want a single object shared by all instances of a class, make it a static data member:
class A {
static const map<A, B> AToB = ;//... big data chunk
static const map<A, C> AToC = ;//... big data chunk
//...
};
|
74,651,912 | 74,652,057 | Error C4430 missing type specifier - int assumed. C++ does not support default-int | I'm getting an missing type specifier error for line 12 ( inline CUserCmd*cmd = nullptr;) for this code and all the answers i can find are about functions but this is an inline variable so I'm rather confused.
#pragma once
#include "../core/interfaces.h"
class CEntity;
namespace globals
{
inline CEntity* localPlay... | You haven't provided a complete program, but I suspect that's part of the problem.
The two errors you mention both point to the compiler being unable to find a definition for CUserCmd.
If that's included in a header, make sure you #include it.
|
74,652,016 | 74,652,647 | How to use uiohook library in CMake project? | I am trying to install the following C library:
https://github.com/kwhat/libuiohook
I did the described steps which seem to work with no error.
$ git clone https://github.com/kwhat/libuiohook
$ cd uiohook
$ mkdir build && cd build
$ cmake -S .. -D BUILD_SHARED_LIBS=ON -D BUILD_DEMO=ON -DCMAKE_INSTALL_PREFIX=../dist
$ c... | As the library provides a uiohook-config.cmake you should use that to link to the library via find_package rather than using find_library.
Something like this should work:
set(CMAKE_PREFIX_PATH /Users/ahoehne/libuiohook/dist/lib/cmake/uiohook/)
find_package(uiohook REQURIED)
target_link_libraries(libuihook_test uiohook... |
74,652,242 | 74,652,495 | std::function argument to receives any number of arguments | I've defined a template function that receives std::function. and I want to send a member function. that works fine (example: test2)
How can I rewrite it so std::function receives any number of argument? (test3)
another question - can this be done without the std::bind?
struct Cls
{
int foo() { return 11; }
};
tem... | The issue is that std::bind doesn't return a std::function, it returns some unspecified callable type. Therefore the compiler can't deduce the correct template parameters for test3.
The way to work around that is to make your function accept any callable type instead of trying to accept a std::function:
template <type... |
74,652,634 | 74,652,741 | how to sort a vector of string and integer pairs by the second key value which is integer? | I have a vector storing the most frequent words in a file. Initially the values was stored in a map of strings and integers but then I copied the map into the vector I thought it would be easier to sort. Then I realized that the std sort() function sorts the vector by the first key (string in this case). But I want to ... | First of all, as mentioned in a comment, this is too complicated:
if(list.find(word) != list.end()){
list[word]++;
}
else{
list[word] = 1;
}
It looks up the key word twice, when it has to be looked up only once, because this does the same:
list[word]++;
operator[] already does add a default constructed element... |
74,652,952 | 74,653,283 | Alias within a class template | For following class
template<typename T>
class test {
public:
using unit = std::micro;
};
How do I access unit like test::unit without having to specify the template argument or make it a template alias. Please note that inserting a dummy template argument like e.g . int is not an option since some template... | First, it is important to understand that really everything in the template depends on the template parameter T. Even if it looks like it does not on first sight.
Consider that there can be a specialization:
template <>
struct foo< bar > {};
Now there is a foo instantiation that has no member alias. And thats the reas... |
74,654,454 | 74,654,631 | Change the comparator for a map that is defined by a variadic template | I have the following piece of code,
// Type your code here, or load an example.
#include <string>
#include <map>
#include <iostream>
struct alpha{
alpha() = default;
alpha(std::string str, int i ) : mystr(str), num(i){}
std::string mystr{"abc"};
int num{0};
bool operator <( const alpha &al ) const
... | Type of the custom comparator must be passed to std::map as the third argument, you can actually use the variadic label_str to your advantage there:
struct num_comparator {
template <typename T>
bool operator()(const T &l, const T &r) const {
return (l.num < r.num);
}
};
struct Label_map {
label... |
74,654,566 | 74,654,619 | Prime number between N and M | So I was trying to get the prime number between two numbers, it works fine but it also prints out odd numbers
int prime(int num1, int num2)
{
int sum{0};
while (num1 <= num2)
{
for (int i = 1; i <= num1; i++)
{
if (num1 % i == 0) //remainder needs to be zero
{
... | This if statement
if (i * num1 == num1 && num1 / i == num1)
{//make sure it only prints prime numbers
cout << num1 << endl;
sum += num1;
}
is always evaluated for any number when i is equal to 1.
So the code has a logical error.
At least there is no sense to start the for loop
for (int i = 1; i <= num1; i++)
... |
74,655,092 | 74,655,349 | Function that returns templated object with any template argument type | I have a templated class, say:
template <class C, int I>
class A {
A() {};
someMethod(){...};
};
Now, let's say I have several objects of this class used in my code with different template parameters (classes B,C, and D are some defined classes):
A<B, 1> object1;
A<C, 2> object2;
A<D, 3> object3;
What I would... | This is simpler to reason about if you think of A<B,1>, A<B,2> and A<B,3> as three completely unrelated classes Foo, Bar and Moo, which they bascially are. Now try to find a way to return those from a single method: You need a common base or any or variant ... runtime polymorphism: The same method returns an object and... |
74,655,645 | 74,656,882 | Multiple inheritance ambiguities with minimal code clutter | I have two interfaces: IFace2 derives from IFace
class IFace
{
public:
virtual ~IFace() = default;
virtual void doit() = 0;
};
class IFace2 : public IFace
{
public:
virtual void doit2() = 0;
};
I am trying reduce code clutter that is required by the implementations. In IFace2Impl I would like to use the ... | Virtual inheriance might help, so IFaceImpl would have only one IFace instead of 2:
class IFace
{
public:
virtual ~IFace() = default;
virtual void doit() = 0;
};
class IFace2 : public virtual IFace
{
public:
virtual void doit2() = 0;
};
class IFaceImpl : public virtual IFace
{
public:
void doit() ove... |
74,655,881 | 74,656,562 | OpenGL Camera Rotation with glm | I'm trying to rotate camera but instead it rotates and changes position.
float m_CameraRotation = 30.0f;
TShader.Bind();
glm::mat4 proj = glm::ortho(0.0f, 1000.0f, 0.0f, 1000.0f, -1.0f, 1.0f);
glm::mat4 view = glm::translate(glm::mat4(1.0f), glm::vec3(0, 0, 0));
glm::mat4 vp = proj * view;
glm::mat4 transform = glm... | Since your translations don't do anything, the only transformations applied to the triangle's vertices are the rotation first and the orthographic projection second. The rotation axis being +z, it will rotate everything in the xy plane around the origin by m_CameraRotation degrees counterclockwise.
Your triangle isn't ... |
74,656,665 | 74,656,698 | Is there a conversion from pointer to array? | For example, for the following code, I know that p is a pointer, which points to the first element of the array arr, and I also know that the array will degenerate into an array under certain conditions, but why can the [] operation be performed on the pointer here?
#include<iostream>
using namespace std;
int main()
{
... | From the C++ 20 Standard (7.6.1.2 Subscripting)
1 A postfix expression followed by an expression in square brackets is
a postfix expression. One of the expressions shall be a glvalue of
type “array of T” or a prvalue of type “pointer to T” and the other
shall be a prvalue of unscoped enumeration or integral type. The
... |
74,656,830 | 74,666,483 | set vcpkg x-buildtrees-root option in manifest or in cmakepresets.json | I've a CMake project that uses vcpkg.json for using vcpkg, and CMakePresets.json for setting the CMake options.
This is the vcpkg.json:
{
"name": "myproj",
"version": "1.0.0",
"dependencies": [
"boost",
"qt"
]
}
This is the CMakePresets.json:
{
"version": 3,
"cmakeMinimumRequired": {
"major": 3... | The variable VCPKG_INSTALL_OPTIONS is meant for passing further options to vcpkg install. So just set it in your preset.
|
74,657,257 | 74,657,501 | C++ unordered set of custom class - segfault on insert | I am following a tutorial on creating a hexagon map for a game. The source has it in struct, but I want it to be a class and so far I am unable to make it work. It compiles fine, but when I try to insert a new value in it, it segfaults. I am probably doing the hash function wrong, or something, but I have ran out of id... | If you run your program under a debugger, you will see it actually overflowed the stack while trying to construct HexagonField objects.
This is because every object has a vector of 6 more HexagonField objects, which in turn needs another vector, and so on.
As a quick fix, you can take hexagonDirections out of the Hexag... |
74,657,605 | 74,658,314 | What mechanism can I use for an optional function parameter that gets a value assigned if not provided? | In Python I can do something like:
def add_postfix(name: str, postfix: str = None):
if base is None:
postfix = some_computation_based_on_name(name)
return name + postfix
So I have an optional parameter which, if not provided, gets assigned a value. Notice that I don't have a constant default for postfix. It ne... | One possibility is to use a std::string const* (a non-constant pointer to a const std::string) as a function argument.
std::string add_postfix(const std::string& name, std::string const* postfix = nullptr)
{
std::string derivedSuffix;
if(!postfix)
{
derivedSuffix = some_computation(name);
postfix = &d... |
74,659,156 | 74,659,822 | Is there a way to use a using-declaration inside a requires-expression | I want to test whether a type can be passed to some function, but I'd like to use ADL on the function lookup and include a function from a certain namespace.
Consider this code:
#include <utility>
#include <vector>
template<class T>
concept Swappable = requires(T& a, T& b)
{
swap(a,b);
};
static_assert(Swappable<... | You can put it inside a lambda:
template<class T>
concept Swappable = []{
using std::swap;
return requires(T& a, T& b) { swap(a, b); };
}();
|
74,660,389 | 74,668,554 | Freetype2 not linking on Windows correctly | I've been fighting freetype2 for a week trying to get it to work on Windows 32 bit but it just won't. My CMakeLists.txt is as follows:
cmake_minimum_required(VERSION 3.0.0)
set(CMAKE_CXX_STANDARD 17)
project(template-project) # change the name here
file(GLOB_RECURSE SOURCE_FILES src/*.cpp)
add_library(${PROJECT_NAME}... | I recommend a different approach than manual downloading of opensource dependencies when using MinGW. Instead of searching for individual binary downloads switch to use msys2 to install MinGW and use the package management of msys2 to all of your dependent open source libraries.
The first step is to remove your current... |
74,660,413 | 74,660,518 | Multiplication Table Based On BOTH User Inputs | I am trying to create a multiplication table that is based on BOTH user inputs. I want to ask the user the first and second integer and then to print out the first integer by the second integer that amount of times.
For example, if I choose 5 for first integer and 10 for second integer, I want the results printed as su... | You don't see the numbers being outputted because your inner for loop is never entered, as b (which has the value of multiply2Number) can never be less than multiply2Number.
Do you want the second number to be the number of entries to display, starting at x 1 and progressing sequentially? If so, then try something lik... |
74,660,477 | 74,660,637 | How to use a library created using Bazel | I'm relatively new to Cpp and I was trying to build a simple app for a quant project. I've managed to use Bazel to convert a chunk of my code to a library residing in the bazel-bin directory in my repository as a .lib file.
However, I'm not able to figure out how to use this library in my main.cpp which is outside the ... | I'm not sure if I understood your question correctly, but I think, there is a .lib file that you want to use it (technically speaking, you need to link that .lib file to another app, or accessing in the main.cpp).
Ok, it depends on what build-system you use.
for MSVC:
Add the full path of the .lib file to Project Prope... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.