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 need to be the same size. For an example the parameter could be vector of deques, classic C-like matrix, vector of vectors, deques of vectors and so on, you get the point. Having said that. Function itself needs to dynamically alocate (using fragmented and not continual allocation) memory for 2d matrix with same structure and type of elements and then copy all the elements from given matrix into it, and finally return a double pointer which you can use to access the elements of matrix. Having that said, I do not actually know how to use full deduction so that the function actually knows which type is the double pointer that it must return. First thing that crosses my mind is to use something like this:
template <typename MatrixType>
auto CreateMatrix (MatrixType M) -> decltype ...
Logic behind it is that full deduction would find out what type of double pointer must be returned, but the three dots (...) is where im halted, i dont actually know what to write there.
Ofcourse I could probably do something like this:
template <typename MatrixType>
MatrixType** CreateMatrix (MatrixType M)
But it doesn't use deduction because call like this:
std::vector<std::deque<double>> a = {...};
auto x = CreateMatrix(a);
wouldn't work without using <double> with the call of the function, so it is not a full "problem solved" it is just a cheap trick.
Memory allocation shouldn't be hard, I think It would be pretty easy to do, but currently I'm stuck here and do not know what to do.
I am grateful for every help!
| 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 as pointer T** then the value type is T. When an array T[M][N] is passed by reference then the value type is T:
template <typename T>
struct value_type { using type = typename T::value_type; };
template <typename T>
struct value_type< T*> { using type = T; };
template <typename T,size_t N>
struct value_type< T[N] > { using type = T;};
template <typename T>
struct value_type2d {
using type = typename value_type<typename value_type<T>::type>::type;
};
As an example I used a function that simple returns the first element:
template <typename Matrix>
typename value_type2d<Matrix>::type foo(const Matrix& m) {
return m[0][0];
}
int main() {
std::vector<std::vector<double>> x{{42,1},{2,3}};
std::cout << foo(x) << "\n";
std::vector<std::deque<double>> y{{42,1},{2,3}};
std::cout << foo(x) << "\n";
int z[2][2] = {{42,1},{2,3}};
std::cout << foo(z) << "\n";
std::vector<std::string> w[2] = {{"42","1"},{"2","3"}};
std::cout << foo(x) << "\n";
}
Live Demo
PS: Yes decltype( M[0][0] ) is a simpler way to get the value type. Though for example std::map::operator[] is not const and you should not pass a non const referene when the function does not modify the parameter. And you certainly do not want to copy the whole matrix just to pass it to the function.
|
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, type_info const * __info,
void const* __fallback_info)
{
switch (__act)
{
case _Action::_Destroy:
__destroy(const_cast<any &>(*__this));
return nullptr;
case _Action::_Copy:
__copy(*__this, *__other);
return nullptr;
case _Action::_Move:
__move(const_cast<any &>(*__this), *__other);
return nullptr;
case _Action::_Get:
return __get(const_cast<any &>(*__this), __info, __fallback_info);
case _Action::_TypeInfo:
return __type_info();
}
__libcpp_unreachable();
}
Note: This is just one __handle function but there there are two such functions in each any implementation: one for small objects (Small buffer optimization) allocated within any and one for big objects allocated on the heap. Which one is used depends on the value of the function pointer stored in the any object.
The ability to choose one of two implementations at run-time and call a specific method from a pre-defined list of methods is essentially a manual implementation of a virtual table. I'm wondering why it was implemented this way. Wouldn't it have been easier to simply store a pointer to a virtual type?
I couldn't find any information about the reasons for this implementation. Thinking about it, I guess using a virtual class is sub-optimal in two ways:
It needs an object instance and managing a singleton, whereas in reality a vtable (without an instance) is enough.
Calling a function on any would involve two indirections: first through the pointer stored in any to get the vtable, then through the pointer stored in the vtable. I'm not sure if the performance of this is any different to the switch-based approach above.
Are these the reasons for using an implementation based on switch-ing op-codes? Is there any other major advantage of the current implementation? Do you know of a link to general information about this technique?
| 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 the any. Given that it's a fairly small type (16 bytes on GCC x86-64), any fits into a pair of registers. Now, if you return an any from a function, the pointer to the "do everything" function of the any is already in a register or on the stack! You can just jump directly to it without having to fetch anything from memory. Most likely, you didn't even have to touch memory at all: You know what type is in the any at the point you construct it, so the function pointer value is just a constant that's loaded into the appropriate register. Later, you use the value of that register as your jump target. This means there's no chance for misprediction of the jump because there is nothing to predict, the value is right there for the CPU to consume.
In other words: The reason that you get the jump target for free with this implementation is that the CPU must have already touched the any in some way to obtain it in the first place, meaning that it already knows the jump target and can jump to it with no additional delay.
That means there really is no indirection to speak of with the current implementation if the any is already "hot", which it will be most of the time, especially if it's used as a return value.
On the other hand, if you use a table of function pointers somewhere in a read-only section (and let the any instance point to that instead), you'll have to go to memory (or cache) every single time you want to move or access it. The size of an any is still 16 bytes in this case but fetching values from memory is much, much slower than accessing a value in a register, especially if it's not in a cache. In a lot of cases, moving an any is as simple as copying its 16 bytes from one location to another, followed by zeroing out the original instance. This is pretty much free on any modern CPU. However, if you go the pointer table route, you'll have to fetch from memory every time, wait for the reads to complete, and then do the indirect call. Now consider that you'll often have to do a sequence of calls on the any (i.e. move, then destruct) and this will quickly add up. The problem is that you don't just get the address of the function you want to jump to for free every time you touch the any, the CPU has to fetch it explicitly. Indirect jumps to a value read from memory are quite expensive since the CPU can only retire the jump operation once the entire memory operation has finished. That doesn't just include fetching a value (which is potentially quite fast because of caches) but also address generation, store forwarding buffer lookup, TLB lookup, access validation, and potentially even page table walks. So even if the jump address is computed quickly, the jump won't retire for quite a long while. In general, "indirect-jump-to-address-from-memory" operations are among the worst things that can happen to a CPU's pipeline.
TL;DR: As it is now, returning an any doesn't stall the CPU's pipeline (the jump target is already available in a register so the jump can retire pretty much immediately). With a table-based solution, returning an any will stall the pipeline twice: Once to fetch the address of the move function, then another time to fetch the destructor. This delays retirement of the jump quite a bit since it'll have to wait not only for the memory value but also for the TLB and access permission checks.
Code memory accesses, on the other hand, aren't affected by this since the code is kept in microcode form anyway (in the µOp cache). Fetching and executing a few conditional branches in that switch statement is therefore quite fast (and even more so when the branch predictor gets things right, which it almost always does).
|
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 call but in this case B should be of type IEnumerable<int> and on calling Skip() with ToArray() it creates a copy with different base address, but I want to pass this same array to function foo. How can we do that in C#?
| 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));
DoSomethingWithSpanReference(arr2.AsSpan().Slice(1, arr2.Length - 1));
}
private static void DoSomethingWithSegmentReference(ArraySegment<int> slice){
for(int i = 0; i < slice.Count; i++)
slice[i] = slice[i] * 2;
}
private static void DoSomethingWithSpanReference(Span<int> slice){
for(int i = 0; i < slice.Length; i++)
slice[i] = slice[i] * 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(*Funcptr)();
Funcptr f1 = &cmd_create<A>;
f1();
return 0;
}
The program output Cmd.
The assembly (-O3) shows that
.file "test.cpp"
.text
.section .rodata.str1.1,"aMS",@progbits,1
.LC0:
.string "Cmd"
.section .text.startup,"ax",@progbits
.p2align 4,,15
.globl main
.type main, @function
main:
.LFB38:
.cfi_startproc
leaq .LC0(%rip), %rsi
subq $8, %rsp
.cfi_def_cfa_offset 16
movl $1, %edi
xorl %eax, %eax
call __printf_chk@PLT
xorl %eax, %eax
addq $8, %rsp
.cfi_def_cfa_offset 8
ret
.cfi_endproc
.LFE38:
.size main, .-main
.ident "GCC: (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0"
.section .note.GNU-stack,"",@progbits
Obviously, &cmd_create<A> returns the A::command.
The cmd_create is defined as an empty return (void), however, the code still gets the A::command in such a weird way.
Thank you for your answer!
|
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 function in the code returns anything (if we do not count printf or main).
f1(); calls the function pointed to by f1. That is: cmd_create<A>. The function creates an object of type A and calls its command member function which prints the output you see on the screen.
Enabling optimizations means that the compiler emits something that has the same observable behavior. It could emit the same as it would for int main() { printf("Cmd"); }.
|
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::VideoCapture cap(0);
if (!cap.isOpened){
std::cout << "Error opening camera" << std::endl;
}
cv::Mat img;
while(1){
cap >> img;
cv::imshow("output", img);
cv::waitKey(1);
}
}
This is how I compile it
g++ example.cpp `pkg-config --libs opencv4`
I can't figure out why the error shows up. Any help is appreciated!
| 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 cv::Mat::Mat(), go to the documentation at https://docs.opencv.org/ , chose the newest version (here: https://docs.opencv.org/4.5.5/ ), enter, in the "search" window, the name of a class/function the linker cannot find (here: Mat), read the header that defines it (here: #include<opencv2/core/mat.hpp>), then the missing library will have the name libopencv_core.* or libopencv_mat.*. Find whichever is in your machine (e.g. inside /user/lib) and link it, omitting the extension and the beginning lib in the name. In my case the library location, with the full path, is /usr/lib/libopencv_core.so, so I link it with -lopencv_core. Then you need to find the remaining libs in the same way.
Learn how to automatize this, e.g. via a Makefile, CMakeLists.txt or just a simple bash script.
|
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 difference is the name mangling and I don't have to worry about that because I am using the unmangled name to find the function with dlsym.
But my understanding is there are other aspects of the linkage which could be a mismatch (I am thinking of exception handling, different ABI?).
I have tried -
extern "C" void (*foo) (void) = (void (*) (void)) dlsym(handle, "foo");
But the compiler doesn't like extern "C" for local variables. What is the right way to call functions loaded with dlsym? Or should I not have to worry about linkages?
Edit: To further clarify the question, I need to compute the function pointer types based on some template parameters which makes this harder and after the discussions in the answers and comments it is currently not possible to do this (the standards are being adjusted to allow this). The current accepted answer correctly answers the question asked.
| 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 possible? I implemented the code below, but unfortunately I got an error message which I couldn't seem to get rid of.
class A {...}; //abstract
class B : public A {...};
class C : public A {...};
class D : public A {...};
class E : public A {...};
vector <B> vecb;
vector <C> vecc;
vector <D> vecd;
vector <E> vece;
vector <A*> mainvec = { vecb, vecc, vecd, vece };
Here is the error I get:
Severity Code Description Project File Line Suppression State
Error (active) E0289 no instance of constructor "std::vector<_Ty, _Alloc>::vector [with _Ty=A *, _Alloc=std::allocator<A *>]" matches the argument list
|
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::vector<D> vecd;
std::vector<E> vece;
using VariantOfVectors = std::variant< std::vector<B>*, std::vector<C>*, std::vector<D>*, std::vector<E>* >;
std::vector<VariantOfVectors> mainvec = { &vecb, &vecc, &vecd, &vece };
|
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 listed in a human-readable way.
enum eventType {
MODIFY_A,
MODIFY_B,
MODIFY_C,
MODIFY_D
}
The communication protocol I try to adapt uses custom packets with predefined hex values. So for example, sending 0x00, 0x01, 0x02, 0x03 could change led colour of a receiving device.
The library used for ble communication accepts arrays of said hexes, or other words, just a plain C string.
It would be easiest to simply define an array in a switch() after declaring it, just like this:
uint8_t* getCommandOf(eventType event) {
uint8_t command[4];
switch(event) {
case eventType::MODIFY_A:
command = {0x01, 0x00, 0x00, 0x00}; break;
case eventType::MODIFY_B:
command = {0x02, 0x00, 0x00, 0x00}; break;
case eventType::MODIFY_C:
command = {0x03, 0x00, 0x00, 0x00}; break;
case eventType::MODIFY_D:
command = {0x04, 0x00, 0x00, 0x00}; break;
}
return command;
}
Then I could simply call:
sendOverBLE(getCommandOf(eventType::MODIFY_A));
Unfortunately, we can't do that in C++.
I'm open to suggestions. How would you solve it? I though of a few solutions, butI don't like any of them.
Maybe define them in a 2d array? Or a custom container class?
| 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};
case eventType::MODIFY_C:
return {0x03, 0x00, 0x00, 0x00};
case eventType::MODIFY_D:
return {0x04, 0x00, 0x00, 0x00};
}
// for bad input
return {}; // for all zeros
// or use an exception
throw std::invalid_argument("some error message here");
}
If you need to pass this array to a function that takes a uint8_t*, then you can use array's data member to get such a pointer like
my_uint8_t_ptr_func(getCommandOf(eventType::MODIFY_A).data());
|
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 will compress body buffers for you and the other end (assuming it supports compression) will transparently decompress them.
|
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 Traits<T U::*>
^^^^^^ // I don't understand this syntax
{
using type1 = T;
using type2 = U;
};
int main()
{
// ### Pointer to member function ###
void (Foo::*memFuncPtr)() = &Foo::bar;
Foo f;
// ### Use the member function pointer to invoke it ###
(f.*memFuncPtr)();
static_assert(std::is_same_v<void(), Traits<decltype(&Foo::bar)>::type1>);
static_assert(std::is_same_v<Foo, Traits<decltype(&Foo::bar)>::type2>);
return 0;
}
How does the specialization syntax work? It makes sense that the U in U::* is the same as the Foo type but why is T the same as the void() type?
Edit
After the very useful comments from @user17732522 and answer by @AnoopRana I was able to change the main function implementation to use the same syntax (just to see it work).
int main()
{
using F = void();
// ### Pointer to member function ###
F Foo::*memFuncPtr = &Foo::bar;
Foo f;
// ### Use the member function pointer to invoke it ###
(f.*memFuncPtr)();
static_assert(std::is_same_v<void(), Traits<decltype(&Foo::bar)>::type1>);
static_assert(std::is_same_v<Foo, Traits<decltype(&Foo::bar)>::type2>);
return 0;
}
|
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 is:
void (Foo::* f)()
Now you can compare this with T U::*
So, after comparing we get:
U = Foo which is the class type.
T = void() which means a function that has the return type void and takes no parameter i.e., a function type.
which effectively means that we've a pointer to a member function that has the return type void and takes no parameters, of class Foo.
|
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 container H, with iterators which for some reason I want to overload std::advance for:
template <typename T, class Allocator=std::allocator<T>>
class H
{
// etc
class iterator;
};
How does one design an advance overload to match that iterator, and have C++ correctly select the overload when calling advance on H's iterator class? The code below does not work because only H is specified in the templating, not the iterator itself:
template< template <typename, class> class container, class T, class Allocator, class Distance >
constexpr void advance( container<T, Allocator>::iterator& it, Distance n );
I can't quite work out how to specify the iterator specifically in the template line.
| 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:
class iterator
{
public:
struct cheat_tag {};
// etc
};
};
template<class T>
concept h_iterator = requires { typename T::cheat_tag; };
namespace std
{
template <h_iterator T, class D>
constexpr void advance(T&, D)
{
// etc
}
}
Provided you match the signature of the template you're trying to overload exactly, this should work.
|
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 compiler tells you:
<source>: In function 'void foo()':
<source>:4:27: warning: empty parentheses were disambiguated as a function declaration [-Wvexing-parse]
4 | class_name object_name();
|
|
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 value 4 is created and then the reference ref is bound to this temporary(prvalue) int object instead of binding to the variable val directly. This happens because the type of the variable val on the right hand side is double while on the left hand side we have a reference to int. But for binding a reference to a variable the types should match. Moreover, the lifetime of the temporary prvalue is extended.
Possibility 2
I think there is another possibility that could happen which is as follows:
Here a temporary(prvalue) of type int with value 4 is created. But since const int &ref expects a glvalue and currently we've a prvalue, the temporary materialization kicks in and so the prvalue is converted to an xvalue. Then the reference ref is bound to this materialized xvalue(since xvalue is also a glvalue) instead of binding to the variable val directly. This happens because the type of the variable val on the right hand side is double while on the left hand side we have a reference to int. But for binding a reference to a variable the types should match. Moreover, the lifetime of the materialized temporary xvalue is extended.
My questions are:
Which of the above explanation is correct according to the C++11 standard. I am open to accept that none of the explanation above is correct in which case what is the correct explanation.
Which of the above explanation is correct according to the C++17 standard. I am open to accept that none of the explanation above is correct in which case what is the correct explanation.
I am also confused to whether a prvalue in the first step of both of the possibilities above, is actually a temporary object? Or the xvalue is the actual object. I mean do we have 2 temporary objects, like the first one due to "conversion to prvalue" and second one due to the "prvalue to xvalue" conversion(temporary materiliazation). Or do we only have one temporary which is due to the "prvalue to xvalue" temporary materialization.
PS: I am not looking for a way to solve this. For example, i know that i can simply write:
const double &ref = val;. My aim is to understand what is happening according to C++11 and C++17 standards.
| 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 important thing to note is that from basic.lval#4:
Class prvalues can have cv-qualified types; non-class prvalues always have cv-unqualified types...
When applied to your example, this means that a temporary of type int is created and is initialized from the initializer expression val using the rules for a non-reference copy-initialization. The temporary int so created has the value category of prvalue if/when used as an expression.
Next, the reference ref is then bound to the temporary int created which has value 4. Thus,
double val = 4.55;
const int &ref = val; // ref refers to temporary with value 4
C++17
From decl.init.ref 5.2.2.2:
Otherwise, the initializer expression is implicitly converted to a prvalue of type “cv1 T1”. The temporary materialization conversion is applied and the reference is bound to the result.
When applied to your example, this means that the initializer expression val is implicitly converted to a prvalue of type const int. Now we currently have a prvalue const int. But before temporary materialization is applied, expr 6 kicks in which says:
If a prvalue initially has the type “cv T”, where T is a cv-unqualified non-class, non-array type, the type of the expression is adjusted to T prior to any further analysis.
This means before temporary materialization could happen, the prvalue const int is adjusted to prvalue int.
Finally, temporary materialization is applied and and ref is bound to the resulting xvalue.
|
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 synchronize source files since we use different file paths.
May I ask what is typical way to collaborate between programmers when they have different setup, different file paths? I think that I need to simplify the file path for asset.
I tried to add include directories for compiler, but it only work with header files, not for asset files.
| 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 to your asset paths.
|
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; // run time argument
constexpr A a{ 2 }, b{ 3 };
A c{ x };
A u = a + b + c; // both + eval at run time
//constexpr A v = a + b + c; // doesn't compile because c is not constant
}
What I want to achieve is that the first operator+ is evaluated at compile time and the second operator+ is evaluated at run time.
It is of course possible to break it into
constexpr A tmp = a + b;
A u = tmp + c;
but in my case the whole point of overloading operators is to allow building more complicated formulas in a more intuitive way, so that would make the overloading pointless.
If I declare operator+ as consteval, then it again doesn't compile. And I cannot overload it twice.
Is there a solution?
| 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) {
constexpr A a{ 2 }, b{ 3 };
A c{ x };
A u = value(a+b) + c;
return u;
}
https://godbolt.org/z/ohf61vebv
|
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.txt file:
cmake_minimum_required(VERSION 3.10)
# set the project name
project(cppApp)
# specify the C++ standard
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)
include_directories(${PROJECT_SOURCE_DIR})
# add the executable
add_executable(cppApp main.cpp ./package1/src/file.cpp ./package2/src/file2.cpp)
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?
Also, how do I in CMake include all files in the "packages" to be built instead of hard coding in the files as an executable? If I create many .cpp/.h files I want to automate this as much as possible.
I have seen that some other projects use a CMakeLists.txt file inside each "package", is this ideal? And is this good practice?
If you have a better suggestion according to some standard I should use to structure my project I would like to know a good one as well.
|
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 in Java in namespace manner. It could be classes of a separate library, but nothing prevents you from using different packages within the same project. It has nothing to do with CMake packages, where each package is actually a whole separate project.
I have seen that some other projects use a CMakeLists.txt file inside
each "package", is this ideal? And is this good practice?
CMakeLists.txt files in subdirectories merely define new subset of rules for those directories. In order to make your CMake project respect those rules, you add such directory with add_subdirectory. It's not neccessarily a separate library, you can make subset of rules for parts of a single project, and it's usually a good idea to do that if some files are really that different.
CMake have something called add_library(lib) and is those kinds of directories considered a library?
add_library creates so-called CMake target, just like add_executable. The targets can be linked with each other with use of target_link_libraries, and that will indeed be considered a library in terms of C++.
|
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 in the array, using **arr gives me the value of the first object in the array.
But how do I access the next objects of the array is what I'm struggling with, let's say I want to iterate through the array in a for loop for example.
| 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 question is: what's the exact definition of "prior to"? Say, in this situation
void write_other()
{
other_var1 = true;
other_var2 = true;
}
void write() // writer thread
{
write_other();
x.store(true, std::memory_order_relaxed);
y.store(true, std::memory_order_release); // release!!
}
void read() // reader thread
{
while (!y.load(std::memory_order_acquire)) {} // acquire!!
assert(x.load(std::memory_order_relaxed)); // this is definitely true
assert(other_var1.load(std::memory_order_relaxed)); // is this true?
assert(other_var2.load(std::memory_order_relaxed)); // is this true?
}
Then in the main thread, I launch the two threads.
std::vector<std::thread> threads;
threads.push_back(std::thread(&read));
threads.push_back(std::thread(&write));
In the writer thread, the write to other_var1 and other_var2 happen in function "write_other" that is called by the thread entry function "write". In this situation, can the updates to other_var1 and other_var2 be synchronized to the loading of y in the reader thread?
In other words, what's the scope of the relative order guarantee? Should it cover only the current code block? Or should it cover all updates that have ever happened in the writer thread before the std::memory_order_release operation?
| 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 fortunately, you don't need to care about it.
In absense of consume operations (the use of which is discouraged by the standard, since apparently no modern compiler supports them, silently replacing them with stronger acquire operations), this is equivalent to a lot less obscure simply-happens-before.
A simply-happens-before B if:
A is sequenced-before B (i.e. they're both in the same thread, and one runs before the other), or
A synchronizes-with B (most often A is a release operation, and B is an acquire operation in a different thread that reads the value from A; but synchronization also happens in some other scenarios).
This relation is transitive, meaning that any number of chained "sequenced-before" and "synchronizes-with" also imposes "simply-happens-before".
There's also strongly-happens-before, which is same as simply-happens-before in absense of mixing release/acquire with seq-cst on the same variable (read more).
|
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 window.
If, on the other hand, you have large textures (just like in the linked thread), or you just want to render the entire frame pixelated, you can do this by rendering the contents of the frame on a low-resolution auxiliary texture (serving as the back buffer), and after rendering the entire frame, rendering the back buffer in the window. The buffer texture will be stretched across the entire window and the pixelation will then be visible.
I used this method for the Fairtris game which renders the image in NES-like resolution. Internal back buffer texture has resolution of 256×240 pixels and is rendered in a window of any size, maintaining the required proportions (4:3, so slightly stretched horizontally). However, in this game I used linear scaling to make the image smoother.
To do this you need to:
remember that the nearest scaling must be set,
create a renderer with the SDL_RENDERER_TARGETTEXTURE flag,
create back buffer texture with low resolution (e.g. 256×240) and with SDL_TEXTUREACCESS_TARGET flag.
When rendering a frame, you need to:
set the renderer target to the backbuffer texture with SDL_SetRenderTarget,
render everything the frame should contain using the renderer and back buffer size (e.g. 256×240),
bring the renderer target back to the window using SDL_SetRenderTarget again.
You can resize the back buffer texture at any time if you want a smaller area (zoom in effect, so larger pixels on the screen) or a larger area (zoom out effect, so smaller pixels on the screen) in the frame. To do this, you will most likely have to destroy and recreate the backbuffer texture with a different size. Or you can create a big backbuffer texture with an extra margin and when rendering, use a smaller or bigger area of it — this will avoid redundant memory operations.
At this point, you have the entire frame in an auxiliary texture that you can render in the window. To render it in a window, use the SDL_RenderCopy function, specifying the renderer handle and back buffer texture handle (rects should not be given so that the texture will be rendered completely over the entire window area), and finally SDL_RenderPresent.
If you need to render in window the frame respecting the aspect ratio, get the current window size with SDL_GetWindowSize and calculate the target area taking into account the aspect ratio of the back buffer texture and the window proportions (portrait and landscape). However, before rendering the back buffer texture in the window, first clean the window with SDL_RenderClear so that the remaining areas of the window (black bars) are filled with black.
|
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, finish;
cout << "Enter range start" << endl;
cin >> start;
cout << "Enter the range end" << endl;
cin >> finish;
if (start < finish)
{
for (int i = start; i <= finish; i++)
{
cout << "Number " << i << " is divisible by ";
for (int j = 2; j <= 10; j++)
{
if (i % j == 0)
{
cout << j << " ";
}
}
cout << endl;
}
}
return 0;
}
And the output I get is:
Number i is divisible by j1, j2 and etc.
Number i is divisible by
Number i is divisible by j1, j2 and etc.
You get the idea.
What I'm trying to get is this
Number i is divisible by j1, j2 and etc.
Number i isn't divisible by any numbers
Number i is divisible by j1, j2 and etc.
I tried doing this:
#include <iostream>
using namespace std;
int main()
{
int start, finish;
cout << "Enter range start" << endl;
cin >> start;
cout << "Enter the range end" << endl;
cin >> finish;
if (start < finish)
{
for (int i = start; i <= finish; i++)
{
cout << "Number " << i;
for (int j = 2; j <= 10; j++)
{
if (i % j == 0)
{
cout << " is divisible by " << j << " ";
}
else
{
cout << " isn't divisible by any numbers";
}
}
cout << endl;
}
}
return 0;
}
But the output is just a mess. Sorry if this is something straight forward and something I could've looked up on the net, but I just didn't know how to phrase my problem correctly and what to look for. I'll appreciate any help.
| 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;
cin >> finish;
if (start < finish)
{
for (int i = start; i <= finish; i++)
{
cout << "Number " << i;
bool divisorFound = false;
for (int j = 2; j <= 10; j++)
{
if (i % j == 0)
{
if (!divisorFound)
{
cout << " is divisible by ";
}
cout << j << " ";
divisorFound = true;
}
}
if (!divisorFound)
{
cout << " isn't divisible by any numbers";
}
cout << endl;
}
}
return 0;
}
|
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(Tuple&& tuple)
{
std::cout << "item " << I << "=" << std::get<I>(tuple) << '\n';
if constexpr (I + 1 < std::tuple_size_v<std::decay_t<Tuple>>)
foo<I+1>(tuple);
}
template<typename... Ts>
void bar(Ts... ts)
{
foo<0>(std::tuple(ts...));
}
int main()
{
bar(5, 3.14, "hello world", 'c');
return 0;
}
This works as expected:
item 0=5
item 1=3.14
item 2=hello world
item 3=c
Is it possible to achieve the same result using std::index_sequence and a template fold expression?
| 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) {
bar2(std::make_index_sequence<sizeof...(Ts)>(), std::forward<Ts>(ts)...);
}
Demo
|
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, nullptr);
//write to IStream
IStream* istream = nullptr;
if (CreateStreamOnHGlobal(NULL, TRUE, &istream) != 0)
return false;
CLSID clsid_png;
if (CLSIDFromString(L"{557cf406-1a04-11d3-9a73-0000f81ef32e}", &clsid_png)!=0)
return false;
Gdiplus::Status status = bmp.Save(istream, &clsid_png);
if (status != Gdiplus::Status::Ok)
return false;
//get memory handle associated with istream
HGLOBAL hg = NULL;
if (GetHGlobalFromStream(istream, &hg) != S_OK)
return 0;
//copy IStream to buffer
int bufsize = GlobalSize(hg);
data.resize(bufsize);
//lock & unlock memory
LPVOID pimage = GlobalLock(hg);
if (!pimage)
return false;
memcpy(&data[0], pimage, bufsize);
GlobalUnlock(hg);
istream->Release();
return true;
}
int main()
{
CoInitialize(NULL);
ULONG_PTR token;
Gdiplus::GdiplusStartupInput tmp;
Gdiplus::GdiplusStartup(&token, &tmp, NULL);
//take screenshot
RECT rc;
GetClientRect(GetDesktopWindow(), &rc);
auto hdc = GetDC(0);
auto memdc = CreateCompatibleDC(hdc);
auto hbitmap = CreateCompatibleBitmap(hdc, rc.right, rc.bottom);
auto oldbmp = SelectObject(memdc, hbitmap);
BitBlt(memdc, 0, 0, rc.right, rc.bottom, hdc, 0, 0, SRCCOPY);
SelectObject(memdc, oldbmp);
DeleteDC(memdc);
ReleaseDC(0, hdc);
//save as png
std::vector<BYTE> data;
if(save_png_memory(hbitmap, data))
{
//write from memory to file for testing:
std::ofstream fout("test.png", std::ios::binary);
fout.write((char*)data.data(), data.size());
}
DeleteObject(hbitmap);
Gdiplus::GdiplusShutdown(token);
CoUninitialize();
return 0;
}
Question
How can prepare that byte data (std::vector data;) to pass it through dart ffi to work with it in flutter?
Please anyway possible will be accepted.
My biggest confussion is ffi doesn't have a coresponding byte data type, so how should I go by it?
| 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 the storage (array of bytes) that the pointer will reference. You can either malloc (and subsequently free) the bytes on the C side, or malloc.allocate<Uint8>() (and subsequently malloc.free()) them on the Dart side.
Then, on the C side you already have sample code in your snippet for copying the std::vector<BYTE> into the pointee buffer:
memcpy(&data[0], the_pointer, bufsize);
copies bufsize bytes from data to the buffer pointed to by the pointer. (Alternatively, you could just assign &data[0] to the pointer as long as you know data won't go out of scope - and you free it after you use it).
Once you have the Pointer<Uint8> on the Dart side, just call asTypedList to get a Uint8List that allows you to access the bytes on the Dart side.
Also, remember that Dart FFI is a C interface, so if you want to use C++ classes you will need to wrap them in C methods. See: Can I call a C++ constructor function in dart ffi? Those C methods can/should be in C++ source files as long as they are marked extern "C".
|
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 elements
if they don't have same elements they are not cyclic permutation
if they have same elements, first element of first vector move to the end of vector and then make temp vector of first two elements of first vector, find that temp vector in second vector and shift is equal to b.size() - i + 1;
For example I get following error
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 15) >= this->size()
(which is 15)
and if I try other sequences result is not correct.
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstdlib>
int sequences_are_equal = 0;
bool sequences_have_same_elements(std::vector < int > a, std::vector < int > b) {
sequences_are_equal = 0;
if (a.size() != b.size())
return false;
for (int i = 0; i < a.size(); i++)
if (a.at(i) == b.at(i))
sequences_are_equal++;
if (sequences_are_equal == a.size()) return true;
sort(a.begin(), a.end());
sort(b.begin(), b.end());
for (int i = 0; i < a.size(); i++)
if (a.at(i) != b.at(i))
return false;
return true;
}
int CyclicPermutation(std::vector < int > a, std::vector < int > b) {
int shift = -1;
std::vector < int > temp(a.size(), 0);
std::vector < int > help(a.size(), 0);
if (sequences_have_same_elements(a, b)) {
int x = a.at(0);
a.erase(a.begin());
a.push_back(x);
temp.push_back(a.at(0));
temp.push_back(a.at(1));
for (int i = 0; i < b.size(); i++) {
help.push_back(b.at(i));
help.push_back(b.at(i + 1));
if (temp == help) {
shift = b.size() - i + 1;
break;
}
help.clear();
}
}
if (sequences_are_equal == a.size()) return 0;
return shift;
}
int main() {
int x;
std::vector < int > a, b;
std::cout << "First sequence: ";
while (std::cin >> x)
a.push_back(x);
std::cin.clear();
std::cin.ignore(1000, '\n');
std::cout << "Second sequence: ";
while (std::cin >> x)
b.push_back(x);
if (CyclicPermutation(a, b) == -1)
std::cout << "Second sequence is not cyclic permutaion of first.";
else
std::cout << "Second sequence is cyclic permutaion of first with shift " << CyclicPermutation(a, b) << ".";
return 0;
}
Could you explain me where did I make mistake in my algorithm and code? How to modify this to work correct?
| 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. So, if for example the original vector size is 4, then your vectors will be 0,0,0,0,x,y.
That is rather strange, or, I do not understand it.
What you should do:
Check, if the size of the 2 vectors is equal
Check, if the vectors are equal using the existing == operator
Rotate the vectors elements for mx "size" times. Count the number of rotations
Go back to 2
You can either use the existing function std::rotate(see here) or write a simple function by yourself.
You could modify your function like this:
#include <iostream>
#include <algorithm>
#include <vector>
#include <limits>
void rotateLeft(std::vector<int>& a) {
if (a.size() > 0) {
int tmp = a[0];
for (size_t k{}; k < a.size() - 1; ++k)
a[k] = a[k + 1];
a.back() = tmp;
}
}
int CyclicPermutation(std::vector<int>& a, std::vector<int>& b) {
// Set result to invalid
int result{ -1 };
int shiftCounter{};
// Only do something if the sizes are different
if (a.size() == b.size()) {
// Rotate until numbers are equal
while ((a != b) and (shiftCounter++ < a.size())) {
//std::rotate(a.begin(), a.begin() + 1, a.end());
rotateLeft(a);
}
if (shiftCounter < a.size())
result = shiftCounter;
}
return result;
}
int main() {
int x;
std::vector < int > a, b;
std::cout << "First sequence: ";
while (std::cin >> x)
a.push_back(x);
std::cin.clear();
std::cin.ignore(1000, '\n');
std::cout << "Second sequence: ";
while (std::cin >> x)
b.push_back(x);
int result = CyclicPermutation(a, b);
if (result < 0)
std::cout << "Second sequence is not cyclic permutaion of first.";
else
std::cout << "Second sequence is cyclic permutaion of first with shift " << result << ".";
return 0;
}
Edit:
It works, see:
#include <iostream>
#include <algorithm>
#include <vector>
#include <limits>
void rotateLeft(std::vector<int>& a) {
if (a.size() > 0) {
int tmp = a[0];
for (size_t k{}; k < a.size() - 1; ++k)
a[k] = a[k + 1];
a.back() = tmp;
}
}
int CyclicPermutation(std::vector<int>& a, std::vector<int>& b) {
// Set result to invalid
int result{ -1 };
int shiftCounter{};
// Only do something if the sizes are different
if (a.size() == b.size()) {
// Rotate until numbers are equal
while ((a != b) and (shiftCounter++ < a.size())) {
//std::rotate(a.begin(), a.begin() + 1, a.end());
rotateLeft(a);
}
if (shiftCounter < a.size())
result = shiftCounter;
}
return result;
}
int main() {
int x;
std::vector a{ 3, 5, 1, 2, 4, 3, 5, 7, 8, 1, 2, 5, 9, 4, 7 };
std::vector b{ 5, 7, 8, 1, 2, 5, 9, 4, 7, 3, 5, 1, 2, 4, 3 };
int result = CyclicPermutation(a, b);
if (result < 0)
std::cout << "Second sequence is not cyclic permutaion of first.";
else
std::cout << "Second sequence is cyclic permutaion of first with shift " << result << ".";
return 0;
}
You input routine is not good that. You should know, that ignore is a unformatted input function
Edit 2
Your input works, with the original function:
|
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 it is very easy, or rather hard to avoid.
In essence, I have the following (simplified) code:
#include <iostream>
using namespace std;
struct Foo {
int v;
Foo() {
cerr << "Foo default constructor with v = " << v << ".\n";
}
Foo(int newV) : v(newV) {
cerr << "Foo constructor with v = " << v << ".\n";
}
~Foo() {
cerr << "Foo destructor with v = " << v << ".\n";
}
};
int main()
{
Foo foo;
try {
foo = Foo(3);
} catch (...) {
// handle exception
}
}
which yields the following output:
Foo default constructor with v = 0.
Foo constructor with v = 3.
Foo destructor with v = 3.
Foo destructor with v = 3.
This is a problem for me, because Foo has been destroyed twice with the value 3. Once, at the end of the program, and once after exiting the try block after an assignment operation.
My question is: can I instantiate an object by destroying its default value and constructing it in-place, instead of constructing another object and performing an assignment?
Of course, there are workarounds like using new, but I do not want to be forced to dereference an object everywhere and also I want to make sure it gets destroyed in case of an error (although of course for that I could use some pointer wrapper). I also do not want to use some separate C-style initialization method because I consider that ugly. I also have other members inside my "Foo" class, so I would need to perform some sort of destruction during assignment, which is inconvenient. Ideally, I'd love to see something akin to
Foo foo;
try {
Foo foo(3);
} catch (...) {
// handle exception
}
but I cannot do that because that leads to a redeclaration, or rather a shadow-declaration and on top of that, the more-local Foo object will be destroyed anyway.
| 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, this method will be called and it will simply swap the values in the v members. The other object will be immediately destroyed, but with the "old" value of v.
Take care to assign some meaningless value to v by default, perhaps -1.
Now, the output of the program is
Foo default constructor with v = 0.
Foo constructor with v = 3.
Foo destructor with v = 0.
Foo destructor with v = 3.
which is exactly what I was looking for.
|
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::string str = "hello";
auto s = std::move(str);
str.find("world");
}
| 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_view<charT, traits> s = *this, sv = t;
return s.G(sv, pos);
which will construct basic_string_view from *this, which has preconditions that [str, str + len) is a valid range, and since the moved string is still in a valid state, so this is OK.
|
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::iterator start, type::iterator after_end) {
int n = 0;
while (start < after_end) {
start++;
n++;
}
start -= n;
type *arr = nullptr;
arr = new type[n];
throw std::bad_alloc("Not enough memory!");
while (start < after_end) {
*arr = *start;
start++;
arr++;
}
delete[] arr;
arr-=n;
return arr;
}
int main() {
int n=5;
std::vector<double>a{1,2,3,4,5};
double *arr = nullptr;
try {
arr = MakeArray(a.begin(),a.end());
} catch (std::bad_alloc e) {
std::cout << "Exception: " << e.what();
}
delete[] arr;
return 0;
}
ERRORS:
line 5:
expected ‘)’ before ‘after_end’
expected ‘;’ before ‘{’ token
line 30:
missing template arguments before ‘(’ token
I don't see any reason why should I get these errors. Could you help me to fix my code? Iterators and dynamic allocation are new to me.
| 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 able to use it in the calling module.
There are also some significant other simplifications and improvements you can make to your function, which I have shown in the below code:
template <typename it_type>
auto* MakeArray(it_type start, it_type after_end)
{
using basetype = typename std::decay< decltype(*start) >::type; // Type of contained objects
size_t size = static_cast<size_t>(std::distance(start, after_end)); // Quick calculation of size
basetype* arr = new basetype[size]; // This will automatically throw (bad_alloc) if it fails
std::copy(start, after_end, arr); // Quicker/easier way to do the data copy
return arr;
}
|
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)
{
std::cout << "default template method has been called" << std::endl << std::endl;
}
template<typename T, size_t N>
void Foo(const std::array<T,N>& var)
{
std::cout << "Array overload has been called" << std::endl;
for(auto& elem : var)
{
Foo(elem);
}
}
template<typename T>
void Foo(const A::Bar<T>& var)
{
std::cout << "Bar overload has been called" << std::endl << std::endl;
}
}
int main()
{
int VarInt;
A::Bar<int> VarBar;
std::array<int, 1> ArrayInt;
std::array<A::Bar<int>, 1> ArrayBar;
B::Foo(VarInt);
B::Foo(VarBar);
B::Foo(ArrayInt);
B::Foo(ArrayBar);
return 0;
}
It's output is not what i expect as with the array of Bar, the default template is called instead of the Bar overload:
default template method has been called
Bar overload has been called
Array overload has been called
default template method has been called
Array overload has been called
default template method has been called
I noticed that doing the folowing enables the compiler to find the correct overloads :
removing all namespaces or
declaring all the templates prototypes before implementing them
|
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 expression Foo(elem) is encountered, the compiler doesn't know about the third overloaded Foo. Thus it chooses the first overload of Foo which is the most general among the two available at that point.
declaring all the templates prototypes before implementing them
Providing the declarations for all the overloads of Foo before implementing them, lets the compiler know that there is a third overload of Foo. So this time, the call expression Foo(elem) calls the third overloaded Foo as expected(because it is more special than the first overload of Foo).
removing all namespaces
And when everything is put in the same global namespace, due to ADL the third overload is also found.
|
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> file_template = ObjectTemplate::New(isolate);
file_template->Set(isolate, "read",
FunctionTemplate::New(isolate, Shell::ReadFile));
d8_template->Set(isolate, "file", file_template);
global_template->Set(isolate, "d8", d8_template);
Local<Context> context = Context::New(isolate, nullptr, global_template);
That snippet results in a function d8.file.read(...) being available.
|
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>
#include <string>
#include <vector>
using namespace std;
class Player
{
private:
string PlayerName;
int PlayerScore;
public:
Player();
Player(string name, int s);
~Player() {};
string getPlayerName() {return PlayerName;}
int getPlayerScore() {return PlayerScore;}
void setPlayerName(string name){PlayerName = name;}
void setPlayerScore(int score){PlayerScore = score;}
};
class Game
{
private:
Player NewPlayer;
int NPlayers;
Player* PlayerList;
//vector <Player> PlayerList2;
public:
Game();
~Game();
void setNewPlayer(string, int);
void resizePlayerList();
void PrintList();
};
The class file:
#include <iostream>
#include <string>
#include <cstring>
#include <memory>
#include "I.h"
using namespace std;
Player::Player()
{
PlayerName = "";
PlayerScore = 0;
}
Player::Player(string name, int s)
{
PlayerName = name;
PlayerScore = s;
}
Game::Game()
{
NPlayers = 0;
PlayerList = NULL;
};
Game::~Game() {};
void Game::setNewPlayer(string str, int scr)
{
NewPlayer = Player(str, scr);
resizePlayerList();
PrintList();
}
void Game::resizePlayerList() {
if(NewPlayer.getPlayerName() != "No Name")
{
int newSize = NPlayers +1;
Player* newArr = NULL;
newArr = new Player[newSize];
memcpy( newArr, PlayerList, NPlayers * sizeof(Player) );
NPlayers = newSize;
delete [] PlayerList;
PlayerList = newArr;
PlayerList[NPlayers-1] = NewPlayer;
}
}
void Game::PrintList()
{
Player player;
//cout << NPlayers << endl;
for(int i= 0; i < NPlayers; i++)
{
player = PlayerList[i];
cout << player.getPlayerName() << " " << player.getPlayerScore() << endl;
}
}
The main:
#include <iostream>
#include <string>
#include "I.h"
using namespace std;
int main()
{
Game NewGame;
NewGame.setNewPlayer("Peter",20);
NewGame.setNewPlayer("Someone Someone",30);
NewGame.setNewPlayer("Someone else",40);
return 0;
}
| 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 data instead:
for (int i = 0; i < NPlayers; ++i) {
newArr[i] = std::move(PlayerList[i]);
}
The better option though, is to use a std::vector<Player>, then the entire resize function can be simplified to:
void Game::resizePlayerList() {
if (NewPlayer.getPlayerName() != "No Name") {
PlayerList.push_back(std::move(NewPlayer));
}
}
|
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 being stopped/terminated so it can cleanup resources (closing files)?
| 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 slow so if possible suggest a sorting algorithm.)
This is the fastest way that I've been able to do:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int Maksimumas(int n, int X[]);
ofstream fr("U1rez.txt");
ifstream fd("U1.txt");
int main()
{
int n, A[100000], B[100000], maxi=0;
fd >> n;
for (int i = 0; i < n; i++) {
fd >> A[i];
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
B[j] = A[i] * A[j];
}
maxi = Maksimumas(n, B);
A[i] = B[maxi];
}
maxi = Maksimumas(n, A);
fr << A[maxi];
fr.close();
return 0;
}
int Maksimumas(int n, int X[])
{
int maxi = 0;
for (int i = 0; i < n; i++) {
if (X[maxi] < X[i]) {
maxi = i;
}
}
return maxi;
}
n is the size of the array for anyone wondering.
| 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 iteration, multiply each pair (if found), and compare the results.
// fd is opened like the original question, n is the number of elements to read
// that part is omitted for brevity
int max = -1;
int preMax = -1;
int min = 1;
int preMin = 1;
int temp;
for (int i = 0; i < n; i++) {
fd >> temp;
if (temp > preMax) {
if (temp > max) {
preMax = max;
max = temp;
} else {
preMax = temp;
}
} else if (temp < preMin) {
if (temp < min) {
preMin = min;
min = temp;
} else {
preMin = temp;
}
}
}
int result = -1;
if (preMax >= 0) {
result = preMax * max;
}
if (preMin <= 0) {
int tempResult = preMin * min;
if (tempResult > result) {
result = tempResult;
}
}
return result;
|
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 overloaded operator)
void Money::division(double i)
{
money_number = money_number / i;
}
Money& Money::operator/(double i)
{
division(i);
return *this;
}
(3.This is my call to it in the main function)
Money money_temp=100;
Money mmm = 0;
cout <<"mmm" << money_temp << endl;
mmm = money_temp / 2;
cout << "mmm" << money_temp << endl;
But I found that in the end “money_temp” changed after division.
it became 50 from 100.
I try to delete the "&" in the "Money& operator/(double);" , but I failed.
How to resolve this problem? Thanks for your kind help.
| 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 temp;
}
Note that I deleted the & because it would lead to a dangling reference otherwise.
|
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.txt")), except that instead of assignment_operator it's spelled operator=. (Note that in this case, the value which is passed to the member function is a temporary value, and is destroyed after the function returns. That doesn't necessarily imply anything specific about what happens with opening and closing files; it's just how the language works.)
A global variable exists throughout the entire life of the program; the precise semantics during startup and shutdown are a little tricky, but certainly during the "main phase" they always exist. The design of ofstream may put s into a different sort of state when s.close() is called, but that's entirely down to the design of ofstream, and is something that you'd discover by reading the documentation of that class rather than by reading the rules of the language.
|
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 to sort the queue or to just set the order in the declaration?
I'm trying to do:
priority_queue<pair<int, int>> queue;
for(int i=0; i<n; i++){
cin>>t>>d;
queue.push(make_pair(t, d));
}
| 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 actually output last. That is, the front of the queue contains the "last" element according to the weak ordering imposed by Compare.
You could use std::greater<pair<int,int>> as custom comparator or your own comparator as well to have a custom ordering. This will put the smallest element at the front of the queue.
priority_queue<pair<int, int>, std::vector<pair<int,int>>, std::greater<pair<int,int>>> q;
|
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);
CVector result;
result = foo - bar;
cout << result.x << ',' << result.y << endl;
}
Code 2:
class CVector {
public:
int x, y;
CVector() {};
CVector(int a, int b) :x(a), y(b) {}
};
CVector operator- (const CVector& lhs, const CVector& rhs)
{
return CVector(lhs.x - rhs.x, lhs.y - rhs.y);
}
int main()
{
CVector foo(2, 3);
CVector bar(3, 2);
CVector result;
result = foo - bar;
cout << result.x << ',' << result.y << endl;
}
These two pieces of code operate identically. I want to know 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?
|
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. Just like CVector foo(2, 3); and CVector bar(3, 2) uses the parameterized constructor, the expression CVector(lhs.x - rhs.x, lhs.y - rhs.y) also uses the parameterized ctor.
You can confirm this by adding a cout inside the parameterized constructor as shown below:
#include <iostream>
class CVector {
public:
int x, y;
CVector() {};
CVector(int a, int b) :x(a), y(b) {
std::cout<<"paremterized ctor used"<<std::endl;
}
};
CVector operator- (const CVector& lhs, const CVector& rhs)
{
return CVector(lhs.x - rhs.x, lhs.y - rhs.y); //this uses the parameterized ctor
}
int main()
{
CVector foo(2, 3);
CVector bar(3, 2);
CVector result;
result = foo - bar;
std::cout << result.x << ',' << result.y << std::endl;
}
The output of the above program is:
paremterized ctor used
paremterized ctor used
paremterized ctor used
-1,1
Notice in the output shown above, the third call to the parameterized ctor is due to the return statement return CVector(lhs.x - rhs.x, 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 function.
I use the GPShell (the commandline tool that uses the same library) source code as a reference to help me translate the functions. There i found the convertStringToByteArray function, which takes a string and converts it to a array of Bytes.
The original C++ function:
static int convertStringToByteArray(TCHAR *src, int destLength, BYTE *dest)
{
TCHAR *dummy;
unsigned int temp, i = 0;
dummy = malloc(destLength*2*sizeof(TCHAR) + sizeof(TCHAR));
_tcsncpy(dummy, src, destLength*2+1);
dummy[destLength*2] = _T('\0');
while (_stscanf(&(dummy[i*2]), _T("%02x"), &temp) > 0)
{
dest[i] = (BYTE)temp;
i++;
}
free(dummy);
return i;
}
and i tried to write a similar procedure in Delphi, i tried to convert the string in two ways - the first (Literally) converts every character (treated as HEX) to integer. The second way uses Move:
procedure StrToByteArray(Input: AnsiString; var Bytes: array of Byte; Literally: Boolean = false);
var
I, B : Integer;
begin
if Literally then
begin
for I := 0 to Length(Input) -1 do
if TryStrToInt('$' + Input[I +1], B) then
Bytes[I] := Byte(B)
else
Bytes[I] := Byte(0);
end else
Move(Input[1], Bytes[0], Length(Input));
end;
But i keep getting a
(6A82: The application to be selected could not be found.)
error, when i try to select AID
A000000003000000
I know i am trying to select the right AID, because when i use this same AID with GPShell - i get a successful response. So i am not sure if the problem is in my String to Byte array procedure, or maybe somewhere else.
When i use breakpoints, and i try to convert the string to bytes literally i get
(10, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0)
in the debugger. But when i try with Move (or ORD) i get
(65, 48, 48, 48, 48, 48, 48, 48, 48, 51, 48, 48, 48, 48, 48, 48)
I also tried to convert the string to bytes online with various websites, and these give me another result
(41, 30, 30, 30, 30, 30, 30, 30, 30, 33, 30, 30, 30, 30, 30, 30)
So i am a bit lost in trying to find out what im doing wrong, is the problem in my string to bytes conversion - or do i need to look somewhere else?
| 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; Literally: Boolean = false);
var
I, B : Integer;
begin
if Literally then
begin
SetLength(Bytes, Length(Input) div 2);
for I := 0 to Length(Bytes)-1 do
begin
if not TryStrToInt('$' + Copy(Input, (I*2)+1, 2), B) then
B := 0;
Bytes[I] := Byte(B);
end;
end else
begin
SetLength(Bytes, Length(Input));
Move(Input[1], Bytes[0], Length(Input));
end:
end;
That being said, Delphi has its own HexToBin() functions for parsing hex strings into byte arrays. You don't need to write your own parser, eg:
procedure StrToByteArray(Input: AnsiString; var Bytes: TBytes; Literally: Boolean = false);
begin
if Literally then
begin
SetLength(Bytes, Length(Input) div 2);
HexToBin(PAnsiChar(Input), PByte(Bytes), Length(Bytes));
end else
begin
SetLength(Bytes, Length(Input));
Move(Input[1], Bytes[0], Length(Input));
end:
end;
|
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");
dim3 gdim(1,1,1);
dim3 bdim(4,4,4);
foo<<<gdim, bdim>>>();
}
main.cpp
#include <iostream>
#include <cuda_runtime_api.h>
#include "a.h"
using namespace std;
int main() {
warperFoo();
return 0;
}
makefile
.PHONY: clean
all: a.o
g++ -m64 -Wall a.o main.cpp -lcudart -L/usr/local/cuda-11.2/lib64/ -I/usr/local/cuda-11.2/include -lcudadevrt -lcuda
a.o:
nvcc --gpu-architecture=sm_70 -ccbin /usr/bin/gcc -c a.cu
clean:
rm -rf *.o a.out
make output
nvcc --gpu-architecture=sm_70 -ccbin /usr/bin/gcc -c a.cu
g++ -m64 -Wall a.o main.cpp -lcudart -L/usr/local/cuda-11.2/lib64/ -I/usr/local/cuda-11.2/include -lcudadevrt -lcuda
a.out output
calling from warperFoo
i want compile .cu with nvcc first and then compile c++ host code with g++.
it supposed to print "calling from kernel foo"...
SO why kernel didn't output?
| 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 << search_ch_upper << " found!\n";
}
}
}
int main() {
std::string word = "substring";
std::cout << word << '\n';
FindCharInString(word, 's');
return 0;
}
Output:
substring
S found!
S found!
|
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 things you will need as instructed on the ccls wiki.
Firstly I used git clone --depth=1 --recursive https://github.com/MaskRay/ccls to clone the repo into a folder.
Secondly I went into the ccls folder and used cmake .. Which built the required things.
Thirdly I the used the make command to fully build the repo and generate the ccls executable.
Then I created a bin directory in the home directory and moved the ccls executable into it.
Then I went into the .bashrc to add ccls to the system path and added the line export PATH="/home/$USER/bin:$PATH" to the final line of the bashrc. Then exited the file and used source ~/.bashrc to force a reset
Finally I added the ccls language server settings to the coc config:
{
"languageserver": {
"ccls": {
"command": "ccls",
"filetypes": ["c", "cpp", "cuda", "objc", "objcpp"],
"rootPatterns": [".ccls-root", "compile_commands.json"],
"initializationOptions": {
"cache": {
"directory": ".ccls-cache"
},
"client": {
"snippetSupport": true
}
}
}
}
}
Alternatively you can (if you are using coc) use CocInstall coc-clangd in vim or nvim, which is a way you can get something similar to ccls for programming.
|
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>
class Foo
{
std::vector<std::variant<std::monostate//work for empty parameter pack,Args...>> partargs;
}
But that makes things a lot harder for me in the future so I was wondering if there was a better solution?
| 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>
struct ignore_first<0, First, Args...> {
using type = std::tuple<First, Args...>;
};
template<std::size_t N>
struct ignore_first<N> {
using type = std::tuple<>;
};
static_assert(std::is_same_v<
ignore_first<0, int, long, char>::type, std::tuple<int, long, char>>);
static_assert(std::is_same_v<
ignore_first<1, int, long, char>::type, std::tuple<long, char>>);
static_assert(std::is_same_v<
ignore_first<2, int, long, char>::type, std::tuple<char>>);
static_assert(std::is_same_v<
ignore_first<3, int, long, char>::type, std::tuple<>>);
Demo
|
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 close to solution but the problem is that if one vector is shorter than another, then program will print '0'.
Problem output:
1 20 4 30 9 0 16 0
Here is the code I tried to solve this problem
merge_vect(first_v, second_v);
vector<int> merge_vect(const vector<int> & a, const vector<int> & b){
vector<int> vec(a.size() + b.size());
for (int i = 0; i < vec.size(); i++){
cout << a[i] << " ";
cout << b[i] << " ";
}
return vec;
}
What can I do in order to solve this problem?
| 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.reserve(avec.size() + bvec.size());
for(auto ait = avec.begin(), bit = bvec.begin();
ait != avec.end() || bit != bvec.end();)
{
if(ait != avec.end()) result.push_back(*ait++);
if(bit != bvec.end()) result.push_back(*bit++);
}
return result;
}
int main() {
std::vector<int> first_v = {1, 4, 9, 16, 8, 56};
std::vector<int> second_v = {20, 30};
auto result = merge_vect(first_v, second_v);
for(auto val : result) std::cout << val << ' ';
}
Output:
1 20 4 30 9 16 8 56
A possible optimization could copy from both vectors for as long as both have elements and then copy the rest from the larger vector in one go:
std::vector<int> merge_vect(const std::vector<int>& avec,
const std::vector<int>& bvec)
{
std::vector<int> result;
result.reserve(avec.size() + bvec.size());
auto ait = avec.begin(), bit = bvec.begin();
// copy while both have more elements:
for(; ait != avec.end() && bit != bvec.end(); ++ait, ++bit) {
result.push_back(*ait);
result.push_back(*bit);
}
// copy the rest
if(ait != avec.end()) result.insert(result.end(), ait, avec.end());
else if(bit != bvec.end()) result.insert(result.end(), bit, bvec.end());
return 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.png" ;
const int width = 800 ;
const int height = 800 ;
bool anti_aliasing = true ;
bool FPS_60_CAP = true ;
bool movable = false ;
Core::Base::MVP mvp;
int a = 32;
void key_callback(GLFWwindow *window, int key, int scancode, int action, int mods)
{
if (action == GLFW_PRESS) { a += 1; }
info(a);
}
double mouseX, mouseY;
double pmouseX, pmouseY;
glm::vec2 t(0);
void mouse(GLFWwindow * window) {
pmouseX = mouseX;
pmouseY = mouseY;
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
mouseX = xpos;
mouseY = height - ypos;
if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) && movable) {
t.x += mouseX - pmouseX;
t.y += mouseY - pmouseY;
mvp.translate(0, t);
}
}
void App::run()
{
Core::Window window(true, anti_aliasing);
window.make_Window(glfwCreateWindow(width, height, name.c_str(), NULL, NULL), key_callback, icon);
srand(time(NULL));
mvp.view = glm::ortho(0.0f, (float)width, 0.0f, (float)height);
Core::Renderer renderer;
Core::Player player;
// 1. TODO: Implement Text
// 2. TODO: Implement UI
FT_Library ft;
FT_Error err = FT_Init_FreeType(&ft);
if (err != 0) {
printf("Failed to initialize FreeType\n");
exit(EXIT_FAILURE);
}
FT_Int major, minor, patch;
FT_Library_Version(ft, &major, &minor, &patch);
printf("FreeType's version is %d.%d.%d\n", major, minor, patch);
FT_Face face;
err = FT_New_Face(ft, "data/fonts/arial.ttf", 0, &face);
if (err != 0) {
printf("Failed to load face\n");
exit(EXIT_FAILURE);
}
while (!glfwWindowShouldClose(window.window))
{
glClearColor(background_col[0], background_col[1], background_col[2], background_col[3]);
glClear(GL_COLOR_BUFFER_BIT);
// mouse(window.window);
// renderer.Render({ Core::Draw::Ellipse({400, 400, {1,0,1,1}}, 100, 75, true) }, mvp);
err = FT_Set_Pixel_Sizes(face, 0, a);
if (err != 0) {
printf("Failed to set pixel size\n");
exit(EXIT_FAILURE);
}
FT_UInt glyph_index = FT_Get_Char_Index(face, 'o');
FT_Int32 load_flags = FT_LOAD_DEFAULT;
err = FT_Load_Glyph(face, glyph_index, load_flags);
if (err != 0) {
printf("Failed to load glyph\n");
exit(EXIT_FAILURE);
}
err = FT_Render_Glyph(face->glyph, FT_RENDER_MODE_NORMAL);
if (err != 0) {
printf("Failed to render the glyph\n");
exit(EXIT_FAILURE);
}
glDrawPixels( face->glyph->bitmap.width, face->glyph->bitmap.rows, GL_ALPHA, GL_UNSIGNED_BYTE, face->glyph->bitmap.buffer);
Core::viewport(window.window);
glfwSwapBuffers(window.window);
glfwSwapInterval(FPS_60_CAP);
glfwPollEvents();
}
alcCloseDevice(player.Device);
window.~Window();
}
here is an example of what i mean:
Error
It renders correctly sometimes but when you change the font size it gets messed up.
| 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.rows, GL_ALPHA, GL_UNSIGNED_BYTE, face->glyph->bitmap.buffer);
|
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 type as well, since just an int type would not be enough for huge numbers. I kept getting a random huge number as the output whenever I tried to run the program :
#include <iostream>
#include <vector>
using namespace std;
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 (numbers[j] > numbers[max2] && j!=max1)
max2 = j;
}
return ((long long)(numbers[max1])) * ((long long)(numbers[max2]));
}
int main(){
int n;
cin >> n;
vector<int> numbers(n);
for (int i = 0; i<n; i++){
cin >> numbers[i];
}
long long result = max_prod(numbers);
cout << result << "\n";
return 0;
}
the last line is the output given by the program
| 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 (numbers[j] > numbers[max2] && j != max1)
max2 = j;
}
return ((long long)(numbers[max1])) * ((long long)(numbers[max2]));
}
You try to access numbers[-1] (twice once in the j loop and once in the i loop).
Set maxi and maxj to 0
|
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
Here is my code:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
std::vector<std::string> readf(std::string filename)
{
std::ifstream file(filename);
file.open(filename);
// Check if file is open
if (!file.is_open())
{
std::cout << "Error opening file: " << filename << std::endl;
exit(EXIT_FAILURE);
}
std::vector<std::string> lines;
std::string line;
// Read the file
while (std::getline(file, line))
{
if (line.size() > 0)
lines.push_back(line);
}
return lines;
}
| 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 between using fstream constructor and open function.
|
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 constructor is templated
// (rather than just accepting A<T>) is because there are other constructors
// that should be preferred when both would be acceptable.
template <typename T>
struct B {
template <typename U,
typename = std::enable_if_t<std::is_convertible_v<U, A<T>>>>
B(U&& u);
};
// A struct that cna be implicitly converted to A<T> or B<T>.
struct C {
template <typename T>
operator A<T> ();
template <typename T>
operator B<T> ();
};
// Another struct that can be implicitly converted to A or B, but this time only
// a specific instantiation of those templates.
struct D {
operator A<int> ();
operator B<int> ();
};
// A function that attempts to implicitly convert from both C and D to B<int>.
void Foo() {
B<int> b_from_c = C{};
B<int> b_from_d = D{};
}
When I compile this with clang, it complains about the b_from_c initialization being ambiguous:
foo.cc:45:10: error: conversion from 'C' to 'B<int>' is ambiguous
B<int> b_from_c = C{};
^ ~~~
foo.cc:24:3: note: candidate constructor [with U = C, $1 = void]
B(U&& u);
^
foo.cc:33:3: note: candidate function [with T = int]
operator B<T> ();
^
This totally makes sense to me: there are two paths to convert from C to B<int>.
But the part that puzzles me is why clang doesn't complain about the b_from_d initialization. The only difference between the two is that the problematic one uses a templated conversion function and the accepted one doesn't. I assume this has something to do with ranking in the implicit conversion rules or the overload selection rules, but I can't quite put it together and also if anything I would have expected b_from_d to be rejected and b_from_c to be accepted.
Can someone help me understand, ideally with citations of the standard, why one of these is ambiguous and the other isn't?
| 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 is used) to a
derived class thereof are enumerated as described in 12.4.2.5, and the best one is chosen through
overload resolution (12.4). If the conversion cannot be done or is ambiguous, the initialization is
ill-formed. The function selected is called with the initializer expression as its argument; if the
function is a constructor, the call is a prvalue of the cv-unqualified version of the destination type
whose result object is initialized by the constructor. The call is used to direct-initialize, according
to the rules above, the object that is the destination of the copy-initialization.
According to 12.4.2.5 (12.4.1.4 in N4861)
[...] Assuming that "cv1 T" is the type of the object being initialized, with T a class type, the candidate functions
are selected as follows:
The converting constructors (11.4.8.2) of T are candidate functions.
When the type of the initializer expression is a class type "cv S", the non-explicit conversion functions of S and its base classes are considered. [...] Those that are not hidden within S and yield a type whose cv-unqualified version is the same type as T or is a derived class thereof are candidate functions. A call to a conversion function returning "reference to X" is a glvalue of type X, and such a conversion function is therefore considered to yield X for this process of selecting candidate functions.
In both cases, the argument list has one argument, which is the initializer expression.
The first bullet implies that the constructor B::B<D>(D&&) is a candidate function, which we'll call F2. The second bullet implies that D::operator B<int>() is a candidate function, which we'll call F1.
The first step to determine whether either F1 or F2 is better than the other is to determine the implicit conversion sequences involved ([over.match.best.general]/2 ([over.match.best]/2 in N4861)). To call F1, the implicit conversion sequence is from D{} to the implicit object parameter of D::operator B<int> (which is of type D&). This is an identity conversion ([over.ics.ref]/1). To call F2, the implicit conversion sequence is from D{} to the constructor's parameter type, D&&. This is also an identity conversion for the same reason.
Normally binding a D rvalue to an rvalue reference would be considered a better implicit conversion sequence than binding it to an lvalue reference; [over.ics.rank]/3.2.3. However, that rule is inapplicable in cases where either of the two bindings is to the implicit object parameter of a function that was declared without a ref-qualifier (as D::operator B<int>() was). The result is that neither of the two implicit conversion sequences is better than the other.
We then have to go through the tiebreaker rules in [over.match.best.general]/2 ([over.match.best]/2 in N4861). We can see that bullet 2.2 does not apply to our case since our context is [over.match.copy], and not [over.match.conv] nor [over.match.ref]. Similarly bullet 2.3 does not apply. This means 2.4 controls: F1 is not a function template specialization, and F2 is. The overload resolution succeeds, selecting F1.
In the case of b_from_c, none of the tiebreaker rules apply, and the overload resolution is ambiguous.
|
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 the absolute value.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<vector<string>> Board
{
{" ", " ", " "},
{" ", " ", " "},
{" ", " ", " "}
};
string playerInput;
bool hasMoved = false;
bool run = true;
while(run) {
//Prints Tic Tac Toe board to the screen
for(int h = 0; h < Board.size();h++){
cout << " ";
for(int d = 0; d < Board[h].size();d++){
cout << Board[h][d];
if(d < Board[h].size() - 1){ cout <<"||"; }
}
if(h < Board.size() - 1){ cout << "\n---------\n"; }
}
cout << "\n choose a number 1-9 to place an X: ";
cin >> playerInput;
hasMoved = false;
while(!hasMoved){
for(int h = 0; h < Board.size();h++){
for(int d = 0; d < Board[h].size();d++){
if(Board[h].size() * abs(h - Board[h].size() + 1) + d == playerInput && Board[h][d] == " ") {
Board[h][d] = "X";
hasMoved = true;
}
}
}
if(!hasMoved){
cout << "\n choose a number 1-9 to place an X: ";
cin >> playerInput;
}
}
}
}
| 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" zero. The result will be a very large number.
One way you can fix your equation is to cast the result to int:
abs(h - static_cast<int>(Board[h].size()) + 1)
But in this case, simply adjusting the equation to not wrap is better:
Board[h].size() - h - 1
|
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 because somebody said it's bad to acquire the address of a function provided by the standard library?
| 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 &std::hex, it evaluates to the address of the function. Same for &&std::hex, &&&&std::hex, etc. They all mean the same thing.
|
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
{
T datum;
Node* left;
Node* right;
};
// REQUIRES: node represents a valid tree
// MODIFIES: cout
// EFFECTS: Prints each element in the given tree to stanhdard out
// with each element followed by a space
void print(const Node *tree) {
if(tree) { // non-empty tree
cout << tree->datum << " ";
print(tree->left);
print(tree->right);
}
}
I am a beginner in C++, I was trying to learn basic Binary tree print, I don't know how to fix the red line under Node in void print(const Node *tree), I saw some people saying that convert the template T to int would fix the bug, but I don't know why that works.
| 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 Node<T>* tree) {
if (tree == nullptr) {
return;
}
print(tree->left);
cout << tree->datum << " ";
print(tree->right);
}
|
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 int[10];
}
~A() {
std::cout << ">>>> destructor >>>>" << std::endl;
delete[] a;
}
void set(int x) { a[0] = x; }
int get() const { return a[0]; }
private:
int* a;
};
int main() {
std::thread t1;
{
thread_local A t;
t1 = std::thread([]() {
t.set(1);
std::cout << t.get() << std::endl;
});
}
t1.join();
std::cout << ">>>> main >>>>" << std::endl;
}
Result:
>>>> constructor >>>>
Segmentation fault (core dumped)
| 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 initialises it's own copy of t and your code executes correctly:
thread_local A t;
int main() {
std::thread t1;
{
t1 = std::thread([]() {
t.set(1);
std::cout << t.get() << std::endl;
});
}
t1.join();
std::cout << ">>>> main >>>>" << std::endl;
}
Unrelated to your problem but you should make sure that your code obeys the rule of three and either delete or implement the copy constructor and assignment operator otherwise this code will have undefined behaviour as both objects will try to delete a:
A a1;
A a2 = a1;
|
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, ostream& os = cout) {
for (auto elem : r) {
os << elem << ' ';
}
os << '\n';
}
mt19937 gen(random_device{}());
template <typename F, ranges::forward_range R = vector<int>> requires regular_invocable<F, R>
void verify_sorting(F&& f, int num_trials = 1'000, int max_length = 1'000) {
uniform_int_distribution<> len_dist(0, max_length);
for (int i = 0; i < num_trials; ++i) {
R v;
int n = len_dist(gen);
generate_n(back_inserter(v), n, ref(gen));
f(v);
if (!ranges::is_sorted(v)) {
throw runtime_error("Sorting verification failed");
}
}
std::cout << "Sorting verification success!\n";
}
} // namespace frozenca
and I wrote an insertion sort code like this:
namespace frozenca {
using namespace std;
struct insertion_sort_func {
template <ranges::bidirectional_range R = vector<int>, typename F = ranges::greater>
constexpr void operator()(R&& r, F comp = {}) const {
if (ranges::empty(r)) return;
for (auto i = next(begin(r)); i != end(r); ++i) {
auto key = *i;
auto j = i;
while (j != begin(r) && comp(*prev(j), key)) {
iter_swap(prev(j), j);
--j;
}
*j = key;
}
}
};
inline constexpr insertion_sort_func insertion_sort{};
} // namespace frozenca
And here is my test code, which works nicely:
int main() {
namespace fc = frozenca;
std::vector<int> v{5, 2, 4, 6, 1, 3};
fc::insertion_sort(v);
fc::print(v); // outputs "1 2 3 4 5 6"
fc::verify_sorting(std::ranges::sort); // outputs "Sorting verification success!"
fc::verify_sorting(fc::insertion_sort); // outputs "Sorting verification success!"
}
My verify_sorting function tests the sorting function for type std::vector<int> by default. Of course it can test other std::ranges::forward_range, but it becomes extremely verbose. For testing std::vector<float>, what I checked working is like this:
fc::verify_sorting<decltype(fc::insertion_sort), std::vector<float>>
(std::forward<decltype(fc::insertion_sort)>(fc::insertion_sort));
// OK
This is way too verbose. Is there any less verbose way?
Running code: https://wandbox.org/permlink/4UPLxeJxDlOkXcN1
|
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::verify_sorting(fc::insertion_sort);
fc::verify_sorting<std::vector<float>>(fc::insertion_sort);
Demo
|
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));
will the implicitly synthesized move constructor just make this in y point to the memory that x is in? If so, how to ensure that x is destructible after the move (if x is destroyed, will members in y be valid)? if not, how does the move constructor of y work?
|
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 that x is destructible after the move
Since move is the same as copying for built in types, x and y are independent of each other. So when x is destroyed y will not be affected.
will the synthesized move constructor set the ptr of x to nullptr?
No, the synthesize move ctor will not do that for you. It will just memberwise move the data members. For built in types this means the same as copying.
if it does not do this, then the ptr of x will still point to the memory to which the ptr of y points, then you cannot safely destroy x.
In that case, you'd need to write a user-defined move ctor which explicitly sets the ptr of x to nullptr so that when x is destroyed, the y is not affected.
|
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 way to archieve the same (automatically generate operator==) but in C++17?
Since libraries are an okay solution I had a look at boost/operators. Would the following be the equivalent as the above?
#include <boost/operators.hpp>
struct Point : boost<equality_comparable<Point, Point>> {
int x;
int y;
bool operator==(const Point&) const; // will this get auto-generated too and do the same as above?
};
| 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
member type retrieval
methods for cooperation with std::tuple
methods to visit each field of the structure
Example using BOOST_PFR_FUNCTIONS_FOR:
Defines comparison and stream operators for T along with hash_value
function.
See Also : 'Three ways of getting operators' for other ways to define
operators and more details.
Live On Coliru
struct Point { int x, y; };
#include <boost/pfr.hpp>
BOOST_PFR_FUNCTIONS_FOR(Point)
#include <iostream>
#include <vector>
#include <set>
int main() {
std::vector pv { Point{1,2}, {2,1}, {-3,4}, {1,4/2}, {-3,-4} };
for(auto& p : pv) std::cout << p << " ";
std::cout << "\n";
std::set ps(begin(pv), end(pv));
for(auto& p : ps) std::cout << p << " ";
std::cout << "\n";
}
Prints
{1, 2} {2, 1} {-3, 4} {1, 2} {-3, -4}
{-3, -4} {-3, 4} {1, 2} {2, 1}
Using strictly c++14 (specifying vector<Point> and set<Point> template arguments).
|
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 In MainPage")
if(sv.depth>1)
{
sv.pop();
}
else if(drawer.visible){
drawer.close();
}
else{
exitDialog.open();
}
}
}
MenuItem{
contentItem: Text {
text: qsTr("Open Dialog")
}
onClicked: {
var c= myDialogCom.createObject(mainWindow);
c.open();
}
}
Component{
id:myDialogCom
MyDialog{
}
}
}
MyDialog.qml
Dialog {
id: root
parent: Overlay.overlay
x:0
height: mainWindow.height
width:mainWindow.width
header: ToolBar{
}
StackView{
}
}
Edit
I want to mention that I have summarized my questions for a faster understanding.But I had multiple Shortcut in diffrent pages like:(ChatsPage.qm and ChatPage.qml and main.qml) but tried to question be simple,So I just said Shortcut in just main.qml becuase the problem is there yet
| 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")
if(sv.depth>1)
{
sv.pop();
}
else if(drawer.visible){
drawer.close();
}
else{
exitDialog.open();
}
}
}
|
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 expected.
string str = "A man, a plan, a canal: Panama";
str.erase(remove(str.begin(), str.end(), ' '), str.end());
Result : Aman,aplan,acanal:Panama
| 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 container.
|
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 new double[size1];
}
I thought a variadic template could somehow do the trick
template<typename T, typename... size_args>
T* mat(int size1, size_args... sizes) {
T* m = new T[size1];
for(int j = 0; j < size1; j++){
m[j] = mat(sizes...);
}
return m;
}
Deducing the template parameter in m[j] = mat(sizes...); doesn't seem to work though when more than one recursive call would be necessary, as in
auto p = mat<double**>(2,3,4);
but how could I provide the parameter in the recursive call? The correct parameter would be one pointer level below T, that is mat<double**> for T=double***.
I feel like I miss something important about templates here.
| 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>(sizes...));
inner_type* m = new inner_type[size];
for(int j = 0; j < size; j++){
m[j] = mat<T>(sizes...);
}
return m;
}
|
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 this, as the function I'm using can copy a 720x480 image into a 1920x955 image in just under 1.5ms. That's fine on its own, but hardly optimal.
#define coord(x, y) ((void *) (dest + 4 * ((y) * width + (x))))
#define scoord(x, y) ((void *) (src + 4 * ((y) * src_width + (x))))
void copy_buffer(uint8_t* dest, int width, int height, uint8_t* src, int src_width, int src_height, int x, int y) {
if (x + src_width < 0 || x >= width || y + src_height < 0 || y >= height || src_width <= 0 || src_height <= 0)
return;
for (int line = std::max(0, y); line < std::min(height, y + src_height); line++)
memcpy(coord(std::max(0, x), line), scoord(-1 * std::min(0, x), -1 * std::min(0, y)), (std::min(x + src_width, width) - std::max(0, x)) * 4);
}
Some things I've considered
Multithreading seems suboptimal for several reasons;
Race conditions from simultaneous access to the same memory region,
Overhead from spawning and managing separate threads
Using my system's GPU
Effectively multithreading
Huge overhead for moving and managing data between GPU and CPU
Not portable to my target platform
Algorithmic optimisations such as calculating multi-image bounding boxes and adding **** loads more code to only render the regions of the image that will be visible
While I was planning on doing this anyway, I thought I'd mention it here to ask for further information on how to best achieve this
Using a library/os function to do this for me
I'm new-ish to programming on the low level, and especially to performance-oriented programming, so there's always the chance I've missed something.
I'm presently not using a multimedia framework like SFML, because I'm trying to focus on executable and codebase size, but if that's the best idea, so be it.
Whew, bit of a mouthful. I apologise, but I would seriously appreciate any pointers.
Extra notes: I'm writing for/on Linux embedded devices over the DRI/M interface.
Edit
As per @Jérôme Richard's comment, some information about my system
Development machine: Dell inspiron 15 7570, 16GB RAM, i7 8core + Ubuntu 21.04
Target machine: Raspberry Pi 3B (1GB RAM, Broadcom something-or-other) 4 cores 1.4GHz + Ubuntu Server for Pi
Compiler: GCC/G++ 11.2.0
| 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-level architecture of mainstream modern processor and more specifically the cache hierarchy.
There are two main writing cache policy widely used in mainstream processors: the write-back policy (with write-allocate) and the write-through policy (without write-allocate). Intel processors and the BCM2837 (Cortex-A53) of the Raspberry Pi 3B use a write-back policy with write-allocate. Write allocation cause data at the missed-write location to be loaded to cache, followed by a write-hit operation. The thing is that cache lines written to the last-level cache (LLC) need first to be read from RAM before being written back. This can cause up to half the bandwidth to be wasted!
To address this issue when big arrays are written into the RAM (not fit in the LLC), non-temporal instructions have been designed. The goal of such instructions is to write directly into the RAM and bypass the cache hierarchy so not to cause cache pollution and better use the memory bandwidth.
memcpy is generally designed to use non-temporal instructions when a large buffer is copied. However, when many small buffers are copied, memcpy cannot know that the overall set of buffer would be too big to fit in the LLC or even that written data are not meant to be reused soon. In fact, sometime, even developers cannot know since the size of the computed buffer can be dependent of the user and the size of the LLC is dependent of the user target machine.
The bad news is that such instructions can hardly be used from a high-level code. ICC supports that using pragma directives, Clang has an experimental support with builtins and AFAIK GCC does not support that yet. OpenMP 5 provide a portable pragma directive for that but it is not yet implemented. For more information, please read this post.
On x86-64 processors, you can use the SSE and AVX intrinsics _mm_stream_si128 and _mm256_stream_si256. Note that the pointers need to be aligned in memory.
On ARMv8 processors, there is an instruction STNP but it is only an hint and it is not really meant to bypass the cache. Moreover, the Cortex-A53 specification seems to only support non-temporal loads (not non-temporal stores). Put it shortly, ARMv8 does not have such instructions.
The good news is that the very recent ARMv9 instruction set adds new instructions for that. In fact it adds specific instructions for non-temporal copies. You can get the specification here.
Since the Raspberry Pi 3B practical memory benchmarks indicates a read bandwidth of 2.7 GB/s and a write bandwidth of 2.4 GB/s. A copy of a 720x480 3-chanel image with write allocations would take about 720 * 480 * 3 * (1/2.4e9 + 2/2.7e9) = 1.2 ms which is close to your reported execution time. It is also important to mention that read-write DRAM accesses tends to be a bit slower than plain reads or plain writes. If the STNP hint works well, it would results in 0.8 ms (optimal on this hardware). If you want a faster execution time, then you need to work on smaller images.
On you Dell machine with an Intel Kaby-Lake processor and certainly 1~2 2400MHz DDR4 memory channels, the practical throughput should be 12~35 GiB/s resulting in 0.1~0.3 ms to copy the image with the basic memcpy and 0.1~0.2 ms with the non-temporal instructions. Moreover, the LLC cache is much bigger so that the operations should be even faster with the basic memcpy as long as the image fit in the LLC (certainly less than 0.1 ms).
|
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 ("CMakeProject1")
find_package(GTest CONFIG REQUIRED)
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
add_executable (CMakeProject1 "main.cpp" TestClass.cpp TestClass.h)
target_link_libraries (CMakeProject1
PRIVATE GTest::gmock GTest::gtest GTest::gmock_main GTest::gtest_main
)
enable_testing()
find_package(GTest CONFIG REQUIRED)
add_executable(SomeTests
"AppTests.cpp" TestClass.cpp TestClass.h
)
target_link_libraries (SomeTests
PRIVATE GTest::gmock GTest::gtest GTest::gmock_main GTest::gtest_main
)
include (GoogleTest)
gtest_discover_tests(SomeTests)
It builds and links as it's supposed to. But no tests are discovered in AppTests.cpp:
#include <gtest/gtest.h>
namespace SomeNamespaceTests {
// Demonstrate some basic assertions.
TEST(HelloTest, BasicAssertions) {
// Expect two strings not to be equal.
EXPECT_STRNE("hello", "world");
// Expect equality.
EXPECT_EQ(7 * 6, 42);
}
}
| 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 this under my shell application I have two functions to run the commands concurrently, execute() takes multiple commands and for each of the commands it fork() a child process to execute the command, subprocess() takes 1 cmd and executes it.
void execute(std::vector<std::string> cmds) {
int fds[2];
pipe(fds);
std::pair<pid_t, int> sp;
for (int i = 0; i < cmds.size(); i++) {
std::pair<pid_t, int> sp = this->subprocess(cmds[i], fds);
}
// wait for all children
while (wait(NULL) > 0);
close(sp.second);
}
std::pair<pid_t, int> subprocess(std::string &cmd, int *fds) {
std::pair<pid_t, int> process = std::make_pair(fork(), fds[0]);
if (process.first == 0) {
close(fds[0]); // no reading
dup2(fds[1], STDIN_FILENO);
close(fds[1]);
char *argv[] = {"/bin/sh", "-c", cmd.data(), NULL};
execvp(argv[0], argv);
exit(0);
}
close(fds[1]); // only reading
return process;
}
The problem here is, when I execute multiple commands on my custom shell (not diving into spesifics here, but it will call execute() at some point.) if I use STDIN_FILENO as above to capture child process stdout, it keeps writing to shell's stdin forever what the captured output is, for example
if the input commands are
echo im done, yet?
echo nope
echo maybe
then, in writing to STDIN_FILENO case, the output is like (where >>> ) is my marker for user input.
im done, yet?
nope
maybe
>>> nope
maybe
im done, yet?
>>> im done, yet?
nope
maybe
in writing to STDOUT_FILENO case, it seems it's ignoring one of the commands (probably the first child), I'm not sure why?
maybe
nope
>>> maybe
nope
>>> nope
maybe
>>> maybe
nope
>>> nope
So, potential things I thought are in my shell I'm using std::cin >> ... for user input in a while loop ofc, this may somehow conflict with stdin case. On the other hand, in the main process (parent) I'm waiting for all children to exit, so children somehow is not exiting, but child should die off after execvp, right ? Moreover, I close the reading end in the main process close(sp.second). At this point, I'm not sure why this case happens ?
Should I not use pipe() for a process like this ? If I use a temp file to redirect stdout of child process, would everything be fine ? and if so, can you please explain why ?
| 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 object at the function scope. But it's a different object that has nothing to do, whatsoever, with it. That's how C++ works: when you declare an object inside an inner scope, inside an if statement, a for loop, or anything that's stuffed inside another pair of { ... } you end up declaring a new object. Whether its name happens to be the same as another name that's been declared in a larger scope, it's immaterial. It's a new object.
// wait for all children
while (wait(NULL) > 0);
close(sp.second);
There are two separate problems here.
For starters, if we've been paying attention: this sp object has not been initialized to anything.
If the goal here is to read from the children, that part is completely missing, and that should be done before waiting for the child processes to exit. If, as the described goal is here, the child processes are going to be writing to this pipe the pipe should be read from. Otherwise if nothing is being read from the pipe: the pipe's internal buffer is limited, and if the child processes fill up the pipe they'll be blocked, waiting for the pipe to be read from. But the parent process is waiting for the child processes to exist, so everything will hang.
Finally, it is also unclear why the pipe's file descriptor is getting passed to the same function, only to return a std::pair with the same file descriptor. The std::pair serves no useful purpose in the shown code, so it's likely that there's also more code that's not shown here, where this is put to use.
At least all of the above problems must be fixed in order for the shown code to work correctly. If there's other code that's not shown, it may or may not have additional issues, as well.
|
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" << std::endl;
}
};
class Derived : public Base {
public:
Derived() {
std::cout << "Derived::constr" << std::endl;
}
private:
void printImpl() const override {
std::cout << "Derived::printImpl" << std::endl;
}
};
int main() {
Base* ptr = new Derived();
ptr->print();
delete ptr;
}
The above code will print the following:
Base::constr
Base::printImpl
Derived::constr
Derived::printImpl
but I don't understand why printImpl private function is accessible from the base's print function. In my understanding this pointer implicitly passed to the print function holds the derived object's address, but I thought private member functions could be called ONLY from the member functions (and from friend functions) of the same class and here, Base class is not the same class as Derived, although there is an is a relationship.
| 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 words, private only regards access by subclasses; it's meaningless to keep something private from a class' base class: If a method is at all known to the base class, it must be a method of the base class... a virtual method.
Having said all that - note that the Derived version of printImpl() is effectively inaccessible from print() - when it's invoked within the base class constructor. This is because during that call, the constructed vtable is only that of Base, so printImpl points to Base::printImpl.
I thought private member functions could be called ONLY from the member functions of the same class
And indeed, print() is a member of Base, which invokes printImpl() - another method of Base.
|
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>
#include <set>
#include <string>
class Guest{
public:
Guest(const std::string &fn, const std::string &ln, const std::string &em, const std::string &loy):firstname(fn), lastname(ln), email(em),loyalty(loy){}
std::string firstname;
std::string lastname;
std::string email;
std::string loyalty;
};
bool operator<(const Guest& l, const Guest& r){
return (l.firstname < r.firstname) or ((l.firstname == r.firstname) and
((l.lastname < r.lastname) or ((l.lastname == r.lastname) and
((l.email < r.email) or ((l.email == r.email) and
((l.loyalty < r.loyalty) or ((l.loyalty == r.loyalty))))))));
}
int main() {
Guest g1("g1","g2","g3","g4");
Guest g2("g1","g2","g3","g4");
std::set<Guest> guests = {g1,g2};
std::cout << guests.size() << std::endl; //Size is always 2 in here. It should be 1
return 0;
}
| 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 ((l.lastname == r.lastname) and
((l.email < r.email) or ((l.email == r.email) and
((l.loyalty < r.loyalty) ))))));
}
Or make it much simpler with std::tie.
bool operator<(const Guest& l, const Guest& r){
return std::tie(l.firstname, l.lastname, l.email, l.loyalty) <
std::tie(r.firstname, r.lastname, r.email, r.loyalty);
}
|
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<char>, fmt::v8::basic_format_args<fmt::v8::basic_format_context<fmt::v8::appender, char> >)'
collect2: error: ld returned 1 exit status
I tried -lfmt but it errors with
/usr/bin/ld: cannot find -lfmt
I cant find any help for this type of use on the git.
How do you use fmt lib on CentOS9 without building fmt project manually?
EIDT: dnf install output
| 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 to link with the shared library when developing applications that use this library.
You need both packages to compile the code that uses the library. The devel package specifies a dependency on the main package, so dnf install name-devel is going to install both packages.
You should invest a little bit of time to learn how to build your own rpm packages. It's not that complicated. When you build your package rpmbuild will take care of analyzing the resulting binary, discovering which shared libraries it links with, then recording the appropriate dependency in your own rpm package, so installing it will pull in only the main name package.
|
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 maybe I got this all wrong, but if I am right I just find it difficult to get past the 1st step - How can I bind those two?
| 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 (SUCCEEDED(item->GetUInt64(PKEY_Size, &size))) // include propkey.h
{
... use size ...
}
item->Release();
}
...
CoUninitialize();
If you already have an IShellItem reference (in general you want to get an IShellItem2 directly) and want a IShellItem2, you can do this:
IShellItem2* item2;
if (SUCCEEDED(item->QueryInterface(&item2)))
{
... use IShellItem2 ...
}
Another way of doing it, w/o using IShellItem2, is this:
IShellItem* item;
if (SUCCEEDED(SHCreateItemFromParsingName(L"c:\\myPath\\myFile.ext", NULL, IID_PPV_ARGS(&item))))
{
IPropertyStore* ps;
if (SUCCEEDED(item->BindToHandler(NULL, BHID_PropertyStore, IID_PPV_ARGS(&ps))))
{
PROPVARIANT pv;
PropVariantInit(&pv);
if (SUCCEEDED(ps->GetValue(PKEY_Size, &pv))) // include propkey.h
{
ULONGLONG size;
if (SUCCEEDED(PropVariantToUInt64(pv, &size))) // include propvarutil.h
{
... use size ...
}
PropVariantClear(&pv);
}
ps->Release();
}
item->Release();
}
|
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 argument
I don't find the answer to this in stackoverflow.(The existing question seem not to solve my problem...)
How to dynamically allocate a 2D std::array in C++?
I know I could use std::vector to solve this. But the vector memory size needs to be organized by myself and this would be used many times in my project. And I want to use C++ type code rather than C type...Maybe there is a method to turn a 2D array in C type to std::array, but I can't find it by Google...
So I ask this question...
I mean the M and N should be got dynamically(not changed,but I can only know it in runtime...),like:
#include <iostream>
int main(){
int a=3;
int b=4;
int rowCount=a+b;
int colCout=b-a;
int** a = new int*[rowCount];
for(int i = 0; i < rowCount; ++i)
{
a[i] = new int[colCount];
}
}
I know where is my mistake. I fell into a logical question... If I don't use push_back,the vector works well. If I use it, the array doesn't work, too.
I think the capcity of vector is bigger than its size, I want to avoid this. But another question: How to limit the capacity of std::vector to the number of element show I should use my allocator or std::vector::shrink_to_fit() to avoid it...(There is no guarantee in C++17 if you use reserve(n))
| 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 using the constructor.
std::vector<std::vector<int>> arr(N);
If you need some special allocator (not just new/malloc), then you can also specify a custom allocator.
Your whole program that you propose is not good C++. A C++ solution would look like:
#include <vector>
int main() {
int a = 3;
int b = 4;
unsigned int rowCount = a + b;
unsigned int colCount = b - a;
std::vector<std::vector<int>> matrix(rowCount);
for (auto& row : matrix) {
row.resize(colCount);
}
}
|
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-config.cmake
but it set VTK_FOUND to FALSE so package “VTK” is considered to be NOT FOUND.
Reason given by package:
Could not find the VTK package with the following required components:
GUISupportQt, ViewsQt.
Has anyone encountered this problem before ?
Thank you for your help.
| 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 also need to enable Module_vtkGUISupportQtOpenGL and Module_vtkRenderingQt).
These options are not enabled by default, but they seem to be required by the example that you're trying to compile.
Don't worry, you shouldn't have to re-do everything now. To fix:
Open the CMake GUI.
Enter the folder where you built VTK in "Where to build the binaries".
If it's not checked, set the "Advanced" checkbox (the required options are not visible otherwise).
Set VTK_MODULE_ENABLE_VTK_GuiSupportQt and VTK_MODULE_ENABLE_VTK_ViewsQt options to "YES"
Press "Configure", and wait for it to finish
During Configuring, you might get an error, if CMake doesn't know how to find Qt; if so, enter the Qt5_DIR / Qt6_DIR, and press configure again.
Press "Generate", and wait for it to finish
Start the vtk build again (depends on what build tool you choose...)
Try configuring the example again, now you should not see the error message anymore.
|
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
#include <atomic>
class Example
{
std::atomic<bool> m_b1 = false; // 1-h
std::atomic<bool> m_b2{ false }; // 2-h
static void doSomethng()
{
std::atomic<bool> b1 = false; // 1-f
std::atomic<bool> b2{ false }; // 2-f
std::atomic<bool> b3(false); // 3-f
// Do something
}
};
| 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); however is direct-initialization and will just construct x with the argument 0 to the constructor.
Since C++17 there is no temporary and x will directly be initialized by a constructor call with 0 as argument in any case and so there is no issue with std::atomic being non-movable. In that sense the slide is now out-dated.
Even though the behavior is now the same for copy-initialization and direct-initialization in this case, there are still differences between the two in general. In particular direct-initialization chooses a constructor to initialize the variable directly by overload resolution while copy-initialization tries to find an implicit conversion sequence (possibly via converting constructor or conversion function with different overload resolution rules). Also, copy-initialization, in contrast to direct-initialization, does not consider constructors marked explicit.
Regarding the code snippet in the question. 1-h and 1-f are copy-initialization as above. 3-f is direct-initialization as above. 2-h and 2-f are direct-list-initialization, which behaves different from both others in some cases, but here it has the same effect as direct-initialization with parentheses.
Explaining all the differences between the initialization forms in general would take a while. This is famously one of the most complex parts of C++.
|
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;
};
MyApplication.cpp
MyApplication::start()
{
// ...
_database = QSqlDatabase::database();
// ...
}
For data model handling I'm using an overloaded class of QSqlTableModel:
SqlContactModel.h
#include <QSqlTableModel>
class SqlContactModel : public QSqlTableModel
{
public:
// ...
void setDatabase(const QSqlDatabase& database) { _database = database };
private:
QSqlDatabase _database;
};
SqlContactModel overloads the typical methods such as data(), roleNames() etc.
My instance of SqlContactModel is used in QML, thus I'm creating the instance in my main.cpp as follows:
main.cpp
int main()
{
// ...
qmlRegisterType<SqlContactModel>("io.taibsu.qxmt", 1, 0, "SqlContactModel");
}
Now since it's being created via qmlRegisterType, I can't pass any parameters in the constructor to set a different database in the SqlContactModel.
I need to pass a different database to it since I'm using multiple different overloaded QSqlTableModel classes (e.g., the other class is called SqlConversationModel and shall use the same _database instance which is used in MyApplication).
Now there are two ways to solve this: either pass the database somehow to my SqlTableModel subclasses via QML or find another way to tell the TableModel to not use its own database instance but the one already there.
Now my questions are:
How can I use a single database in different table models?
Is there a way to pass parameters when constructing a class instance in QML?
| 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. There probably isn’t even a need to have that property be another type than QAbstractItemModel* so you keep the freedom to modify it to another model type if needed in the future without affecting your QML. Such decoupling is desirable.
|
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 = sin.length() - 1;
cout << revstr(sin, n) << endl;
return 0;
}
Python Program (Correct)
def revstr(s, n):
if n == 0:
return l[0]
else:
return l[n] + revstr(s, n-1)
#Main Code
sin = input()
l = []
for i in range(0, len(sin)):
l.append(sin[i])
print(l)
n = len(l) - 1
print(revstr(sin, n))
Description
I am trying to reverse a string using the recursion technique as classwork, but then my program works on Python but not C++, which gives "O" only.
I do not know what the problem in the C++ program is, since the Python counterpart works well.
For example,
Input
Computer
C++ Output
O
Python Output
retupmoC
IMPORTANT
Instructions said I have to do it in recursion
This happens when I declare the function return value as string.
error: could not convert 's.std::__cxx11::basic_string<char>::operator[](0)' from '__gnu_cxx::__alloc_traits<std::allocator<char>, char>::value_type' {aka 'char'} to 'std::string' {aka 'std::__cxx11::basic_string<char>'}
8 | return s[0];
| ^
| |
| __gnu_cxx::__alloc_traits<std::allocator<char>, char>::value_type {aka char}
| 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 overflow of course since the range of char is limited to typically -128..127)
Changing the above causes, as you note in the comments, a follow up problem - how to convert a single character to a string, to which, fortunately, there is an answer already here on SO
Your recursion exit condition - it is n == 1... what about strings of length 1? They will never reach n == 1 ...
To fix problems 2 and 3 at once and simplify your code a little, think about the case of an empty string and whether your code can currently handle that. You can handle that case by simply returning an empty string...
|
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);
}
~String()
{
cout<<"DELETING\n";
delete[] ptr;
}
void display()
{cout<<ptr;}
};
int main()
{
String s("Waqar"); String* s2 =&s;
String s1(s);
delete s2;
s1.display();
It goes fine till the second last line delete s2. While debugging, it throws an error to the effect of an unknown signal and never executes s1.display().
Being a noob, I was testing deep vs shallow copy concepts in c++ and thus written this junk.
Where did I go wrong?
| 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 fault here.
Here's a sample program detailing how and when the destructor is
called a different points, and only delete's memory that was allocated with new.
// declare `copy`, but do not initialise it just yet. We want to
// initialise it from `s` (which is not yet declared)
String* copy;
{
// declare and initialise `s`, and copy "Wagner" into s.ptr
String s("Wagner");
// create a new String on the heap, initialised from `s`
// this is a deep copy because of how you wrote String(String&)
copy = new String(s);
s.display();
// `s` falls out of scope at the end of this block
// this means that s.~String() is invoked
}
// `copy` is unaffected as it was declared in the outer scope,
// and because it is a deep copy. Had it been a shallow copy
// then it would be broken as its `char* ptr` would not be valid
// any more.
copy->display();
// copy->~String() is invoked when copy is deleted
delete copy;
|
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 frequency elemnt in the 2d
vector .
#include <iostream>
#include <vector>
#include <map>
#include <iomanip>
using namespace std;
int main()
{
vector<vector<int>> edge
{
{4, 2, 3},
{4, 5, 6},
{2, 8, 9}
};
map<int, unsigned int> occurrences;
// Process the hypergraph.
for (int i = 0; i < edge.size(); i++)
{
for (int j = 0; j < edge[i].size(); j++)
{
occurrences[edge[i][j]]++;
}
}
unsigned currentMax = 0;
unsigned arg_max = 0;
// Show the results:
for (map<int, unsigned int>::iterator it = occurrences.begin(); it != occurrences.end(); ++it)
{
if (it ->second > currentMax) {
arg_max = it->first;
currentMax = it->second;
}
}
cout << "Value " << arg_max << " occurs " << currentMax << " times " << endl;
return 0;
}
| 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, 5, 6},
{2, 8, 9}
};
unsigned int max_count = 0;
std::map<int, unsigned int> counts;
for (const std::vector<int> &row : edge) {
for (const int &ele : row) {
if (++counts[ele] > max_count) {
max_count = counts.at(ele);
}
}
}
for (const auto& [val, count] : counts) {
if (count == max_count) {
std::cout << "Value " << val << " occurs " << count << " times\n";
}
}
return 0;
}
Output:
Value 2 occurs 2 times
Value 4 occurs 2 times
|
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 Milan) and extract only that line so in this case it extracts MILAN;F205 and puts it in the variable result.
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <algorithm>
using namespace std;
string file_content();
int main()
{
string database = file_content();
string result,city;
int len_database = database.size();
cout<<"which city do you want to look for? ";
cin>>city;
//cerchiamo la città nel database
if (database.find(city) != string::npos)
{
//cout<<"the code is present in the database"
//how should i continue?
}else{
cout << "it is not present in the database! ";
return 0;
}
cout << result;
return 0;
}
string file_content()
{
// filestream variables
fstream file;
string filename;
// we declare filename which corresponds to the file we want to open
filename = "lista-codici.txt";
//open the file
file.open(filename.c_str());
// create a stringstream
stringstream buffer;
//passes the file buffer to the stringstream
buffer << file.rdbuf();
//reading the file
return buffer.str();
}
How do I extract a specific line of text present in the database variable?
| 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
takes the walk of the input lines and the creation of the output vector to a filter_by_city function.
[Demo]
#include <algorithm> // copy_if
#include <iostream> // cout
#include <iterator> // istream_iterator
#include <sstream> // istringstream
#include <string>
#include <string_view>
#include <vector>
auto filter_by_city(const std::vector<std::string>& lines, std::string_view city) {
std::vector<std::string> ret{};
std::copy_if(std::cbegin(lines), std::cend(lines), std::back_inserter(ret),
[&city](const auto& line) {
return line.substr(0, line.find(';')) == city;
});
return ret;
}
int main()
{
std::istringstream iss{"MILAN;F205\nROME;G306\nMILAN;H407\nFIRENZE;I508\n"};
std::vector<std::string> lines{std::istream_iterator<std::string>{iss}, {}};
for (auto&& line : filter_by_city(lines, "MILAN")) {
std::cout << line << "\n";
}
}
// Outputs:
//
// MILAN;F205
// MILAN;H407
A probably better option, considering your input file is a database, would be to:
read your input stream into a map of cities, and
query for a specific city.
[Demo]
#include <algorithm> // transform
#include <iostream> // cout
#include <iterator> // istream_iterator
#include <map>
#include <sstream> // istringstream
#include <string>
#include <utility> // make_pair
auto create_db(std::istringstream& iss) {
std::map<std::string, std::string> ret{};
std::transform(std::istream_iterator<std::string>{iss}, {},
std::inserter(ret, std::end(ret)),
[](const auto& line) {
auto sep{ line.find(';') };
return std::make_pair(line.substr(0, sep), line.substr(sep + 1));
});
return ret;
}
int main()
{
std::istringstream iss{"MILAN;F205\nROME;G306\nNAPOLI;H407\nFIRENZE;I508\n"};
auto db{ create_db(iss) };
if (db.contains("MILAN")) {
std::cout << "MILAN: " << db["MILAN"] << "\n";
}
}
// Outputs:
//
// MILAN: F205
|
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() {
std::cout << "running!" << std::endl;
}
};
template<typename T> class TaskRunner {
public:
TaskRunner<T>() {
task = std::make_unique<T>();
}
private:
std::unique_ptr<T> task;
};
using Runner = std::shared_ptr<TaskRunner<Task>>;
However I get error: no matching member function for call to 'push_back' with:
std::vector<Runner> runners;
runners.push_back(std::make_shared<TaskRunner<QuietTask>>());
runners.push_back(std::make_shared<TaskRunner<LoudTask>>());
Due to:
note: candidate function not viable: no known conversion from 'shared_ptr<TaskRunner>' to 'const shared_ptr<TaskRunner>' for 1st argument
| 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() {
std::cout << "running!" << std::endl;
}
};
class TaskRunnerBase
{
public:
virtual void run() =0;
};
template <class T>
class TaskRunner: public TaskRunnerBase {
public:
TaskRunner():
task(std::make_unique<T>()) {
}
void run() override
{
task->run();
}
private:
std::unique_ptr<T> task;
};
int main()
{
using Runner = std::shared_ptr<TaskRunnerBase>;
std::vector<Runner> runners;
runners.push_back(std::make_shared<TaskRunner<QuietTask>>());
runners.push_back(std::make_shared<TaskRunner<LoudTask>>());
runners[0]->run();
runners[1]->run();
}
Output:
running!
RUNNING!
Note however that TaskRunner doesn't need to be a template; as it is currently implemented above, it has a kind of double role: (1) task factory, and (2) container and runner of tasks.
paolo's answer separates this out nicely, there, the factory aspect is moved to the main function.
|
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;
}
}
What am I doing wrong here?
| 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)
{
previous = current;
current = current->next;
previous->next = NULL; // avoid the delete below to propagate through list.
delete previous;
}
}
There is no need to set previous to NULL, since it will run out of scope. But it is needed to detach previous from its successors, so to avoid the the destructor will follow that chain again.
This code assumes that this is the first node of the list, which would be the natural thing to execute delete on. If for some reason you would execute delete on a node somewhere in the middle of a list, with the aim to discard the whole list, then you would need to repeat the above loop also for the nodes that precede the current node.
|
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.
How do I "install" C++ 20 ? What is it and how can it be done on RH/CentOS ?
| 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 for enabled C++20 support, but in practice that doesn't mean that all C++20 features are supported.
There are further feature-specific feature test macros that may be of help.
For an overview of what exactly is supported in which compiler version see https://en.cppreference.com/w/cpp/compiler_support, as well as the corresponding pages of the individual compilers.
As you can see there, with GCC 11 you have mostly complete C++20 support, except for few items, especially in the standard library, such as for example full module support, constexpr for std::string and std::vector, atomic shared pointers and notably std::format.
|
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 verbose
for (const auto [x, y] : std::map<int, double>{{1, 1.0}, {2, 1.1}, {3, 1.2}}) {
// ...
}
| 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 the remaining elements. E.g. if you do {std::pair{1, 2}, {3.1, 4.1}}, the last pair becomes {3,4}, since the first one uses ints.
|
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
0x1p-10
0x1p+0
As one can see, the results look "reasonable". However, there are probably multiple different ways
to display these numbers. Or to display numbers very close.
Is it guaranteed in C and in C++ that IEEE 754 floating arithmetic like addition, multiplication and int-to-float conversion yield the same results, on all machines and with all compilers (i.e. that the resulting floats are all bit-wise equal)?
| 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 predefine the __STD_IEC_559__ macro.
If the macro is defined, then IEEE 754 guarantees the bit representation (but not the byte order) of float and double as 32-bit and 64-bit IEEE 754. This in turn guarantees bit-exact representation of double arithmetic (but note that the C standard allows float arithmetic to happen at either 32 bit or 64 bit precision).
The C standard requires that float to int conversion be the same as the trunc function if the result is in range for the resulting type, but unfortunately IEEE doesn't actually define the behavior of functions, just of basic arithmetic. The C spec also allows the compiler reorder operations in violation of IEEE754 (which might affect precision), but most that support IEEE754 will not do that wihout a command line option.
Anecdotal evidence also suggest that some compilers do not define the macro even though they should while other compilers define it when they should not (do not follow all the requirements of IEEE 754 strictly). These cases should probably be considered compiler bugs.
|
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 set, it is anyways going to copy over the const Order &order
Is the above code any better than:
class OrderBook
{
set<Order> orders;
void insert_Bid(Order order);
}
void OrderBook::insert_Bid(Order order)
{
orders.insert(order);
}
Thanks
| 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++) {
auto l_front = list_1.begin();
advance(l_front, i);
for (int j = 0; j < Size(list_2); j++) {
auto l_front_2 = list_2.begin();
advance(l_front_2, j);
if (*l_front == *l_front_2)
{
l_front_2 = list_2.erase_after(l_front);
}
}
}
}
| 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 = 0; j < Size(list_2); j++) {
the next element in the list will be skipped.
A straightforward approach can look for example the following way as it is shown in the demonstration program below.
#include <iostream>
#include <string>
#include <forward_list>
#include <iterator>
#include <algorithm>
void make_unique( std::forward_list<std::string> &list_1,
const std::forward_list<std::string> &list_2 )
{
for ( auto current = std::begin( list_1 ); current != std::end( list_1 ); )
{
if (std::find( std::begin( list_2 ), std::end( list_2 ), *current ) != std::end( list_2 ))
{
std::string s( *current );
list_1.remove( s );
current = std::begin( list_1 );
}
else
{
std::advance( current, 1 );
}
}
}
int main()
{
std::forward_list<std::string> list_1 = { "A", "B", "A", "C", "D", "B", "E" };
std::forward_list<std::string> list_2 = { "A", "B" };
for (const auto &s : list_1)
{
std::cout << s << ' ';
}
std::cout << '\n';
make_unique( list_1, list_2 );
for (const auto &s : list_1)
{
std::cout << s << ' ';
}
std::cout << '\n';
}
The program output is
A B A C D B E
C D E
A much more simple function definition can be if to use the method remove_if or the general function std::erase_if introduced in the C++ 20 Standard. For example
void make_unique( std::forward_list<std::string> &list_1,
const std::forward_list<std::string> &list_2 )
{
auto found = [&list_2]( const auto &s )
{
return std::find( std::begin( list_2 ), std::end( list_2 ), s ) != std::end( list_2 );
};
list_1.remove_if( found );
}
Or if the compiler supports C++ 20 then
void make_unique( std::forward_list<std::string> &list_1,
const std::forward_list<std::string> &list_2 )
{
auto found = [&list_2]( const auto &s )
{
return std::find( std::begin( list_2 ), std::end( list_2 ), s ) != std::end( list_2 );
};
std::erase_if( list_1, found );
}
The both presented functions remove elements in list_1 that are found in list_2.
|
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 <typename T>
struct Magma { //magma trait
T (& combine)(T, T);
consteval Magma(decltype(combine) c): combine{c} {}
};
template <typename T, const Magma<T> & mag>
T add(T x, T y) {return mag.combine(x, y);}
Here is an example of a naive attempt to do so with a templated function ptr:
template <template<typename> typename F>
struct Functor { //functor trait
template <typename A, typename B> //member template compilation error
F<B> (& map)(std::function<B(A)>, F<A>);
consteval Functor(decltype(map) m): map{m} {}
};
//...
template <template<typename>typename F, const Functor<F> & ftor>
This fails because on the member template case, sadly there is no way to tell the compiler that the type will only exist at compile time, not that (as of writing) it would care.
Issues I have faced:
I would use C++20 concepts do write temp_callable_concept auto map or something similar however auto is not a valid identifier for a data member.
I could probably move the type definition into the template of Functors using C++20 concepts however that goes against the very point of encapsulating the function.
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.
Final thoughts
I do not see a way to do this right now and I believe that this requires C++ to allow explicitly compile time types with data member signatures that match those of template args.
If anyone knows a way to encapsulate this behaviour please leave an answer, or if you have any questions leave a comment.
|
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 in rust or typeclasses in haskell. If you wanted to implement haskell Functor for example:
template<template<typename> typename T>
struct Functor : public std::false_type {};
template<>
struct Functor<std::vector> : public std::true_type {
template<typename T, typename F>
requires (std::invocable<F, T>)
static auto fmap(std::vector<T> v, F&& f) -> std::invoke_result_t<F, T> {
// ...
}
};
template<template<typename> typename C, typename T, typename F>
requires (Functor<C>::value && std::invocable<std::remove_cvref_t<F>, T>)
auto fmap(C<T> v, F&& f) {
return Functor<C>::fmap(v, std::forward<F>(f));
}
This then lets you use it as simply fmap giving you the compile time polymorphism while still allowing the trait like implementation. Really you should also make a concept that specifies the requirements on Functor implementations and use that instead of just checking for any implementation (with value)
|
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("", 0, 0, 200, 200, 0);
SDL_Renderer* r = SDL_CreateRenderer(w, -1, 0);
TTF_Font* f = TTF_OpenFont(MY_FONT, 100);
SDL_Color c = {.r = 0, .g = 255, .b = 0, .a = 255};
SDL_Surface* s = TTF_RenderGlyph32_Blended(f, 'A', c);
SDL_Texture* t = SDL_CreateTextureFromSurface(r, s);
#ifdef RENDER_COPY
SDL_Texture* t2 = SDL_CreateTexture(
r,
SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_TARGET,
s->w,
s->h);
SDL_SetRenderTarget(r, t2);
SDL_RenderCopy(r, t, NULL, NULL);
SDL_SetRenderTarget(r, NULL);
t = t2;
#endif
#ifdef RENDER_MEMCPY
SDL_Texture* t2 = SDL_CreateTexture(
r,
SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_STREAMING,
s->w,
s->h);
SDL_Surface* s2;
sdl_try(SDL_LockTextureToSurface(t2, NULL, &s2));
memcpy(s2->pixels, s->pixels, s->w * s->h * sizeof(SDL_Color));
SDL_UnlockTexture(t2);
t = t2;
#endif
#ifdef RENDER_BLEND
SDL_SetTextureBlendMode(t, SDL_BLENDMODE_BLEND);
#endif
SDL_SetRenderDrawColor(r, 255, 255, 255, 255);
SDL_RenderClear(r);
SDL_Rect rect = {.x = 0, .y = 0};
SDL_QueryTexture(t, NULL, NULL, &rect.w, &rect.h);
SDL_RenderCopy(r, t, &rect, &rect);
SDL_RenderPresent(r);
SDL_Event event;
do { SDL_WaitEvent(&event); } while (event.type != SDL_KEYDOWN);
}
Without RENDER_COPY, I get a texture (created via SDL_CreateTextureFromSurface) that blends correctly onto a render target (this is what I want, but with multiple surfaces combined into one texture.)
With RENDER_COPY (i.e. a second texture is created and then copied onto) the background of the texture is black. This is a contrived example since there is only one surface being copied, but I want to copy multiple surfaces to t2.)
With RENDER_BLEND, the black is mostly gone but it's as if the texture was blended onto a black background.
Is there a way to create a texture that can be set completely transparent instead of a solid color? I've also tried to set the pixels directly (RENDER_MEMCPY) but that just ends up being a solid color as it appears the alpha in each pixel is ignored:
SDL version is 2.0.20.
| 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>
#include <vector>
#include <iterator>
#include <algorithm>
#include <cstddef>
#include <memory_resource>
// how should I implement this class? Using a template? How?
struct Foo
{
explicit Foo( const std::size_t count = 1000, const char fillChar = ' ' )
: vec( count, fillChar )
{
}
std::pmr::vector<char> vec; // I need both normal and pmr vector
// (depending on what the client chooses to use)
};
int main( )
{
std::array<std::byte, 10'000> buffer;
std::pmr::monotonic_buffer_resource rsrc { buffer.data( ), 10'000 };
std::pmr::vector<char> vec( 6000, '*', &rsrc ); // this free vector is a sample that
// shows how I may want to allocate
// a buffer for the vector member of Foo
// print the content for demonstration
std::copy_n( std::begin( vec ), 5, std::ostream_iterator<char>( std::cout, " " ) );
std::cout << '\n';
// how should I achieve the above or something similar for this object
Foo foo { 2000, '!' };
}
I would also want to mention that the aim is simplicity so I'll be glad to see a fairly simple approach. But any suggestion is welcome.
| 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,
const Allocator& alloc = Allocator())
: vec(count, value, alloc) {}
std::vector<char, Allocator> vec;
};
namespace pmr {
using Foo = foo::Foo<std::pmr::polymorphic_allocator<char>>;
}
} // namespace foo
Using foo::Foo and foo::pmr::Foo:
int main() {
foo::Foo x(1000, '^');
std::array<std::byte, 10'000> buffer;
std::pmr::monotonic_buffer_resource rsrc{buffer.data(), buffer.size()};
foo::pmr::Foo y(2000, '$', &rsrc);
}
Demo
|
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 needs only float as arguments? I want to make sure at compile-time that every argument is the type I want.
So these are my questions:
Is there a way to force a certain type with variadic templates (something like this)?
template <float... Fs>
f(Fs... args); // unlimited number of arguments but only float
If not, is there a way to check it at compile-time? static_assert(std::is_same<A,B>) is fine in most cases, but it doesn't work for templated classes (like for my use case):
template <typename T, uint16_t dimension>
class Vector
{
template <typename... Ts>
Vector(Ts... args)
{
static_assert(sizeof...(args) == dimension);
static_assert(std::is_same_v<Ts..., T>()); //doesn't work because Ts will
//develop into a lot of template
//arguments. Just putting Ts doesn't
//work either.
}
}
Ps: Yes I could use std::vector or std::array as arguments, but that's not really the point. Plus, I want to keep the beautiful Vector(2.0, 1.0, 0.0) syntax, not using curly braces.
| 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>>...>
{
}
};
//...
Vector<float, 5> v( 1.1f, 2.2f, 3.3f, 4.4f, 5.5f );
Or as @HolyBlackCat wrote in a comment you may also write
template <typename T, uint16_t dimension>
class Vector
{
public:
template <typename... Ts>
Vector( std::same_as<T> auto ...args ) requires( sizeof...( args ) == dimension )
{
}
};
|
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 return its player state object.
The second would check if the actor has a controller and if that controller is the APlayerController class, then calls a function from the APlayerController class if it is. I feel like there should be a way to avoid doing this every time I want to check if an object exists or if an object is a specific class. Is there?
| 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 may be compiler implementation specific in which case an example would be helpful). With dynamic deleters, does it restrict the destructor from being inlined?
| 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*) = /* somehow */;
int main()
{
A* p = /* somehow */;
static_delete(p); // undefined behaviour
dynamic_delete(p); // maybe not
}
As long asdynamic_delete points to a function that's defined where A is also defined, you have well-defined behaviour.
To prevent undefined behaviour, the default deleter checks for a complete type, which may be implemented as
void default_delete(A* p)
{
static_assert(sizeof(A) > 0);
delete p;
}
|
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 number of users using the program is incremented.
When the value -999. When -999 is entered, the total number of students, total textbooks, and the average number of textbooks are printed.
#include <iostream>
using namespace std;
int main () {
const int minBooks = 0, maxBooks = 50;
int books;
int sum=0;
int student = 1;
do {
cout << "Books: " << endl;
cin >> books;
student++;
sum += books;
if (books == -999) {
cout << "Books: " << sum << "\n" << "Students: " << student << "\n" << "Average" << sum/student<< endl;
break;
}
while (books < minBooks || books > maxBooks)
{
cout << "You should at least have " << minBooks << " but no more than " << maxBooks << endl;
cout << "How many books did you purchased?"<< endl;
cin >> books;
}
} while (books!= -999);
}
My problem is that I cant make a program exit after user input is -999.
I tried to change place, use in the loop, out of the loop
If -999 works, then it doesn't validate the input
changed while for "if" and now it works
however, it doesn't sum up books and takes only last input which is -999
after changing books for sum in two place, now my average is not correct due wrong amount of student; I tried to do decremation but then my average becomes negative
| 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 = student - 1;
sum += 999;
cout << "Here is your summary: " << endl;
cout << "Books: " << sum << "\n" << "Students: " << student << "\n" <<
"Average: " << sum/student<< endl;
break;
}
while (books < minBooks || books > maxBooks)
{
cout << "You should at least have " << minBooks << " but no more than " << maxBooks << endl;
cout << "How many books did you purchased?"<< endl;
cin >> books;
}
} while (books!= -999);
}
|
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 = vertex.y;
z = vertex.z;
Or is there a way I can bind the values to the vec3
| 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 <typename T>
using SafeReference =
std::conditional_t<std::is_scalar_v<T>, T, const T&>;
The scalar part isn't interesting here, but what's interesting is const T&. This looks right to me, but it's not:
struct Foo{};
using Bar = Foo&&;
// A failing static assert, and a reduced version. It turns out `const Bar&`
// is `Foo&`.
static_assert(std::is_same_v<const Foo&, SafeReference<Bar>>);
static_assert(std::is_same_v<const Foo&, const Bar&>);
I understand that Foo&& becomes Foo& due to the rules for reference collapsing. I also understand that the const is probably "lost" because it tries to make a reference const rather than making the referred-to type const. But I don't even know what to Google in order to confirm that.
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?
|
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 create the type lvalue reference to cv TR creates the type lvalue reference to T, while an attempt to create the type rvalue reference to cv TR creates the type TR.
The quote probably explains the behavior you're seeing.
|
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 Manifest but make it install libraries system wide instead of locally to the project?
Or at least not inside the build directory, so will be possible to reuse it?
| 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(CUDAToolkit)
include_directories(${CUDA_INCLUDE_DIRS})
link_directories(${CUDA_LIBRARY_DIRS})
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK3 REQUIRED gtk+-3.0)
include_directories(${GTK3_INCLUDE_DIRS})
link_directories(${GTK3_LIBRARY_DIRS})
add_definitions(${GTK3_CFLAGS_OTHER})
add_executable(untitled1 main.cpp bob.h bob.cu)
target_link_libraries(untitled1 ${GTK3_LIBRARIES} ${CUDA_LIBRARIES} ${CUDA_CUDART_LIBRARY})
But I get the following error
-- Unable to find cuda_runtime.h in "/usr/lib/cuda/include" for CUDAToolkit_INCLUDE_DIR.
-- Unable to find cudart library.
-- Could NOT find CUDAToolkit (missing: CUDAToolkit_INCLUDE_DIR CUDA_CUDART) (found version "11.2.67")
-- Configuring done
CMake Error: The following variables are used in this project, but they are set to NOTFOUND.
Please set them or make sure they are set and tested correctly in the CMake files:
CUDA_CUDART_LIBRARY (ADVANCED)
I am on Pop OS 21.10 (Ubuntu), I can use the Cuda libraries and nvcc outside of this project, so I know it is installed and working properly. I just don't know how to link the cuda libraries to a non cuda project.
Edit: Working CMakeLists.txt down below thx to dhyun
# Set the minimum version of cmake required to build this project
cmake_minimum_required(VERSION 3.21)
# Set the name and the supported language of the project
project(final CUDA)
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CUDA_STANDARD 14)
# Use the package PkgConfig to detect GTK+ headers/library files
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK3 REQUIRED gtk+-3.0)
# Setup CMake to use GTK+, tell the compiler where to look for headers
# and to the linker where to look for libraries
include_directories(${GTK3_INCLUDE_DIRS})
link_directories(${GTK3_LIBRARY_DIRS})
# Add other flags to the compiler
add_definitions(${GTK_CFLAGS_OTHER})
# Add an executable compiled from files:
add_executable(final main.cu showtext.h)
target_link_libraries(final ${GTK3_LIBRARIES})
# Idk what this does or if it's necessary, but it works with it and was there on creation
# So I'm keeping it :)
set_target_properties(final PROPERTIES
CUDA_SEPARABLE_COMPILATION ON)
| 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 14)
set(CMAKE_CUDA_STANDARD 14)
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK3 REQUIRED gtk+-3.0)
include_directories(${GTK3_INCLUDE_DIRS})
link_directories(${GTK3_LIBRARY_DIRS})
add_definitions(${GTK3_CFLAGS_OTHER})
add_executable(untitled1 main.cpp bob.h bob.cu)
target_link_libraries(untitled1 ${GTK3_LIBRARIES})
I believe cudart is linked automatically, but you will need to specify any other libraries you use (cufft, cublas, cudnn, etc.).
|
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 through this, d.b is now unspecified
The above example is from cppreference.
My first question is that it is written that "this cannot be aliased in a ctor" but then in the example above, they've written in the comment "b(this->a) would be correct". This seems to be a contradiction to me because when they said that this cannot be aliased in a ctor i understood that "this cannot be used in a ctor". But then why are they saying that writing b(this->a) would be correct if this cannot be used/aliased in a ctor. Isn't the initializer list considered "in a ctor"?
Now lets look at a custom example:
struct Name
{
private:
int x = 0;
Name(int n )
{
this->x = 4; //is the use of "this" well-defined here?
}
};
My second question is that is the use of the expression this->x inside the converting constructor shown above well-defined? I mean since according the quote at the beginning of my question this can't be aliased in a ctor, so this shouldn't be valid.
| 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 which is implicitly the same as this->a.
It is also ok to copy the pointer this and access members through that, e.g.
auto p = this;
b = p->a;
or to store a reference to the object:
auto& r = *this;
b = r.a;
But in the example given at the beginning, d is the same object as this points to. In other words the name d and *this are aliases for the same object. It is not allowed to use this other alias d to access non-static data members of the class while it is under construction because d was not obtained from this. Or to be more precise, it is unspecified what value such an access will read. So b(d.a) may or may not initialize the b member to the same value as a.
See [class.cdtor]/2.
|
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 isPrimary = false;
//list all DisplayDevices (Monitors)
do
{
DISPLAY_DEVICE displayDevice;
ZeroMemory(&displayDevice, sizeof(DISPLAY_DEVICE));
displayDevice.cb = sizeof(displayDevice);
ret = EnumDisplayDevices(NULL, devId, &displayDevice, 0);
if (ret != 0) // reinterpret_cast
{
// 有‘DISPLAY_DEVICE_ATTACHED_TO_DESKTOP’标志的显示设备
if ((displayDevice.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP) == DISPLAY_DEVICE_ATTACHED_TO_DESKTOP)
{
devices.push_back(displayDevice);
isPrimary = ((displayDevice.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE) == DISPLAY_DEVICE_PRIMARY_DEVICE);
}
}
devId++;
} while (ret);
m_vDisplayDevice_list = devices;
std::list<DISPLAY_DEVICE>::iterator it;
for (it = m_vDisplayDevice_list.begin(); it != m_vDisplayDevice_list.end(); it++)
{
DEVMODE deviceMode;
deviceMode.dmSize = sizeof(DEVMODE);
deviceMode.dmFields = DM_PELSWIDTH | // dmPelsWidth
DM_PELSHEIGHT | //dmPelsHeight
DM_BITSPERPEL |
DM_POSITION |
DM_DISPLAYFREQUENCY |
DM_DISPLAYFLAGS; // | DM_DISPLAYORIENTATION;
EnumDisplaySettings((const char*)(it->DeviceName), (int)ENUM_REGISTRY_SETTINGS, &deviceMode);
modes.push_back(deviceMode);
}
m_vDevmode_list = modes;
I used this function to open the Windows desktop shortcut:
ShellExecute(NULL,
NULL,
_T("C:\\Users\\Administrator\\Desktop\\BasePointV - ***.lnk"),
NULL,
NULL,
SW_SHOWNORMAL);
I have a problem:
--------Configuration: Display - Win32 Release--------
Linking...
***.obj : error LNK2001: unresolved external symbol __imp__EnumDisplayDevicesA@16
Debug/***.exe : fatal error LNK1120: 1 unresolved externals
***.exe - 1 error(s), 0 warning(s)
The project I built is MFC AppWinzard(exe);
Environment is:Windows10 VC 6.0
Online solutions include:
Define WINVER 0x0500
Add user32.DLL
There are many good solutions, but the linking problem is not solved yet!
| 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. Something like this:
BOOL EnumDisplayDevices(
LPCSTR lpDevice,
DWORD iDevNum,
PDISPLAY_DEVICEA lpDisplayDevice,
DWORD dwFlags
);
There's two problems with this approach.
First, there's no API called EnumDisplayDevices. There is however, two APIs called EnumDisplayDevicesA and EnumDisplayDevicesW for both Unicode and ANSI builds. The Windows SDK will use a macro to map either one to the thing you can to invoke:
#ifdef UNICODE
#define EnumDisplayDevices EnumDisplayDevicesW
#else
#define EnumDisplayDevices EnumDisplayDevicesA
#endif // !UNICODE
Second, the actual declaration of EnumDisplayDevicesA and EnumDisplayDevicesW will are declared as stdcall calling type, like most Win32 APIs. Your declaration is likely missing this detail.
Hence, you want to declare this:
BOOL __stdcall EnumDisplayDevicesW(
LPCWSTR lpDevice,
DWORD iDevNum,
PDISPLAY_DEVICEW lpDisplayDevice,
DWORD dwFlags);
And this:
BOOL __stdcall EnumDisplayDevicesA(
LPCSTR lpDevice,
DWORD iDevNum,
PDISPLAY_DEVICEA lpDisplayDevice,
DWORD dwFlags);
If you manually declared DISPLAY_DEVICE and PDISPLAY_DEVICE yourself, you may also need to fixup your declaration as well. That's addressed in the sample code below.
Finally, even after you fix this, you still won't have a lib to link with since your version of user32.lib doesn't know anything about this API that came later.
You could find a newer version of the Windows SDK that still works with VC 6.0. But a simpler approach might to LoadLibrary the API directly at runtime. So putting it all together, here's a complete solution in which we'll dynamically load the EnumDisplayDevicesW and EnumDisplayDevicesA functions at runtime. Sample invocation as well:
#include <windows.h>
// BORROWED THIS FROM THE WINDOWS SDK - uncomment it if you need it
#if 0
typedef struct _DISPLAY_DEVICEA {
DWORD cb;
CHAR DeviceName[32];
CHAR DeviceString[128];
DWORD StateFlags;
CHAR DeviceID[128];
CHAR DeviceKey[128];
} DISPLAY_DEVICEA, *PDISPLAY_DEVICEA, *LPDISPLAY_DEVICEA;
typedef struct _DISPLAY_DEVICEW {
DWORD cb;
WCHAR DeviceName[32];
WCHAR DeviceString[128];
DWORD StateFlags;
WCHAR DeviceID[128];
WCHAR DeviceKey[128];
} DISPLAY_DEVICEW, *PDISPLAY_DEVICEW, *LPDISPLAY_DEVICEW;
#ifdef UNICODE
typedef DISPLAY_DEVICEW DISPLAY_DEVICE;
typedef PDISPLAY_DEVICEW PDISPLAY_DEVICE;
typedef LPDISPLAY_DEVICEW LPDISPLAY_DEVICE;
#else
typedef DISPLAY_DEVICEA DISPLAY_DEVICE;
typedef PDISPLAY_DEVICEA PDISPLAY_DEVICE;
typedef LPDISPLAY_DEVICEA LPDISPLAY_DEVICE;
#endif // UNICODE
#endif // if 0
// Declare the function types for EnumDisplayDevices
typedef BOOL(__stdcall* FN_EDD_W)(LPCWSTR, DWORD, PDISPLAY_DEVICEW, DWORD);
typedef BOOL(__stdcall* FN_EDD_A)(LPCSTR, DWORD, PDISPLAY_DEVICEA, DWORD);
int main()
{
FN_EDD_W fnEnumDisplayDevicesW;
FN_EDD_A fnEnumDisplayDevicesA;
// Dynamically load EnumDisplayDevices
HMODULE hMod = LoadLibraryW(L"user32.dll");
fnEnumDisplayDevicesW = (FN_EDD_W)GetProcAddress(hMod, "EnumDisplayDevicesW");
fnEnumDisplayDevicesA = (FN_EDD_A)GetProcAddress(hMod, "EnumDisplayDevicesA");
// now invoke the loaded API function
DISPLAY_DEVICEW device = {};
device.cb = sizeof(device);
fnEnumDisplayDevicesW(NULL, 0, &device, 0); // equivalent to EnumDisplayDevicesW
}
|
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 in C++ .
Here is my code:
#include <iostream>
using namespace std;
class A
{
public:
int num;
void number()
{
cout << "1 for British Pound " << endl;
cout << "2 for Mexican Pesos " << endl;
cout << "3 for Japanese Yen " << endl;
cout << "4 for Chinese Yen " << endl;
cout << "5 for Australian Dollar "
<< "\n\n";
cout << "Enter number here: ";
cin >> num;
}
};
class B : public A
{
private:
float money;
float res;
public:
void ifs()
{
number();
if (num == 1)
{
cout << "Enter how much US money you have: ";
cin >> money;
res = money * 0.77; // British pound is 0.77 for every US dollar.
cout << money << "$ in US is " << res << " in British pounds";
}
if (num == 2)
{
cout << "Enter how much US money you have: ";
cin >> money;
res = money * 20.08; // Mexican Pesos is 20.08 for every US dollar.
cout << money << "$ in US is " << res << " in Mexican Pesos. ";
}
}
};
class C : public B
{
private:
float money, res;
public:
void ifs2()
{
ifs();
if (num == 3)
{
cout << "Enter how much US money you have: ";
cin >> money;
res = money * 125.31; // Japansese Yen is 125.31 for every US dollar.
cout << money << "$ in US is " << res << " in Japanese Yen. ";
}
if (num == 4)
{
cout << "Enter how much US money you have: ";
cin >> money;
res = money * 6.37; // Chinese Yen is 6.37 for every US dollar.
cout << money << "$ in US is " << res << " in Chinese Yen. ";
}
if (num == 5)
{
cout << "Enter how much US money you have: ";
cin >> money;
res = money * 1.35; // Australian Dollar is 1.35 for every US dollar.
cout << money << "$ in US is " << res << " in Australian Dollar. ";
}
else
{
cout << "Please enter a number that is listed above! ";
};
}
};
int main()
{
C obj;
obj.ifs2();
}
// This code is a US currency converter.
// It contains class and methods.
| 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)
{
cout << "Enter how much US money you have: ";
cin >> money;
res = money * 125.31; // Japansese Yen is 125.31 for every US dollar.
cout << money << "$ in US is " << res << " in Japanese Yen. ";
}
else if (num == 4)
{
cout << "Enter how much US money you have: ";
cin >> money;
res = money * 6.37; // Chinese Yen is 6.37 for every US dollar.
cout << money << "$ in US is " << res << " in Chinese Yen. ";
}
else if (num == 5)
{
cout << "Enter how much US money you have: ";
cin >> money;
res = money * 1.35; // Australian Dollar is 1.35 for every US dollar.
cout << money << "$ in US is " << res << " in Australian Dollar. ";
}
else
{
cout << "Please enter a number that is listed above! ";
};
}
};
int main()
{
C obj;
obj.ifs2();
}
|
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 it, unless I change a method whose declaration includes __declspec(dllexport). It appears that I have to add this declaration, since otherwise, a derived issue is that of course the main project has linkage errors.
Is there a more elegant way to do it rather than adding __declspec(dllexport) before the declaration of every public method, like in the code below?
public:
__declspec(dllexport) MyProperty(const std::string &csvLine);
__declspec(dllexport) bool getIsActive();
__declspec(dllexport) std::string getFormatting();
__declspec(dllexport) PropertyType getType();
| 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 thanfor methods - not in front of the complete declaration, but between the class keyword the class name.
As a followup, often a macro is used instead, which is defined to be either __declspec(dllexport) or __declspec(dllimport), depending on some preprocessor condition specifying whether we are currently compiling the dll or trying to use it:
#if defined(MY_DLL)
#define MY_DLL_API __declspec(dllexport)
#else
#define MY_DLL_API __declspec(dllimport)
#endif
class MY_DLL_API MyProperty
{
public:
MyProperty(const std::string &csvLine);
bool getIsActive();
std::string getFormatting();
PropertyType getType();
};
For your dll project, you then define MY_DLL, and for everyone who just uses the dll (without having MY_DLL defined), the header will automatically have the required dllimport.
Important: It is not recommended to pass most STL types across DLL boundaries, see for example Exporting STL class from DLL... or How can I call a function of a C++ DLL ..., as commented also below.
|
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" << std::endl; }
mystring( mystring&& ) { std::cout << "Move" << std::endl; }
mystring( const mystring& ) { std::cout << "Copy" << std::endl; }
mystring& operator=( const mystring& ) { std::cout << "Copy assign" << std::endl; return *this; }
mystring& operator=( mystring&& ) { std::cout << "Move assign" << std::endl; return *this; }
~mystring() { std::cout << "Delete" << std::endl; }
};
And with some test code
int main()
{
std::cout << "1" << std::endl;
mystring ms;
std::cout << "2" << std::endl;
B b(std::move(ms));
std::cout << "3" << std::endl;
}
You will see:
1
Default
2
Copy
Copy
Move
Delete
Delete
3
Delete
Delete
Your question "In this case, str would be copied twice, or not?" is answered: Yes, it copies twice!
you have always to follow rule of three/five/zero if you also want forwarding/move to work as expected.
This will result into:
class A
{
private:
mystring val1;
public:
A(): val1{}{}
A( const mystring& str ): val1( str ) {}
A(mystring&& str) : val1(std::move(str)){}
// if you also want to assign a string later
A& operator=(const mystring& str ) { std::cout << "copy string to A" << std::endl; val1 = str; return *this; }
A& operator=(mystring&& str ) { std::cout << "move string to A" << std::endl; val1 = (std::move(str)); return *this; }
// and now all the stuff for copy/move of class itself:
A( const A& a): val1{ a.val1} {}
A( A&& a): val1{ std::move(a.val1)} {}
A& operator=( const A& a) { std::cout << "copy from A" << std::endl; val1=a.val1; return *this; }
A& operator=( A&& a) { std::cout << "move from A" << std::endl; val1=std::move(a.val1); return *this; }
};
class B: public A
{
public:
B(): A{}{}
B( const mystring& str ): A( str ) {}
B(mystring&& str) : A(std::move(str)){}
// and now all the stuff for copy/move of class itself:
B( const B& b): A{ b} {}
B( B&& b): A{ std::move(b)} {}
B& operator=( const B& b) { std::cout << "copy from B" << std::endl; A::operator=(b); return *this; }
B& operator=( B&& b) { std::cout << "move from B" << std::endl; A::operator=(std::move(b)); return *this; }
};
And now test also this:
int main()
{
std::cout << "1" << std::endl;
mystring ms;
std::cout << "2" << std::endl;
B b(std::move(ms));
std::cout << "3" << std::endl;
//
std::cout << "4" << std::endl;
B b2;
// and now move assign
std::cout << "5" << std::endl;
b = std::move(b2);
std::cout << "6" << std::endl;
}
Result:
1
Default
2
Move
3
4
Default
5
move from B
move from A
Move assign
6
Delete
Delete
Delete
Now you have a single move for first step and the move assign works also as expected.
See it running here
|
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;
//this is cube.h
public:
Cube(double s = 0.0) :side{ s } { //constructor
counter++;
}
};
However, when I separate the interface from the implementation like this:
class Cube {
private:
double side;
static int counter; //static data
//this is cube.h
public:
Cube(double);
};
Its implementation:
#include <iostream>
#include "Cube.h"
int Cube::counter{ 0 };
//this is cube.cpp
Cube::Cube(double s = 0.0) :side{ s } {
counter++;
}
And I go to the main function in source.cpp, Cube c1{}; now gives me the error:
no instance of constructor "Cube::Cube" matches the argument list
Note: When I gave c1 a value, like Cube c1{5}; it works in both cases.
| 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) { for (auto &i : a) i = -i; }
// object 'a' remains available
template<typename T>
auto operator-(const T &a) { std::cout << "1\r\n"; T b = a; neg(b); return b; }
// object 'a' terminates its life
template<typename T>
auto operator-(T &&a) { std::cout << "2\r\n"; neg(a); return std::move(a); }
// make an rvalue
template<typename T1, typename T2>
auto operator+(const T1 &a, const T2 &b) { return a; }
int main()
{
std::array<int, 4> a;
auto d = -(a+a); // outputs 2 : correct
auto e = -a; // outputs 2 : I want 1
auto f = -std::move(a); // outputs 2 : correct
return 0;
}
EDIT: One of the solutions proposed by user17732522 (please upvote him).
template<typename T>
auto operator-(T &&a)
{
std::cout << "2\r\n"; neg(a); return std::move(a);
}
template<typename T>
auto operator-(T &a)
{
std::cout << "1\r\n";
std::remove_cvref_t<T> b = a;
neg(b); return b;
}
int main()
{
std::array<int, 4> a;
auto d = -(a+a); // now outputs 2 : correct
auto e = -a; // now outputs 1 : correct
auto f = -std::move(a); // now outputs 2 : correct
const std::array<int, 4> b{1,2,3,4};
d = -(b+b); // now outputs 2 : correct
e = -b; // now outputs 1 : correct
return 0;
}
Another solution, always based on user17732522 answer, is this:
template<typename T>
requires(!std::is_reference_v<T>)
auto operator-(T &&a);
template<typename T>
auto operator-(const T &a);
| 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 deduction have a function parameter U& and consequently neither will be better based on that.
However, in partial ordering of function templates the T& template will win over T&& and so the former will be chosen if the function argument is a lvalue.
This does however have the consequence that a in the function will not be const qualified. You can obtain a const reference from it by applying std::as_const.
Alternatively you can use a requires clause or std::enable_if to constrain the T&& template on T being a non-reference type. Or you can use a single function template and decide in its body how to operate based on the type of the reference with if constexpr. Relevant type traits: std::is_lvalue_reference_v<T> or std::is_reference_v<T> and std::is_lvalue_reference_v<decltype(a)>.
|
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 capturing a small object (like an 8-sized pointer) is much smaller than a std::function
Do you have any better idea to save that unnecessary space-usage?
| 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 name) and make a vector of that type.
Example: With lambda:
std::vector<std::function<void()>> funcs;
for(int i = 0; i < 10000; i++)
funcs.push_back([i]() {std::cout << i << std::endl;});
for(auto& func : funcs)
func();
With functor:
struct number_printing_function {
int i;
number_printing_function(int i) : i(i) {}
void operator()() {
std::cout << i << std::endl;
}
};
std::vector<number_printing_function> funcs;
for(int i = 0; i < 10000; i++)
funcs.push_back(number_printing_function(i));
// or funcs.emplace_back(i);
for(auto& func : funcs)
func();
IMO this is a bit useless, because we might as well store a vector of ints and stop pretending they are functions. When you have many functors of the same type you already know what they do, so just do it. Really, the code above is just the code below, but with extra steps:
std::vector<int> ints;
for(int i = 0; i < 10000; i++)
ints.push_back(i);
for(auto& i : ints)
std::cout << i << std::endl;
|
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 data as whole datagram.
# If there are more pending datagrams, it will called more than once
pass
The asyncio eventloop receives whole datagrams. But when I use BSD socket, I should use all or part of received data. Total data can be greater than one datagram. And I don't know the bounds of this data. I just can parse it by using of my own algorithms (read heading, count of bytes in body, etc).
if (ioctlsocket(Socket, FIONREAD, (u_long*)(&PendingDataSize)) == 0)
{
BytesRead = recv(Socket, (char*)Data, PendingDataSize, Flags);
// Now I can use Data and parse it here.
// But Data can be two or more datagrams if remote machine sent two or more packets?
}
How can I repeat the behavior of asyncio but with just BSD sockets?
| 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 still executing.
Could you tell me how I can solve this?
void MainWindow::ejecutarModoDemo()
{
this->md->show();
this->md->setIniciar();
//when pushbutton is clicked in the md window, it change to true
while(!this->md->getTerminar()){
srand(time(NULL));
girarPlato(8 + rand()%8);
QThread::msleep(5000);
tragarBola();
while(obtenerSTA()!=1){
QThread::msleep(1000);
}
QThread::msleep(2000);
girarPlato(20 + rand()%10);
lanzarBola(900 + rand()%600);
mostrarGanador();
}
detenerMotor();
this->md->hide();
}
| 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 QCoreApplication::processEvents()
Typically, computations that take a while should run in a separate background thread, not in the GUI thread. For a "quick fix", you might get away with QCoreApplication::processEvents() in between computation steps; but you need to make sure that the single steps of the computation are very short then; let's say less than 100ms.
Reacting on the press of a button in Qt typically happens with the signal-slot mechanism.
|
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()::<lambda(auto:1)>' and 'main()::<lambda(int)>'
2 | true ? [](auto) noexcept {} : [](int) {};
| ~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Clang-trunk accepts it in all C++14/17/20 mode (Demo).
MSVC-trunk only accepts it in C++20 but rejects it in C++14/17 with (Demo):
<source>(2): error C2446: ':': no conversion from 'main::<lambda_01e5bb79b5a210014fb78333f6af80f9>' to 'main::<lambda_57cf6f5767bc1bee4c1e1d9859a585d2>'
<source>(2): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
Which compiler is right?
| 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 applied to the operands ([over.match.oper], [over.built]). If the overload resolution fails, the program is ill-formed.
Otherwise, the conversions thus determined are applied, and the converted operands are used in place of the original operands for the remainder of this subclause.
The candidates are ([over.built]/25):
For every type T, where T is a pointer, pointer-to-member, or scoped enumeration type, there exist candidate operator functions of the form
T operator?:(bool, T, T);
I believe that overload resolution should succeed in this case, and as a result, both operands should be converted to void(*)(int).
That is, IMO clang is correct.
Edit: I believe that [](auto) noexcept {} is convertible to void(*)(int), because it has a conversion function template template<class T> operator FP(), where FP is void(*)(T) ([expr.prim.lambda.closure]/9).
For a generic lambda with no lambda-capture, the closure type has a conversion function template to pointer to function.
The conversion function template has the same invented template parameter list, and the pointer to function has the same parameter types, as the function call operator template.
The return type of the pointer to function shall behave as if it were a decltype-specifier denoting the return type of the corresponding function call operator template specialization.
And I believe that template argument deduction should make this conversion template usable as a conversion to void(*)(int) ([temp.deduct.conv]/5).
Template argument deduction is done by comparing the return type of the conversion function template (call it P) with the type specified by the conversion-type-id of the conversion-function-id being looked up (call it A) as described in [temp.deduct.type].
[...]
In general, the deduction process attempts to find template argument values that will make the deduced A identical to A.
However, certain attributes of A may be ignored:
[...]
If the original A is a function pointer or pointer-to-member-function type, its noexcept.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.