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,797,532 | 71,798,153 | How do i use deduction to choose the return type of function | I have a question regarding the full deduction with functions using C++11 standard. Basically I am ought to make a function that takes a single parameter that should look like a matrix (basically any container) whose elements can again be any container but having in mind that elements of every row do not necessarily ne... | I am still not sure if I understood what you want to do. I will concentrate on the actual question: How to infer the value type from a 2D container when the container can be made of standard containers or C arrays?
You can use a type trait. Standard containers have a value_type member alias. When an 2d array is passed ... |
71,797,625 | 71,798,145 | Why does the implementation of std::any use a function pointer + function op codes, instead of a pointer to a virtual table + virtual calls? | Both the GCC and LLVM implementations of std::any store a function pointer in the any object and call that function with an Op/Action argument to perform different operations. Here is an example of that function from LLVM:
static void* __handle(_Action __act, any const * __this,
any * __other,... | Consider a typical use case of a std::any: You pass it around in your code, move it dozens of times, store it in a data structure and fetch it again later. In particular, you'll likely return it from functions a lot.
As it is now, the pointer to the single "do everything" function is stored right next to the data in th... |
71,798,193 | 71,798,791 | C# Passing array with specific array index | I want to pass an array to a function with specific index in C#, like we do in C++, something like below:
void foo(int* B) {
// do something;
}
int main() {
int A[10];
foo(A + 3);
}
In this case suppose A starts with base address 1000, then B would be 1000+(sizeof(int)*3). The answer in this link uses Skip() function... | This has been answered here:
C# Array slice without copy
You can use ArraySegment or Span to achieve this
public static void Main()
{
int[] arr1 = new int[] {2, 5, 8, 10, 12};
int[] arr2 = new int[] {10, 20, 30, 40};
DoSomethingWithSegmentReference(new ArraySegment<int>(arr1, 2, arr1.Length - 2));
... |
71,799,353 | 71,800,196 | c++ Empty template function returns non-empty function pointer | I am confused by the function pointer of the template function.
See
#include <cstdio>
class A
{
public:
A(){}
~A(){}
void command()
{
printf("Cmd");
}
};
template<class T>
void cmd_create()
{
T t;
t.command();
};
int main()
{
typedef void(*Funcpt... |
Obviously, &cmd_create returns the A::command.
I am not fluent with assembly, but obviously you misunderstand the code ;).
&cmd_create<A> is a pointer to the function cmd_create<A>. This function pointer is assigned to f1. The pointer is of type void(*)(), pointer to function returning void and no arguments. No funct... |
71,799,459 | 71,799,996 | Undefined reference to cv::Mat::Mat() | I made a simple c++ code that reads the webcam image and display it. However, when I compile, I get the error - 'Undefined reference to cv::Mat::Mat()'. I don't know why it shows two Mat's. Here is my code:
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
#include <stdlib.h>
int main() {
cv::Vid... | This works on my Linux:
g++ main.cpp -I/usr/include/opencv4/ -lopencv_core -lopencv_videoio -lopencv_highgui
While this is not portable, (using cmake would do the trick, but you'd need to learn cmake first), I'll give you a hint how you can discover this yourself.
Whenever you see an error like Undefined reference to ... |
71,800,789 | 71,801,848 | extern "C" for functions loaded with dlsym | In a C++ project I am loading a .so with dlopen and dlsym. The .so is compiled from C source and all functions have C linkages.
The only part I am not able to figure out is how do I cast the resulting pointer to an extern "C" function so that the actual call site uses the appropriate linkage.
I know one of the main dif... | Introduce a typedef first:
extern "C" typedef void (*verb)();
void f() {
const auto foo=(verb)dlsym(handle, "foo");
}
|
71,801,300 | 71,801,971 | How to store different class objects in a single array/vector? | The program I'm writing requires me to implement a certain code so that every class instance that is stored in vectors is accessible within a single array or vector. The problem is that the instances belong to different classes and cannot be stored in a single array/vector by itself. Is there any way that this is possi... |
vector <A*> mainvec = { vecb, vecc, vecd, vece };
This can never work. mainvec expects to hold raw A* pointers, but you are trying to pass it vectors of objects instead.
If you really want a vector to hold other types of vectors, you could use std::variant for that, eg:
std::vector<B> vecb;
std::vector<C> vecc;
std:... |
71,802,055 | 71,802,129 | Converting enum type to a specific, predefined array of hex values in C++ | What would be the most optimal and shortest way to write a function returning an array of 8-bit hex values, which are assigned based on an enumerated parameter.
I need to hard code commands, which will be sent over bluetooth and still have an easy access to them in code. So I have an enum with all possible commands lis... | I would suggest using and returning a std::array. That would change your function to
std::array<uint8_t, 4> getCommandOf(eventType event) {
switch(event) {
case eventType::MODIFY_A:
return {0x01, 0x00, 0x00, 0x00};
case eventType::MODIFY_B:
return {0x02, 0x00, 0x00, 0x00};
... |
71,802,355 | 71,802,541 | Possible ways to compress Apache Arrow RecordBatch? | I am working on C++ and trying to reduce network traffic of Flight RPC by compressing the RecordBatch object.
What's the best way to make a RecordBatch compact? I found that RecordBatch consists of Array. Is it good to directly compress ArrayData?
| With the caveat that in my own testing, I've never found compression to help substantially, Arrow already supports compression and this can be enabled (with some finagling) by setting IPC options.
For example, if you have a DoGet, pass an IpcWriteOptions with compression enabled to RecordBatchStream. Then Arrow/Flight ... |
71,804,840 | 71,804,851 | if (counter ) is the same as If (counter !=0)? | I'm learning c++, and I wanted to know whether the statement
"if(counter)" is the same as "if (counter!=0)"
| If counter is a built-in primitive type (int, double, pointers), yes, it means the same thing. If it's not a primitive type, they could mean completely different things (whatever operator bool and the comparator defined for comparing with something implicitly convertable from int happen to return).
|
71,805,241 | 71,805,315 | What is this member pointer syntax? | #include <iostream>
#include <type_traits>
struct Foo
{
// ### Member Function ###
void bar() { std::cout << "Foo::bar()\n"; }
};
// ### 1 Parameter Primary Template (which is empty) ###
template<typename>
struct Traits {};
// ### 2 Parameter Template Specialization ###
template<class T, class U>
struct Trai... |
struct Trait<T U::*>
^^^^^^ // I don't understand this syntax
The above syntax means that we've a pointer to a member of a class named U where the member has type T. In other words, a pointer to a member of class U that has type T.
Now let's apply this to &Foo::bar. The type of the expression &Foo::bar ... |
71,805,335 | 71,950,774 | How to make an overload for templated functions for a custom container's iterator | This is a generic question about templating, I am using advance as an example. Assume there are reasons I can't use ADL or hidden friends here.
The definition of std::advance is:
template< class InputIt, class Distance >
constexpr void advance( InputIt& it, Distance n );
For the sake of argument, say I have a containe... | A friend of mine came up with a solution based on tags (empty structs).
Basically, put a unique empty struct in the iterator class then build a C++20 concept using it, then use that to match in the template overload:
template <typename T, class A = std::allocator<T>>
class H
{
// etc
public:
cla... |
71,806,191 | 71,806,283 | How to create an object in a form like this: ifstream in(); | Im beginner in c++. I have seen several times when object created like:
class_name object_name();
and after that you can refer to object_name as an object of the class.
How can i do this in my class? Should I override the constructor? And how to do that?
| This line of code can probably trigger a vexing (but not "the most vexing") parse behavior: instead of being interpreted as a variable declaration, it will be interpreted as the declaration of a function named object_name, taking no parameters and returning a value of type class_name.
See it happen on GodBolt: The comp... |
71,806,505 | 71,839,110 | Temporary initialization and Reference initialization | I am trying to understand how reference initialization. For example, let's look at a typical example.
double val = 4.55;
const int &ref = val;
I can think of 2 possibilities of what is happening in the above snippet.
Possibility 1
The usual explanation is given as follows:
Here a temporary(prvalue) of type int with va... | Lets look at each of the cases(C++11 vs C++17) separately.
C++11
From decl.init.ref 5.2.2:
Otherwise, a temporary of type “ cv1 T1” is created and initialized from the initializer expression using the rules for a non-reference copy-initialization ([dcl.init]). The reference is then bound to the temporary.
One more im... |
71,806,538 | 71,806,653 | Assets path with SDL2 library | I'm trying to load image with IMG_Load() function from SDL.
I saw from tutorials that they doesn't need full path for asset files.
But when I try to do that, it doesn't work.
My solution is include full path of those files, but I found that is clunky. Especially when I try to collaborate with my friend, it's hard to sy... | Relative paths are relative to the current working directory. On Windows, when starting a program from the exporer with a double-click, it matches the location of the .exe, but this isn't always the case, e.g. when running from some IDEs.
Use SDL_GetBasePath() to get the directory where the .exe is located. Prepend it ... |
71,806,631 | 71,807,176 | How to call an operator with constexpr without using temporary variables? | The following sample code illustrates my problem.
constexpr int fact(int N) {
return N ? N * fact(N - 1) : 1;
}
struct A {
int d;
constexpr A operator+(const A& other) const { return A{ fact(d + other.d) }; }
// overload of many other operators
};
int main() {
int x;
cin >> x; ... | You can force the evaluation with (non-type) template parameter or consteval function.
constexpr int fact(int N) {
return N ? N * fact(N - 1) : 1;
}
struct A {
int d;
constexpr A operator+(const A& other) const { return A{ fact(d + other.d) }; }
};
consteval auto value(auto v){return v;}
A foo (int x) {
... |
71,806,990 | 71,807,924 | How to build many different packages with CMake | I'm trying to put together a CMake project where I have different packages that I need to build. This is my desired structure:
package1
src
file.cpp
test
file_test.cpp
package2
src
file2.cpp
test
file2_test.cpp
CMakeLists.txt
main.cpp // this will be removed later
This is my current CMakeLists.... |
So the question is firstly, is a library considered a package in
CMake? This question comes from someone who have done a lot of Java
where I would typically call that a package and not a library. But
does it in CMake?
Your definition of package in Java is not quite accurate. Package is just a mean to organize classes... |
71,807,071 | 71,807,089 | Working with adress of a pointer in a function | I have a function which receives an address of a pointer to an array, I want the function to iterate that array, how exactly should I write the function's code?
example of the function, and the function's call:
int example(int** arr, int n){}
k = example(&arr, n);
Using *arr, gives me the address of the first object... | Just treat *arr as an array
int *array = *arr;
for(int i = 0; i < n; i++)
{
// do something with array[i];
}
|
71,807,104 | 71,807,299 | Does std::memory_order_release and std::memory_order_acquire only guarantee the relative order within the current code block? | My gut feeling is this is a stupid question, as no one has ever asked it. But I am still a bit obsessed with it.
I understand that a std::memory_order_release operation guarantees that all writes prior to it can be seen by another thread when that thread has loaded the atomic variable with std::memory_order_acquire.
My... | Yes, the effect of release covers everything thread 1 did before, not limited to the code block.
It can even cover things done by different threads, if they had synchronized with thread 1 before.
what's the exact definition of "prior to"?
The standard calls this happens-before. It has a rather obscure definition, but... |
71,807,220 | 72,236,108 | How to Upscale window or renderer in sdl2 for pixelated look? | I want this pixelated look in sdl2 for all the object in my screen
| To do this, the nearest scaling must be set (default in SDL2), which does not use antialiasing. If so, you can use SDL_SetHint by setting hint SDL_HINT_RENDER_SCALE_QUALITY to nearest (or 0). If you now render a small texture in a large enough area (much larger than the texture size), you will see large pixels in the w... |
71,807,239 | 71,807,266 | If statement inside of a for cycle | first of all, sorry if my title isn't appropriate. English isn't my first language so I didn't really know how to phrase it correctly and understandably.
So, I'm learning some C++ and I got stuck on a problem. Right now my code looks like this:
#include <iostream>
using namespace std;
int main()
{
int start, fini... | You should
create a flag that indicates if any j that divides i.
after the loop, check the flag and print the message if applicable.
#include <iostream>
using namespace std;
int main()
{
int start, finish;
cout << "Enter range start" << endl;
cin >> start;
cout << "Enter the range end" << endl;
... |
71,807,340 | 71,807,425 | use template fold expressions instead of recursive instantions of a function template? | Given a variadic parameter pack, I would like to call a function with each element and its index in the pack.
I have a simple example below which uses recursive instantiations of a function template to achieve this. (on godbolt)
#include <iostream>
#include <tuple>
template<std::size_t I, typename Tuple>
void foo(Tupl... | It could be:
template<size_t ... Indices, typename... Ts>
void bar2(std::index_sequence<Indices...>, Ts&&... ts) {
auto action = [](size_t idx, auto&& arg) { std::cout << "item " << idx << "=" << arg << std::endl; };
(action(Indices,std::forward<Ts>(ts)),...);
}
template<typename... Ts>
void bar2(Ts&&... ts) {... |
71,807,343 | 71,811,321 | Sending c++ byte data using ffi to flutter | I used this code in this link to take a screenshot of the screen using GdiPlus and convert the bitmap to png bytes.
#include <iostream>
#include <fstream>
#include <vector>
#include <Windows.h>
#include <gdiplus.h>
bool save_png_memory(HBITMAP hbitmap, std::vector<BYTE>& data)
{
Gdiplus::Bitmap bmp(hbitmap, nullpt... | The data type you are looking for on the Dart side is Pointer<Uint8>, which is a pointer to unsigned bytes. You can pass this pointer over the ffi boundary and access the pointee bytes on either side. But, pointer is no good to you until you allocate some storage (think malloc / free).
There are two ways to allocate th... |
71,807,413 | 71,808,253 | Find shift of cyclic permutation of two sequences | I need to find shift of two cyclic permutations of sequences.
EXAMPLE:
3 5 1 2 4 3 5 7 8 1 2 5 9 4 7
5 7 8 1 2 5 9 4 7 3 5 1 2 4 3
Second sequence is cyclic permutaion of first with shift 6.
My algorithm:
if sequences are equal return 0 as shift
if they are not equal, sort them and then check if they have same element... | Your design is wrong.
It seems that you simply want to rotate elements in a std::vector.
The exception is because of an out of bounds error: help.push_back(b.at(i + 1));
There is a strange handling with "help" and "temp". You first create "help" and "temp" with n 0es in it. Then you push back stuff, but only 2 elements... |
71,807,588 | 71,807,589 | Avoid object destruction when initializing in local scope, C++ | I am working on a networking project and I need to initialize an object in a try-catch block. I want the object, which represents a socket, to close the socket upon destruction, but I must avoid closing a socket before using it. A socket is represented with something as simple as an integer value which is why closing i... | I thought of this just when I was finishing typing up the question. Use move-assignment.
Take the original code and add the following method to the class definition:
Foo & operator=(Foo && other) {
swap(v, other.v);
return *this;
}
This way, when constructing an object only to assign it to some other object, t... |
71,807,861 | 71,808,018 | Is it ok to call std::basic_string::find on already moved string? | According to std::move, a moved std::string is in a "valid but unspecified state", which means that functions without preconditions can be used on the string. Is it ok to use std::basic_string::find on the unspecified string? Does std::basic_string:find have any precondition?
#include <string>
int main() {
std::strin... | According to the description of std::basic_string:find in [string.find]:
constexpr size_type F(const charT* s, size_type pos) const;
has effects equivalent to:
return F(basic_string_view<charT, traits>(s), pos);
which has the following effects
Effects: Let G be the name of the function. Equivalent to:
basic_string... |
71,807,962 | 71,808,297 | Accept pointer/iterator in generic function | I need to make a generic function which will allocate an array that has same elements as vector in the main function.
This generic function should accept pointers/iterators to the beginning and end of the vector.
#include <iostream>
#include <new>
#include <vector>
template <typename type>
type *MakeArray(type::iterat... | You can use the iterator type itself as the template arguments and then extract the underlying type of the contained elements in the function.
Also, you shouldn't be using delete[] arr; in your function because: (a) at that point, it no longer points to the memory allocated by the new call; (b) if you do, you won't be ... |
71,808,092 | 71,808,302 | What is the difference between qualified and unqualified name lookup when deducting templates? | While writing template methods, i ran into the folowing behavior, which i do not understand.
I have the folowing code:
#include <array>
#include <iostream>
namespace A
{
template<typename T>
class Bar
{
T Var;
};
}
namespace B
{
template<typename T>
void Foo(const T& var)
{
... |
It's output is not what i expect as with the array of Bar, the default template is called instead of the Bar overload
For the call expression, B::Foo(ArrayBar), the 2nd overload void Foo(const std::array<T,N>& var) is chosen with N deduced to 1 and T deduced to A::Bar<int>.
Now inside that overload, when the call exp... |
71,808,797 | 71,828,529 | How to create global object with static methods in v8 engine? | I want to have the same object as JSON in my embedded v8. So I can have several static methods and use it like this:
MyGlobalObject.methodOne();
MyGlobalObject.methodTwo();
I know how to use Function template for the global function but I can not find any example for global object with static methods.
| In short: use ObjectTemplates, just like for the global object you're setting up.
There are several examples of this in V8's d8 shell. The relevant excerpts are:
Local<ObjectTemplate> global_template = ObjectTemplate::New(isolate);
Local<ObjectTemplate> d8_template = ObjectTemplate::New(isolate);
Local<ObjectTemplate> ... |
71,808,851 | 71,808,933 | Segmentation Fault during delete [] | I am building a game and I need to store in a dynamic array a player, every time that a player is created. I built a small piece of code to try it and I get a segmentation fault when I try to delete the table to insert the third player. I just can't realize why that happens: the header file is:
#include <iostream>... | The problem stems from here:
memcpy(newArr, PlayerList, NPlayers * sizeof(Player));
You cannot copy classes in this manner, unless they are Trivially Copyable (originally said POD, but as Yksisarvinen points out in the comments, memcpy is not quite that restrictive). You can fix this by using a loop to copy over the d... |
71,809,066 | 71,850,136 | C++ app - how to stop/cleanup if it is run as Linux service? | I have basically a console C++ app for Linux CentOS9. I am going to run it as a service using systemctl start/stop.
Currently the app exits if user press Enter in the console but this wont be possible in service mode as the user wont see the app console after logging in.
What can be done so I the app can detect it is b... | It seems systemctl stop sends SIGTERM.
Just register callback for it
void signal_callback()
{
printf("Process is going down\n");
}
signal(SIGTERM, signal_callback)
How systemd stop command actually works
|
71,809,322 | 71,809,441 | how to find the biggest multiplication between numbers in a given array(limit is 100000 numbers) | I am trying to learn programming and in our school we have exercises which are automatically checked by a bot. The time limit is 1 second and the memory limit is 1024 mb.
I've tried sorting the array in an ascending order and then multiplicating the 2 highest numbers but that was too slow(my sorting algorithm could be ... | You don't need to sort the entire array - you just need the two largest positive numbers and the two smallest negative numbers. Everything in between is inconsequential.
Instead, you can go over all the input and keep track of the two largest positive numbers and two smallest negative numbers.; At the end of the iterat... |
71,809,520 | 71,809,600 | The division operation of overloaded function operators leads to the change of divisor | when I build a class named "Money", I overloaded the "/" sign in the class. But the divisor changed during the division operation. As shown below:
(1.This is the declaration of overloaded function operators in the header file)
Money& operator/(double);
void division(double);
(2.This is the specific definition of over... | Problem:
In Money::division you're modifying the object through the statement money_number = money_number / i;, which assigns a new value to money_number.
Solution:
Create a copy of the object in the division and return that instead.
Code:
Money Money::operator/(double i)
{
Money temp = money_number / i;
return... |
71,809,559 | 71,809,743 | How does variable allocation works in C++? | I have this in the main.cpp body (how is it called? global?)
ofstream s;
...
int main ... {
s = ofstream("somefile.txt");
...
then another thread uses it once a day to rollover:
s.close();
// do I need to cleanup in between?
s = ofstream("anotherone.txt");
do I need to cleanup before creating new stream?
| close() is a member function defined in the class ofstream. It's not a destructor; it's not special in any way which fundamentally matters to the rules of the C++ language. For that matter, s = ofstream("anotherone.txt") is actually just another way to spell the line of code s.assignment_operator(ofstream("anotherone.t... |
71,809,592 | 71,809,817 | How can I create a priority queue that stores pairs in ascending order? | I need to create a queue that stores pairs of integers in ascending order by their first value.
Say I have the following queue:
0 10
0 10
1 10
2 10
30 10
If I try to create a priority queue with these values, it's just going to store the pairs by descending order, starting with 30 all the way to 0.
Is there a way t... | For priority_queue, the largest element is at the front of the queue.
Note that the Compare parameter is defined such that it returns true if its first argument comes before its second argument in a weak ordering. But because the priority queue outputs largest elements first, the elements that "come before" are actual... |
71,809,730 | 71,809,796 | What is difference between these two pieces of code when we do operator overloading? | Code 1:
class CVector {
public:
int x, y;
CVector() {};
CVector(int a, int b) :x(a), y(b) {}
};
CVector operator- (const CVector& lhs, const CVector& rhs)
{
CVector temp;
temp.x = lhs.x - rhs.x;
temp.y = lhs.y - rhs.y;
return temp;
}
int main()
{
CVector foo(2, 3);
CVector bar(3, 2... |
why we can write CVector(lhs.x - rhs.x, lhs.y - rhs.y). What does it mean? What happens when we use a class without a name?
The expression CVector(lhs.x - rhs.x, lhs.y - rhs.y) uses the pameterized constructor CVector::CVector(int, int) to construct a CVector by passing the arguments lhs.x - rhs.x and lhs.y - rhs.y. ... |
71,809,876 | 71,811,056 | C++ convertStringToByteArray to Delphi convertStringToByteArray | Im trying to use the GlobalPlatform library from Karsten Ohme (kaoh) in Delphi. Thanks to the help of some people here on stackoverflow i got it parially working and i am able to setup a connection to the cardreader. Now i am trying to select an AID, and therefore i need to pass the AID as array of Bytes to the functio... | The original C++ code parses pairs of hex digits into bytes:
A000000003000000 -> A0 00 00 00 03 00 00 00
But your Delphi code is parsing individual hex digits into bytes instead:
A000000003000000 -> A 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0
Try this instead:
procedure StrToByteArray(Input: AnsiString; var Bytes: TBytes; Literall... |
71,810,211 | 71,810,429 | what is the proper way to compile cuda with g++ | the code files as follow:
a.h
void warperFoo();
a.cu
//---------- a.cu ----------
#include <cuda.h>
#include <cuda_runtime.h>
#include <stdio.h>
#include "a.h"
__global__ void foo (void) {
printf("calling from kernel foo: %d\n", threadIdx.x);
// bar();
}
void warperFoo() {
printf("calling from warperFoo\n")... | the problem occured because cudaDeviceSynchronize().
refer to similiar question, printf didn't work because host process have exited before kernel function executed.
|
71,810,810 | 71,810,947 | For every instance of a character/substring in string | I have a string in C++ that looks like this:
string word = "substring"
I want to read through the word string using a for loop, and each time an s is found, print out "S found!". The end result should be:
S found!
S found!
| Maybe you could utilize toupper:
#include <iostream>
#include <string>
void FindCharInString(const std::string &str, const char &search_ch) {
const char search_ch_upper = toupper(search_ch, std::locale());
for (const char &ch : str) {
if (toupper(ch, std::locale()) == search_ch_upper) {
std::cout << sear... |
71,810,868 | 71,810,871 | How to build CCLS on Linux (performed on Fedora)? | I have tried using CMake to build ccls many times and I have just about given so if anyone has a way to do it that would be mega helpful.
I am on Fedora Linux and I am using the repo to get ccls as the prebuilt binaries don't work.
Any help would be appreciated. Thanks.
| To get it to work on Fedora (I don't see any reason why it shouldn't work on other Linux distros) this is how I did it step by step:
Quick note: You may want to use sudo yum install clang-devel and sudo yum install llvm-devel since they potentially hold needed dependencies. Also make sure you have downloaded the other... |
71,811,030 | 71,811,276 | How to unpack only part of a parameter pack when declaring a variable? | I want to create a tuple that ignores an N number of the first types on a parameter pack, something like this
template<typename... Args>
class Foo
{
std::tuple</*Args<2>,Args<3>,Args<4> and so on*/> tup;
}
Currently the only solution that I found to achieve something close to this is
template<typename... Args>
cl... | Using class template partial specialization should be enough
#include <tuple>
template<std::size_t N, typename... Args>
struct ignore_first;
template<std::size_t N, typename First, typename... Args>
struct ignore_first<N, First, Args...> : ignore_first<N-1, Args...> { };
template<typename First, typename... Args>
st... |
71,811,414 | 71,811,461 | How to interleave two vectors of different sizes? | I have two vectors
vector<int> first_v = {1, 4, 9, 16, 8, 56};
vector<int> second_v = {20, 30};
And the goal is to combine those vectors in specific order like that (basically program first prints one value of the first_v vector and then one value of second_v vector):
Expected Output:
1 20 4 30 9 16 8 56
I'm very cl... | You could keep one iterator to each vector and add from the vector(s) that have not reached their end() iterator.
Example:
#include <iostream>
#include <vector>
std::vector<int> merge_vect(const std::vector<int>& avec,
const std::vector<int>& bvec)
{
std::vector<int> result;
result.... |
71,811,825 | 71,811,848 | Character goes diagonal by diffrent font sizes in c++ opengl true type font | I've been trying to get TTF to work with my OpenGL project and this is the closest I've come to, here is my code:
#include "App.h"
std::array <float, 4> background_col = {0.25, 0.25, 0.25, 1.0} ;
std::string name = "OpenGL" ;
std::string icon = "data/images/dot.... | By default each row of the pixels is assumed be aligned to 4 bytes, but your pixel data is not aligned at all. You can change the alignment requirements by setting GL_UNPACK_ALIGNMENT (see glDrawPixels and glPixelStore):
glPixelStore(GL_UNPACK_ALIGNMENT, 1);
glDrawPixels( face->glyph->bitmap.width, face->glyph->bitmap.... |
71,812,034 | 71,812,083 | Why isn't my C++ maximizing pairwise product code working? | So the problem asked me to find the greatest product from a given sequence of non-negative integers. What I did was I tried to find the greatest two integers from the sequence (for which I used a vector, by taking an input of n numbers) and multiplied them, since there are no negative integers. I used the long long typ... | You haver undefined behavior right here
long long max_prod(const vector<int>& numbers) {
int max1 = -1; <<<<<====
int max2 = -1;
int n = numbers.size();
for (int i = 0; i < n; i++) {
if (numbers[i] > numbers[max1]) <<<<<==
max1 = i;
}
for (int j = 0; j < n; j++) {
if ... |
71,812,408 | 71,812,633 | C++ - std::getline() returns nothing | I have a C++ function that reads a .txt file, however, when I run it, std::getline returns nothing. Therefore, the while loop on line 22 does not run.
How do I fix this function to return a vector where each line is a different item in the vector?
The file I am reading from a .txt file that has two lines:
testing
123
... | You don't need to invoke file.open(filename); because you already opened the file using the constructor std::ifstream file(filename);.
Invoking file.open(filename); after opening the file using the constructor causes the stream to enter an error state, because the file has not been closed yet.
See The difference betwee... |
71,812,498 | 73,921,837 | Why and how do the C++ implicit conversion rules distinguish templated conversion functions from non-templated? | I'm trying to understand the implicit conversion rules in C++, and why the two implicit conversions in the following reduced case differ:
// A templated struct.
template <typename T>
struct A {};
// A templated struct that can be constructed from anything that can be
// converted to A<T>. In reality the reason the con... | Quoted text is from the C++20 standard, but links are to N4861.
[dcl.init.general]/17.6.3 explains how such a copy-initialization is done:
Otherwise (i.e., for the remaining copy-initialization cases), user-defined conversions that can
convert from the source type to the destination type or (when a conversion function... |
71,812,942 | 71,812,965 | c++ wont take absolute value of a number | I create a tic tac toe AI in c++. I've tried adding code to add X to where the player put it, but when I run it gives me an error related to line 37. There's an expression that simply converts a set of coordinates into a number. Rearranging the code gives me another error. The error might be related to how I ask for t... | This does not work the way you expect:
abs(h - Board[h].size() + 1)
The call to vector::size() returns a size_t value, which you are subtracting from a int value. By the rules of arithmetic conversions the int will be converted to unsigned.
So what you have is an unsigned type whereby your subtraction wraps "below" z... |
71,813,027 | 71,813,079 | Questions about `std::cout << &std::hex << 123 << std::endl;` | Here is the code snippet:
#include <iostream>
int main()
{
std::cout << std::hex << 123 << std::endl;
std::cout << &std::hex << 123 << std::endl;
}
What's &std::hex? I think it acquire the address of std::hex. And the address would be printed out.
Is there any potential problem with this code snippet beca... | The name of a function decays into a pointer to that function. So std::cout << std::hex uses the stream inserter that takes a pointer to a function that takes an std::ios_base& and returns an std::ios_base&. The stream inserter simply calls the function.
Function pointers have another peculiar property: when you write ... |
71,813,354 | 71,813,393 | argument list for class template "Node" is missingC/C++(441) | #include <iostream>
using namespace std;
template <typename T>
// we shouln't use the template here, it will cause a bug
// "argument list for class template "Node" is missingC/C++(441)"
// to fix the bug, check "https://stackoverflow.com/questions/15283195/argument-list-for-class-template-is-missing"
struct Node
{
... | The print function should also be a template function, the C++ compiler needs you to tell it the specific type of the Node in print function. see below:
#include <iostream>
using namespace std;
template<typename T>
struct Node
{
T datum;
Node* left;
Node* right;
};
template<typename T>
void print(const No... |
71,813,542 | 71,814,451 | Why does using thread_local variable cause a segfault? | I create an on-heap array in class A and then create a thread_local A object. Accessing on-heap storage via A causes a segfault, why?
#include <chrono>
#include <iostream>
#include <memory>
#include <thread>
#include <vector>
class A {
public:
A() {
std::cout << ">>>> constructor >>>>" << std::endl;
a = new... | t is only initialised in when your code passes through it in main. As t1 is a separate thread its t is a separate instance of the variable but it is not initialised as the code in t1 never executes the line where t is declared.
If we change t to a global then the rules are different and each thread automatically initia... |
71,814,117 | 71,814,170 | C++ less verbose way to input template argument | I'm practicing Algorithms textbook and modern C++ coding.
I wrote a brief test that verifies sorting functions as the following:
(I know using namespace std; is discouraged in production, so please don't advice on that)
namespace frozenca {
using namespace std;
template <ranges::input_range R>
void print(R&& r, ostre... |
This is way too verbose. Is there any less verbose way?
Just change the order of template parameters
template <ranges::forward_range R = vector<int>, typename F>
requires regular_invocable<F, R>
void verify_sorting(F&& f, /* */);
Then you can just invoke like this
fc::verify_sorting(std::ranges::sort);
fc::verif... |
71,814,853 | 71,814,901 | Does move constructor change the memory to which "this" points to? | I have some confusions about C++ move constructor. If the compiler is implicitly synthesizing a move constructor, what will this move constructor do? Will it just make "this" point to the object that is used for initialization?
there's an example:
struct Foo {
int i;
int *ptr;
};
Foo x;
Foo y(std::move(x));
w... |
will the implicitly synthesized move constructor just make this in y point to the memory that x is in?
The synthesized move ctor will memberwise-move the data members of its arguments(x here) to the object being created(y here).
Also, note that for built-in types like int, move is the same as copying.
how to ensure... |
71,815,173 | 71,819,957 | Can C++20's 'operator==(const T&) = default' be mimiqued in C++17? | In C++ 20 we are able let the compiler automatically generate the implementation for operator== for us like this (and all the other default comparasions too, but I'm just interested in operator== here):
#include <compare>
struct Point {
int x;
int y;
bool operator==(const Point&) const = default;
};
Is there a w... | Only for aggregates (a slightly widened set around POD (trivial+standard layout) types).
Using PFR you can opt in using a macro:
Boost.PFR adds the following out-of-the-box functionality for
aggregate initializable structures:
comparison functions
heterogeneous comparators
hash
IO streaming
access to members by index... |
71,815,472 | 72,666,519 | Dialog will disable Shortcut in it's parent? | I have a dialog in my main.qml file the problem is that when I click menu to open dialog, after closing the dialog, Shortcut don't work any more.
main.qml
ApplicationWindow {
id:mainWindow
Shortcut {
id:backShortcut
sequences: ["Esc", "Back"]
onActivated: {
console.log("Back... | I changed context property of Shortcut to Qt.ApplicationShortcut .Now It works.But I don't know why :> ,tanks if every body explain
Shortcut {
id:backShortcut
sequences: ["Esc", "Back"]
context: Qt.ApplicationShortcut
onActivated: {
console.log("Back In MainPage")
... |
71,815,555 | 71,815,597 | How C char is different from C++ string element accessed using index | I am using C++ erase remove idiom and facing a weird problem.
If I access element using string index result is not as expected.
string str = "A man, a plan, a canal: Panama";
str.erase(remove(str.begin(), str.end(), str[1]), str.end());
Result : Aman, a plan, a canal: Panaa
and if I use as below, result is as ex... | Look at the signature of std::remove:
template< class ForwardIt, class T >
ForwardIt remove( ForwardIt first, ForwardIt last, const T& value );
The value is passed by const reference, therefore after removing first space your str[1] points to a wrong memory. It's unsafe to access container elements while modifying the... |
71,816,024 | 71,816,415 | Pointer level return type based on template function arguments | For a tensor class I would like to have a template creating functions like
double* mat(int size1);
double** mat(int size1, int size2);
double*** mat(int size1, int size2, int size3);
i.e. the pointer level of the return type depends on the number of inputs.
The base case would just be
double* mat(int size1){
return ... | you cannot declare m and return type as T* since it is not in multiple dimension.
template<typename T, typename size_type>
auto mat(size_type size){return new T[size];}
template<typename T, typename size_type, typename... size_types>
auto mat(size_type size, size_types... sizes){
using inner_type = decltype(mat<T>... |
71,816,358 | 71,821,494 | Advice on improving a function's performace | For a project I'm working on, I require a function which copies the contents of a rectangular image into another via its pixel buffers.
The function needs to account for edge collisions on the destination image as the two images are rarely going to be the same size.
I'm looking for tips on the most optimal way to do th... | Your code is mostly bounded by memory operations and more specifically the memcpy since compilers (like GCC 11) already optimize it aggressively. memcpy is generally very efficiently implemented. That being said, it is sometime sub-optimal. I think this is the case here. To understand why, we need to delve into the low... |
71,816,416 | 71,875,673 | CMake and GTest in VS 2019 test building failure | Somehow I have the same problem I had last time see here and I can't solve it this time.
I have my CMakeLists.txt file:
cmake_minimum_required (VERSION 3.20)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_TOOLCHAIN_FILE "C:/Users/JackOfShadows/vcpkg/scripts/buildsystems/vcpkg.cmake")
project... | Per suggerstion by @local_ninja I've linked project only to gtest_main and now tests are running okay.
|
71,816,555 | 71,816,661 | Interprocess communication, reading from multiple children stdout | I'm trying to write a custom shell-like program, where multiple commands can be executed concurrently. For a single command this is not much complicated. However, when I try to concurrently execute multiple commands (each one in a separate child) and capture their stdout I'm having a problem.
What I tried so far is thi... | There are multiple, fundamental, conceptual problems in the shown code.
std::pair<pid_t, int> sp;
This declares a new std::pair object. So far so good.
std::pair<pid_t, int> sp = this->subprocess(cmds[i], fds);
This declares a new std::pair object inside the for loop. It just happens to have the same name as the sp o... |
71,816,664 | 71,816,986 | Why private virtual member function of a derived class is accessible from a base class | Consider the following snippet of code:
#include <iostream>
class Base {
public:
Base() {
std::cout << "Base::constr" << std::endl;
print();
}
virtual ~Base() = default;
void print() const { printImpl(); }
private:
virtual void printImpl() const {
std::cout << "Base::printImpl" ... | First, as @Eljay notes - printImpl() is a method, albeit virtual, of the Base class. So, it's accessible from the base class. Derived merely provides a different implementation of it. And the whole point of virtual functions is that you can call a subclass' override using a base class reference or pointer.
In other wo... |
71,816,700 | 71,816,749 | less than operator is not guaranteeing uniqueness for set of objects | I am trying to construct a set of objects called guests. For this purpose, I overloaded the less than operator. The problem is that I'm not getting unique elements. I can't figure out why. The size of the set is always 2 in the following example.
// Online C++ compiler to run C++ program online
#include <iostream>
#inc... | You should remove the last part or ((l.loyalty == r.loyalty)), otherwise the operator< would return true when all the data members of Guest are equivalent.
bool operator<(const Guest& l, const Guest& r){
return (l.firstname < r.firstname) or ((l.firstname == r.firstname) and
((l.lastname < r.lastname) or... |
71,816,931 | 71,817,843 | How do you use C++ fmt on CentOS9? | I installed fmt using dnf install fmt. It was successful. But when I try to use it as #include <fmt/format.h> it says it is not found. I downloaded include from fmt git page so it finds format.h now with -I... but I have compilation errors.
undefined reference to `fmt::v8::vformat[abi:cxx11](fmt::v8::basic_string_view<... | Fedora/RHEL/CentOS uses the following naming convention for all packages that installed shared libraries:
name - this package contains runtime shared libraries that are needed to run programs that are linked with this library.
name-devel - the "devel" packages contains header files and the symbolic links that allow you... |
71,816,959 | 71,817,140 | How to retrieve an IShellItem's file size? | Given an IShellItem*, how can I find out its size?
When looking around, I've seen that a solution for this can be:
bind IShellItem2 to the given IShellItem
retrieve the IShellItem property store
with this function (as seen in the example in the page), find the file's size
I don't fully understand the Win32 API, so ma... | You don't need to use IPropertyStore if you have an IShellItem2 reference, you can directly use IShellItem2::GetUInt64 . Here is some sample code:
CoInitialize(NULL);
...
IShellItem2* item;
if (SUCCEEDED(SHCreateItemFromParsingName(L"c:\\myPath\\myFile.ext", NULL, IID_PPV_ARGS(&item))))
{
ULONGLONG size;
if (SUCC... |
71,817,529 | 71,817,560 | How to dynamically allocate a 2D std::array in C++ or why I should not use it? | I want to malloc an array in my code, and its size should be defined at runtime.
I tried like this:
#include <iostream>
#include <array>
int main(){
int M=4,N=3,P=5;
M=N+P;
std::array<std::array<double,M>,N> arr;
}
But MSVC told me:
a variable with non-static storage duration cannot be used as a non-type ... | The dynamically allocated array container in C++ is std::vector. std::array is for specifically compile-time fixed-length arrays.
https://cppreference.com is your friend!
But the vector memory size needs to be organized by myself
Not quite sure what you mean with that, but you specify the size of your std::vector usi... |
71,817,577 | 71,817,626 | CMake error: Could not find the VTK package with the following required components:GUISupportQt, ViewsQt | I compiled VTK in my RedHat 8.3 machine, and now when I want to compile an example in the /GUI/Qt/SimpleView with cmake I get the following error message when configuring:
CMake Warning at CMakeLists.txt:4 (find_package):
Found package configuration file:
home/user/Downloads/VTK-9.1.0/build/lib64/cmake/vtk-9.1/vtk-conf... | This looks like you did not set the VTK_MODULE_ENABLE_VTK_GuiSupportQt and VTK_MODULE_ENABLE_VTK_ViewsQt options to "YES" when running configure in CMake.
Note: the abovementioned option names are only applicable for VTK >= 9; for VTK < 9, they are called Module_vtkGUISupportQt and Module_vtkViewsQt (and you might als... |
71,817,610 | 71,817,684 | Indirect & Direct initialization of std::atomic in C++11/17. What are the differences? | When I see this CPP Con 2017 webinar, Fedor Pikus says: "it has to be direct initialization"
This is the link to the webinar.
What are the differences between these initialization methods? (and subsequently, why it has to be a "direct" initialization? why "indirect" initialization is "NOT"?)
// C++17 Compiler
#includ... | std::atomic is not copyable or movable.
Before C++17, the copy-initialization std::atomic<int> x = 0; would first construct a temporary std::atomic<int> from 0 and then direct-initialize x from that temporary. Without a move or copy constructor this would fail and so the line doesn't compile.
std::atomic<int> x(0); how... |
71,817,634 | 71,818,637 | QSqlTableModel: change database after constructing | I'm creating an application which uses QSqlDatabase and QSqlTableModel for inserting and retaining data from an SQLite database file.
The database instance is being created in MyApplication:
MyApplication.h
#include <QSqlDatabase>
// ...
class MyApplication
{
public:
// ....
private:
QSqlDatabase _database;
}... | The best way probably is to set up your database from a controller class in C++, give that controller a (read only & constant) properly contactsModel and expose the controller as a singleton to QML. This way you can setup the database from C++ (where your business logic belongs) while you can access your data from QML.... |
71,817,724 | 71,817,817 | C++ Program to Reverse String via Recursion keeps giving me an unwanted letter, but Python counterpart works | C++ Program (Wrong)
#include <iostream>
#include <string>
using namespace std;
char revstr(string s, int n){ //I cannot assign string here. Error pops up.
if (n == 0){
return s[0];
}
else
{
return s[n] + revstr(s, n-1);
}
}
int main(){
string sin;
cin >> sin;
int n = s... | There are three problems I can see with the code:
Check the return type of revstr - you want to return a full string, but it returns a single character (this is the cause of the problem you see, namely of the program only writing a single, often strange character; you currently simply add up characters, the values ove... |
71,817,773 | 71,817,960 | destructor's unexplained behavior while testing deep/shallow copy in C++ | class String
{
private:
char* ptr;
public:
String(const String& s1)
{
int len = strlen(s1.ptr);
ptr = new char[len+1];
strcpy(ptr,s1.ptr);
}
String(char* c)
{
int len = strlen(c);
ptr = new char[len+1];
strcpy(ptr,c);
}
~Str... | s2 points to s. It is a pointer, and not a copy at all (shallow or otherwise). It was never allocated any memory by new. So when you try to delete s2, you are asking the program to free up memory on the stack that is not managed by new/delete. Do not delete s2 in this instance. It is an error. Your destructor is not at... |
71,818,157 | 71,818,498 | get frequency elements from 2D vector? |
i try to get frequency elements for 2D vector for example : my vector vector<vector> edge { {4, 2, 3}, {4, 5, 6}, {2, 8,
9} }; result: 4 and 2 because appears 2 time in the 2D vector i'm not
familiar with c++. my code return only one element "the first
frequent element but i need to return evry f... | In your first set of for-loops where you iterate over edge, you could identify the max_count value, subsequently, you could use that value to selectively print when iterating over your map:
#include <iostream>
#include <map>
#include <vector>
int main() {
std::vector<std::vector<int>> edge
{
{4, 2, 3},
{4,... |
71,818,172 | 71,818,653 | extract line of text into a variable string | I'm building a code that must search for a line of text in a string variable that contains many lines of text (example the text variable has lines formed like this MILAN;F205).
Once the user has entered the city he wants to search for, the program must search the database for the city entered by the user (in this case ... | You could:
read your input stream into a vector of lines, and
walk that vector of lines checking if it starts with a given city name;
copying those lines that do match to an output vector (or just printing them out, or whatever).
The example below:
uses a std::istringstream instead of a std::fstream as input, and
ta... |
71,818,342 | 71,818,622 | Vector of shared pointers to templated classes | I have a templated class TaskRunner that takes a polymorphic type Task and I want to create a container of shared pointers to them.
class Task {
virtual void run() = 0;
};
class LoudTask : Task {
void run() {
std::cout << "RUNNING!" << std::endl;
}
};
class QuietTask : Task {
void run() {
... | Implemented IgorTandetnik's suggestion, and it works for me:
#include <iostream>
#include <memory>
#include <vector>
class Task {
virtual void run() = 0;
};
class LoudTask : Task {
public:
void run() {
std::cout << "RUNNING!" << std::endl;
}
};
class QuietTask : Task {
public:
void run() {
... |
71,818,515 | 71,828,125 | Linked linked destructor raises segmentation fault | I am trying to delete a linked list using the destructor.
But this code is giving a segmentation fault:
~Node()
{
Node *current = this ;
Node *previous = NULL;
while(current != NULL)
{
previous = current;
current = current->next;
delete previous;
previous = NULL;
}
}
... | You should exclude the current node from the delete operator, as the code is already a response to such a delete. Doing it again is like running in circles.
So modify your code to this:
~Node()
{
Node *current = this->next; // exclude current node
Node *previous;
while (current != NULL)
{
previ... |
71,818,819 | 71,818,990 | How do you ensure C++20 support? | I have g++ installed on CentOS9
g++ (GCC) 11.2.1 20220127 (Red Hat 11.2.1-9)
I can compile with switch -std=c++20 without errors/warnings.
When I search filesystem for '11' I find
/usr/lib/gcc/x86_64-redhat-linux/11
/usr/include/c++/11
/usr/libexec/gcc/x86_64-redhat-linux/11
But when I search for '20' I get nothing.
... | 11 in the file path is the compiler version, not the C++ version. So it is not a problem that there is no corresponding path with a 20.
If -std=c++20 doesn't give an error, you have (at least to some degree) C++20 support.
Theoretically there is the __cplusplus macro, which is predefined to a value of at least 202002L ... |
71,819,183 | 71,819,233 | How to iterate over temporary pairs | I would like to loop over an array of temporary pairs (with specifying as few types as possible)
for (const auto [x, y] : {{1, 1.0}, {2, 1.1}, {3, 1.2}}) {
// ...
}
Is that possible? (I am free to use any C++ standard which is implemented in gcc 11.2)
Currently I am using a workaround using maps which is quite verbo... | std::map performs a heap allocation, which is a bit wasteful. std::initializer_list<std::pair<int, double>> is better in this regard, but more verbose.
A bit saner alternative:
for (const auto [x, y] : {std::pair{1, 1.0}, {2, 1.1}, {3, 1.2}})
Note that in this case the type of the first element dictates the types of t... |
71,819,230 | 71,819,615 | C/C++: Are IEEE 754 float addition/multiplication/... and int-to-float conversion standardized? | Example:
#include <math.h>
#include <stdio.h>
int main()
{
float f1 = 1;
float f2 = 4.f * 3.f;
float f3 = 1.f / 1024.f;
float f4 = 3.f - 2.f;
printf("%a\n",f1);
printf("%a\n",f2);
printf("%a\n",f3);
printf("%a\n",f4);
return 0;
}
Output on gcc/clang as expected:
0x1p+0
0x1.8p+3
0x1... | No, unless the macro __STD_IEC_559__ is defined.
Basically the standard does not require IEEE 754 compatible floating point, so most compilers will use whatever floating point support the hardware provides. If the hardware provides IEEE compatible floating point, most compilers for that target will use it and predefin... |
71,819,570 | 71,819,871 | Pass by const ref in function | If eventually we want the object to own another object, what's the use of passing by const reference.
Ex.
class OrderBook
{
set<Order> orders;
void insert_Bid(const Order &order);
}
void OrderBook::insert_Bid(const Order &order)
{
orders.insert(order);
}
When we are inserting the order into the orders se... | You don't save the copy from order to orders at the insert, but you save the copy to from the caller to insert_Bid(<order_argument>) to the order parameter
|
71,819,671 | 71,819,996 | Delete the selected item in forward_list C++ | I need to somehow remove an element in a list if it is already in another list. I created a function but it doesn't work. Tell me how to fix it. thank you very much.
void compare(forward_list<string> list_1, forward_list<string> list_2) {
auto prev = list_1.before_begin();
for (int i = 0; i < Size(list_1); i+... | It seems you are trying to remove elements from list_2 that are found in list_1. But in this statement
l_front_2 = list_2.erase_after(l_front);
you are using the iterator l_front from list_1 that does not make a sense.
Also if an element in list_2 is removed then due to the expression j++ in the for loop
for (int j = ... |
71,819,745 | 71,820,062 | encapsulate reference to templated function inside compile time object | As of writing this metaclasses are sadly not a feature.
I am trying to encapsulate a reference to a templated function inside some compile time object, ideally the compile time object is easy to make, something like a type with a consteval ctor.
Doing this with a non templated function ptr is trivial:
template <typenam... |
I could write Functor as a concept and have "instances" of Functor be classes with visible static member functions with matching name and signature; but that makes the "instances" obtuse to implement.
This is usually how it is done. It is a little unweidly although its not all that different from how traits are done ... |
71,820,257 | 71,822,416 | Textures created with SDL_CreateTexture don't appear to support transparency | I want to copy multiple surfaces (created with TTF_*) to a single texture, and I can't seem to get that resulting texture to render onto the window with transparency handled correctly.
static void example(void) {
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS);
TTF_Init();
SDL_Window* w = SDL_CreateWindow("",... | Figured it out. When doing SDL_RenderCopy from the first texture to the second, the blend mode on the first texture should be set to none:
SDL_SetTextureBlendMode(t, SDL_BLENDMODE_NONE);
Now when the second texture is copied (with SDL_BLENDMODE_BLEND) the edges don't have the black artifacts.
|
71,820,548 | 71,822,849 | how to implement a class that supports both stack and heap allocations | What is the most straightforward way of forcing std::vector to use a stack-based buffer? My guess is to use std::pmr::vector.
I want to write a class in a way that enables the use of both the normal vector (which uses dynamic allocations) and also one which uses a custom buffer.
Here is a sample:
#include <iostream>
#i... | One way could be to mimic the setup used by vector and the alias template pmr::vector:
namespace foo {
template <class Allocator = std::allocator<char>>
struct Foo {
using size_type = typename std::vector<char, Allocator>::size_type;
constexpr Foo(size_type count, const char value,
... |
71,820,825 | 71,820,904 | C++ function with a viariable number of arguments of a certain type | I just learned about variadic templates in C++. I implemented it, but I want to know, can it do the following?
If I want a function with a variable number of arguments, I could do that:
template <typename... Ts>
f(Ts... args);
But I lose type safety (I don't know the type of the arguments).
What if I know my function ... | If the compiler supports C++ 20 then you can write for example
#include <type_traits>
template <typename T, uint16_t dimension>
class Vector
{
public:
template <typename... Ts>
Vector( Ts &&... args ) requires ( sizeof...( args ) == dimension ) && std::conjunction_v<std::is_same<T, std::decay_t<Ts>>...>
{
... |
71,820,980 | 71,821,235 | Is there a way to avoid casting for class and/or validity before using an object? | I started programming on UE4 recently and find myself using this code a lot:
if (GetController())
{
GetController()->GetPlayerState();
}
... or
if (GetController<APlayerController>())
{
GetController<APlayerController>()->GetMousePosition();
}
The first would check if the actor has a controller and would then... | You can avoid writing the name of the function out twice by declaring a variable in the if statement:
// "auto"/"auto&"/"auto&&" if not a pointer type
if (auto* controller = GetController<APlayerController>()) {
controller->GetMousePosition();
}
|
71,821,115 | 71,821,592 | incomplete types with shared_ptr and unique_ptr | I would like to understand why unique_ptr destructors require the type to be complete upon destruction while that isn't the case with shared_ptr. This blog from Howard Hinnant briefly mentions it has to do with static vs. dynamic deleters. I'm looking for a more detailed explanation of why that might be the case (it ma... | Howard Hinnant was simplifying. What he precisely meant was if you use the default deleter for std::unique_ptr, you need a complete type. For the default deleter, it simply calls delete for you.
The gist of static and dynamic deleters is
class A;
void static_delete(A* p)
{
delete p;
}
void (*dynamic_delete)(A*) =... |
71,821,516 | 71,821,796 | Cant make the programm exit after -999 input with summary information | Task:
Write a program that would (theoretically) remain open, and allow users to enter numbers throughout the day.
Users can enter numbers between 0 and 50. Numbers outside of that range, except -999, are invalid and the user must re-enter a valid number.
When a user enters the number, it is added to the sum, and the n... | FIGURED IT OUT, THANKS EVERYONE FOR HELP!
Here are some changes that helped:
#include <iostream>
using namespace std;
int main () {
const int minBooks = 0, maxBooks = 50;
int books;
int sum=0;
int student = 0;
do {
cout << "Books: " << endl;
cin >> books;
student++;
sum += books;
if (books == -999) {
student = stud... |
71,822,254 | 71,884,619 | Is there any way to reference floats as a glm::vec3 | I have floats in a context
float* floats = calloc(3, sizeof(float));
float& x = floats[0];
float& y = floats[1];
float& z = floats[2];
How do I assign them to a glm::vec3 such that I can perform operations on them? Is it really a matter of:
glm::vec3 vertex = { x, y, z };
// Transform and Rotate vertex
X = vertex.x;
y... | Casting to a vec3 worked as expected, with the underlying floats changing when I changed the vec3 values.
vec3& vertex = (*reinterpret_cast<vec3*>(floats));
vertex.x = 1;
assert(floats[0] == vertex.x);
|
71,822,483 | 71,822,515 | Why is the const lost in an expression like `const T&` where T is an rvalue reference? | I'm working on a templated class, and given an incoming type T the template needs to map to a "safe" const reference. (This is essentially to avoid handing the ability to mutate to a wrapped function when it's called; see here for the real code).
The original author wrote something equivalent to this:
template <typenam... |
Which part of the standard says that the const is "lost" in an expression like const T& for a templated T expanding to an rvalue reference?
From dcl.ref/p6:
If a typedef-name ([dcl.typedef], [temp.param]) or a decltype-specifier ([dcl.type.decltype]) denotes a type TR that is a reference to a type T, an attempt to c... |
71,822,648 | 71,833,564 | vcpkg manifest install system wide | Just tried Vcpkg Manifest on my cmake project and it is cool, with exceptions however.
My project depends on opencv and it takes a long time for vcpkg to install opencv. So I realized I don't want vcpkg downloawding/installing opencv every time I clone the project in a different folder.
Is it possible to use Vcpkg Mani... | No, you can't install libraries system-wide in manifest mode.
But binaries are cached so that if you use a library in multiple projects, you don't have to build it from scratch.
https://github.com/microsoft/vcpkg/blob/master/docs/users/binarycaching.md
|
71,822,708 | 71,879,002 | How to link cuda library to cpp project/files with Cmake? | I am trying to write a gui program using the gtk libraries and do some matrix operations with the cuda libraries, however I get an error when trying to link the cuda libraries in my project. My Cmake looks like this:
cmake_minimum_required(VERSION 3.21)
project(untitled1)
set(CMAKE_CXX_STANDARD 14)
find_package(CUDA... | I can't speak for your exact setup, but I've had success with CMake and CUDA on Ubuntu by directly enabling CUDA as a language in the project declaration rather than using find_package(CUDAToolkit).
Something like this:
cmake_minimum_required(VERSION 3.21)
project(untitled1 LANGUAGES CUDA CXX)
set(CMAKE_CXX_STANDARD 1... |
71,822,921 | 71,823,004 | this pointer cannot be aliased in a constructor: | I am learning about inheritance in C++. And i came across the following statement:
In other words, the this pointer cannot be aliased in a constructor:
extern struct D d;
struct D
{
D(int a) : a(a), b(d.a) {} // b(a) or b(this->a) would be correct
int a, b;
};
D d = D(1); // because b(d.a) did not obtain a ... | What is meant is that during the construction of a class object any access to the object's non-static data members should happen through a pointer/glvalue obtained directly or indirectly from this of the constructor. Otherwise the value read by such an access is unspecified.
So this->a is always fine, as is simply a wh... |
71,823,587 | 71,824,138 | In vc6.0, using WinAPI to open the program to expand the monitor some problems | Below is the main code, the problems encountered, and how they were resolved
***.h
std::list<DISPLAY_DEVICE> m_vDisplayDevice_list;
std::list<DEVMODE> m_vDevmode_list;
int m_nDisplayScreen;
***.cpp
std::list<DISPLAY_DEVICE> devices;
std::list<DEVMODE> modes;
int devId = 0;
BOOL ret = false; // bool ret = false;
bool... | Your linkage error concerning _EnumDisplayDevices says it all.
My psychic powers suggests that since Visual Studio 6.0 (released in 1998) predates the availability of EnumDisplayDevices (Windows 2000), you are trying to pre-declare the API yourself. You probably predeclared EnumDisplayDevices manually yourself. Somet... |
71,824,178 | 71,824,233 | Basic Currency Converter | I am a beginner coder and I have a problem with my code. Every time I run it, near the end it always goes to the else statement. I tried including break statements to see if that would help, but that doesn't seem to work. I also tried just making all of them if statements instead of using else if.
This code was written... | To run a control statement between multiple conditions, you have to use else if. When using else if, it will sequentially evaluate the if conditions. Currently, the else only works for the last if (num == 5).
The correct answer would be:
public:
void ifs2()
{
ifs();
if (num == 3)
{
... |
71,824,443 | 71,824,489 | using `__declspec(dllexport)` before every public method | I'm working in a C++ workspace in VS2017, having two projects in the workspace: a utility project and a main project that uses the utility project.
After I added a new class (".h" and ".cpp" files) to the utility project, I noticed that although I make changes in the code, the ".lib" file is not rewritten when I build ... | You can add the declaration to the class, instead of to the individual methods:
class __declspec(dllexport) MyProperty
{
public:
MyProperty(const std::string &csvLine);
bool getIsActive();
std::string getFormatting();
PropertyType getType();
};
Note that for the class, the place is slightly different t... |
71,824,853 | 71,825,424 | Copy and Move Idiom in children classes? | class A
{
std::string val1;
A(std::string str) : val1(std::move(str)){}
};
class B: A
{
B(std::string str) : A(str){}
};
In this case, str would be copied twice, or not?
What is the best way to use Copy & Move idiom with children's classes?
| If you are new to C++, it is maybe a good idea to simply investigate what is happening if you execute your code instead of take maybe wrong assumptions.
To see what is happening, simply replace std::string with your own class and put some debug output in it.
struct mystring
{
mystring() { std::cout << "Default" << ... |
71,825,137 | 71,825,181 | C++ Constructor error when I separate the function prototype from the definition | When I have both the prototype and definition in the same header file (as shown below), and I create an object in main (source.cpp) with Cube c1{}; I get no error and the default constructor works; c1's side will be defaulted to 0.0
class Cube {
private:
double side;
static int counter;
... | You should put the default argument to the declaration Cube(double = 0.0);, not the definition. Otherwise the matching function cannot be found in other files.
|
71,825,411 | 71,825,571 | I want to move semantics but I get a universal reference which hides copy semantics | How can I deal with universal reference, when I want either to copy semantics with a function parameter const T& or move semantics with function parameter T&&. The later hides the first.
A sample code with algebraic vector operators follow.
#include <array>
#include <iostream>
template<typename T>
void neg(T &a) { fo... | You just need to remove const from const T&.
With using U = std::array<int, 4>;:
The issue here is that T&& deduces T to U, not const U, since a in main isn't const. And binding to U& instead of const U& is considered better in overload resolution.
If you remove const from const T&, then both candidates will after dedu... |
71,825,499 | 71,828,425 | Possible storage waste of storing lambda into std::function | The size of a lambda expression object with an empty capture-list is 1
But if you store it into std:function, its size becomes 48 (on my platform)
Imagine when you have a container that stores thousands of functions
The memory usage will be 48-times bigger if you store them into std::function
Even a lambda object captu... | This is the price you pay for not needing to know the type of the function. All std::function<void()>s are interchangeable no matter which lambda they came from. If you want to store lots of the same type of function (with different captures) in a vector, you can make it a functor instead of a lambda (so that it has a ... |
71,826,282 | 71,828,307 | How asyncio UDP connection receives whole datagrams? | There is an interface asyncio.DatagramProtocol from Python library. It gives possibility to implement receiving datagrams by using method datagram_received(self, data, addr):
class MyDatagramProtocol(asyncio.DatagramProtocol):
def datagram_received(self, data: bytes, addr: tuple[str, int]):
# Here I can use... | With a datagram socket, recv always receives only one datagram at a time.
See man page udp(7):
All receive operations return only one packet.
|
71,826,310 | 71,826,343 | Repeat indefinitely until a button is pressed in another window with C++ in QT | I am writing a program in C++ with qtcreator in which I have to execute some actions indefinitely until the user, in another window, wants to stop it by pressing a button. The problem I am having is that when I run the code, the new window is blank and the program goes into "not responding" mode even though the loop is... | QThread::msleep sleeps for a certain time, it's what's called "busy waiting".
For the GUI to be responsive, it has to be able to process events (paint event etc.). In Qt, you can do this two ways:
Either implicitly by calling QApplication::exec() (which internally runs an event loop for you), or
by explicitly calling ... |
71,826,315 | 71,826,470 | Ternary operator applied to different lambdas produces inconsistent results | Consider the following which uses the ternary operator to get the common function pointer type of the two lambdas
int main() {
true ? [](auto) noexcept {} : [](int) {};
}
GCC-trunk only accepts it in C++14 but rejects it in C++17/20 with (Demo):
<source>:2:8: error: operands to '?:' have different types 'main()::<la... | Since each lambda expression has a unique type, and neither lambda expression is convertible to the other, [expr.cond]/6 applies.
If the second and third operands do not have the same type, and either has (possibly cv-qualified) class type, overload resolution is used to determine the conversions (if any) to be applie... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.