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 |
|---|---|---|---|---|
72,550,013 | 72,550,128 | std::array<int> iterator convertible to int* on clang but not MSVC? | So I have some code like
void func( const int* begin, const int* end );
and then want to use std::array<int, X> to have the data stored, and then call the function like so:
std::array<int, 5> data = {1,2,3,4,5};
func( data.begin(), data.end() );
When using clang, the iterator apparently is implicitly convertible to c... | The iterator for std::array<int> doesn't necessarily have to be int*, it's just std::array<int>::iterator, which is up to the individual compiler implementation to decide what it should be.
the standard library provides a function to reliably convert iterators into raw pointers:
std::addressof(*iterator)
Although this ... |
72,550,479 | 72,552,506 | How to transpose a 4D tensor in C++? | I need to pre-process the input of an ML model into the correct shape.
In order to do that, I need to transpose a tensor from ncnn in C++.
The API does not offer a transpose, so I am trying to implement my own transpose function.
The input tensor has the shape (1, 640, 640, 3) (for batch, x, y and color) and I need to ... | I'm only talking about index calculations, not the ncnn API which I'm not familiar with.
You set
fromIndex = i*A + j*B + k*C + l*D;
toIndex = i*E + j*F + k*G + l*H;
where you compute A B C D E F G H based on the source and target layout. How?
Let's look at a simple 2D transposition first. Transpose a hw layout matr... |
72,550,738 | 72,552,174 | How to store Huffman tree in file | I'm looking for a convenient way to store Huffman tree inside the file for further reading and decoding. Here is my Node structure:
struct Node
{
char ch;
int freq;
Node *left, *right;
Node(char symbol, int frequency, Node *left_Node, Node *right_Node) : ch(symbol),
... | Traverse the tree recursively. At each node, send a 0 bit. At each leaf (pointers are nullptr), send a 1 bit, followed by the eight bits of the character.
On the other end, read a bit, make a new node if it's a zero. If it's a 1, make a leaf with the next eight bits as a character. Proceed to the next empty pointer. Th... |
72,550,741 | 72,550,946 | Can I create constexpr strings with functions? | I have a method that creates a file header with a given comment symbol, depending on the output file type. There are only a few supported file types, thus I want to create these headers at compile time. Can I make these as a constexpr ?
std::string create_header(const std::string &comment_symbol) {
std::string div(... |
Can I create constexpr strings with functions?
You can't return std::string, cause it allocates memory.
Can I make these as a constexpr ?
Sure, something along:
#include <array>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
template<size_t N> constexpr
auto create_header(const char ... |
72,550,973 | 72,552,772 | libtiff: How to get values from the TIFFGetField routine? | I have a .tif file and would like to get the image width using libtif.
I have tried the following c++ code so far:
TIFF* tif = XTIFFOpen(filenameStr.c_str(), "w");
if (!tif) {
std::cout << "Error: failed to open file" << std::endl;
}
int32_t width = 0;
int test = TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);
std:... | The function TIFFGetField() doesn't return a value. Instead it modifies the variable whose address you pass:
uint32_t width;
TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);
std::cout << width << std::endl;
|
72,551,469 | 72,551,514 | sum of array elements using recursion | #include<iostream>
using namespace std;
int getSum(int *arr, int size) {
if(size == 0) {
return 0;
}
if(size == 1 )
{
return arr[0];
}
int remainingPart = getSum(arr+1, size-1);
int sum = arr[0] + remainingPart;
return sum;
}
int main() {
int arr[100], n;
cin >> ... | cin >> arr[n];
should be
cin >> arr[i];
|
72,551,989 | 72,552,118 | p in Hexadecimal floating point constant | C++17 allows defining floating point constants in hexadecimal format like
double d1 = 0x1.2p3; // 9.0
double d2 = 0x1.86Ap+16 // 100000.0
In hexadecimal floating point constants the mantissa and exponent is separated using the letter p|P.
Why C++ standard committee decided to use the letter p|P instead of any other... | From https://en.wikipedia.org/wiki/Hexadecimal#Hexadecimal_exponential_notation :
By convention, the letter P (or p, for "power") represents times two raised to the power of, [...]
Why C++ standard committee decided to use the letter p|P instead of any other letter?
Because it was so in C. It wasn't in B, so must h... |
72,552,310 | 72,552,625 | How to stop user from entering a duplicate integer in the vector in (C++)? | // Using switch statement
// Vectors & Variables required to store selection and list of items
vector <int> list_items{};
char selection{};
int list_adder{};
do {
// Displaying Menu Options First:
cout << "\n" << endl;
cout << "P - Print numbers" << endl;
... | If you really want to use a vector to store the list items, you can use std::find to check if the item already exists in the vector. std::find returns an iterator to the found item or the end() iterator if it was not found.
if(std::cin >> list_adder) {
if(std::find(list_items.begin(), list_items.end(), list_adder) ... |
72,552,346 | 72,552,448 | Delete nodes at positions divisible by 5 in linked list | I'm trying to delete every node at positions divisible by 5. With my approach I cannot seem to delete the last node:
void removeDivFive(Node* head){
int count = 0;
Node* temp = head;
while(temp != NULL){
count++;
if(count%5==0){
if(temp->next != NULL){
temp->... | First off, you are leaking the nodes you "remove". You need to actually destroy them since they are no longer being used.
Now, regarding your actual problem - what do you thing temp->next points at when the last node in the list is at a position divisible by 5? NOTHING! Thus, if (temp->next != NULL) evaluates as false,... |
72,552,568 | 72,555,951 | CMAKE include src and install directories on different OS | I am learning to use CMake and trying to understand where should I place files from different open-source libraries when I download them. I am talking about install location.
On linux include directory is this by convention: /usr/local/include/
What is default location for Windows and Mac OS?
I know that these location... | On windows usually the install prefix is something like C:/Program Files/<Package Name>, the usual install prefix on Unix being /usr/local. Usually this directory contains subdirectories like include containing the headers, lib containing (import) libraries, ect..
Using MSVC for the Windows targets those include direct... |
72,552,669 | 72,552,736 | Templated class with constructor arguments | Consider this class:
template <typename t>
class Something
{
public:
Something(t theValue) {mValue=theValue;}
t mValue;
};
When I do this, everything is okay:
Something<float>* mSomething=new Something<float>(100);
HOWEVER, if I try to do this:
Something<float> mSomething(100);
I am declaring the above insid... | You may not use such an initializer as a function call
class SomethingElse
{
public:
Something<float> mSomething(100);
};
You need to use an equal or braced initializer. For example
class SomethingElse
{
public:
Something<float> mSomething { 100 };
};
Here is a demonstration program.
template <typename t>
c... |
72,552,730 | 72,557,588 | Should I prefer glMapBufferRange over glMapBuffer? | The documentation for glMapBuffer says it can only use the enum access specifiers of GL_READ_ONLY, GL_WRITE_ONLY, or GL_READ_WRITE.
The documentation for glMapBufferRange says it uses bitflag access specifiers instead, which include a way to persistently map the buffer with GL_MAP_PERSISTENT_BIT.
I want to map the buff... | glMapBufferRange was first introduced in OpenGL 3. OpenGL has evolved to provide more control to developers while keeping backwards compatibility as much as possible. So glMapBuffer remained unchanged, and glMapBufferRange introduced the explicitness that developers wanted (not only the subrange part, but also other bi... |
72,552,890 | 72,557,227 | How to pass a 3D element into JNI? | I am working on a project and need to do some calculations with a 3D array in C++. I need to pass this 3D array from Java to C++, do some calculations, then return it. I am using JNI and am very new to it so I don't know very much. I am trying to make a sample program to test this and to use it as reference. I have got... | Just structure your program like your data:
float* thirdLevel(JNIEnv *env, jfloatArray arr) {
jsize len = env->GetArrayLength(arr);
float* ret = new float[len];
env->GetFloatArrayRegion(arr, 0, len, ret);
return ret;
}
float** secondLevel(JNIEnv *env, jobjectArray arr) {
jsize len = env->GetArrayLength(arr);... |
72,552,941 | 72,553,323 | Transform a vector of elements into another vector of elements in parallel, without requiring the latter to be initialized | I have a const std::vector<T> source of a big size, and a std::vector<T> dest.
I want to apply a transformation to each element in source and store it in dest; all of this in parallel, and knowing that T is not default constructible.
What I initially attempted was using std::transform with a parallel execution policy:
... | Try using a std::vector<> of std::optional<T>:
#include <algorithm>
#include <execution>
#include <optional>
#include <vector>
struct T { // NOTE: T is NOT default-constructible!
T(int x) : value(x) {}
operator int() { return value; }
int value;
};
T op(const T& in) {
return in.value * 2;
}
#include ... |
72,553,505 | 72,553,559 | Can you use templates to nest an enum class inside a containing class | I an trying to describe a sensor CFA in a class or struct. Id like to be able to do something like this:
enum class cfa_type
{
RGGB,
RCCB
};
enum class RGGB_ch
{
R,
G1,
G2,
B
};
enum class RCCB_ch
{
R,
C1,
C2,
B
};
template <typename CH>
struct CFA
{
cfa_type type;
CH ch;
CFA(cfa_type t) : ... | Type is not a variable.
static_cast<int>(decltype(RGGB.ch)::R);
|
72,553,566 | 72,560,969 | SDL.h No such file or directory in VSCode | I'm trying to add the relevant "-I"path_to_your_SDL_include_directory"" as outlined in several similar posts such as this one. I have tried three approaches;, adding it to tasks.json, Makefile and c_cpp_properties.json.
My file structure is as follows. My main.cpp is in MyProject/src. I have copied all the contents of ... | It is clear that you have two problems.
The VSCode's C++ extension complains about the file SDL2.h
There's a linking problema when you compile from your Makefile
Let's address the Makefile thing first:
There's a typo in your Makefile, it says SDL2_lib/libr instead of SDL2_lib/lib.
After fixing that, you must add the ... |
72,553,871 | 72,554,057 | Dealing with special characters in CLI11 | I have code like the following
flags->add_option("--name", name_, "The name.")->required();
I want to be able to pass strings like "aa$p$aa" to the --name parameter. However, this does not seem to work with CLI11, and the name gets truncated to just "aa". I need to escape the $ characters to properly read the strings.... | Your operating system takes the command you type in and executes the given program, passing the parameters to it.
The interpolation, and the handling of $ characters in typed-in commands is handled by your operating system as part of executing the typed-in command. Your compiled C++ program receives the transformed arg... |
72,554,196 | 72,554,238 | How to identify all C++ standard library calls in source code? | I want to get the information about how many kind of C++ standard library features are used in my application source code, e.g., whether vector is used or some STL algorithm is used? For C library, I know that I can use objdump -T | grep GLIBC on the compiled binary as the post how to identify all libc calls at compile... | Many components of the C++ standard library are templates. Other non-template functions could be declared inline. In either case, there's no guarantee that there will be a call to a function visible in the assembly. The compiler could easily inline all of these, and there would be virtually no way to tell that this had... |
72,554,304 | 72,554,459 | Why can't C++ deduce a template type argument from a function pointer prototype individually but not as a pack? | This code compiles with both gcc and clang:
#define PACK //...
template <typename Result, typename PACK Args, typename Last>
auto g(Result (*f)(Args PACK, Last)) -> Result (*)(Args PACK)
{
return reinterpret_cast<Result (*)(Args PACK)>(f);
}
double af(char c, int i);
auto ag{g(&af)};
However, if I change the fi... | The correct syntax for the second case to work would be as shown below. Note how the order of Last and Args... is changed.
Method 1
//----------------------------------------------------vvvv--->OK: Last is deducible
template <typename Result, typename... Args, typename Last>
auto g(Result (*f)(Last, Args...)) -> Result... |
72,554,498 | 72,554,708 | Cannot compile `enqueue_kernel` on opencl 2.1 NEO device | I have the following code on the device Intel(R) Gen9 HD Graphics NEO -- OpenCL 2.1 NEO :
__kernel void update(
const __global uint* positions,
const __global float3* offsets,
const int size,
__global int* cost
) {
int global_id = get_global_id(0);
if (global_id >= size) {
return;
... | When compiling, it is not just the version of the device that is important. The compiled version of cl code is passed into the compilation options. AKA the compilation options when compiling the opencl program (kernel code) should include:
-cl-std=CL2.0
Or the specific standard that you are looking for.
|
72,554,588 | 72,554,691 | How to receive strings with ncurses? | I'm trying to ask the user to enter a random word, but when I go to try to store it, the normal cin isn't working and just seems to be confusing ncurses. I've tried other functions like wgetstr() but it takes a char and not a string. I've been attempting multiple conversion functions like c_str() but nothing. Does anyb... | getstr() family of functions do return null-terminated strings, not just a single character. It's C library, there isn't any std::string type.
You must supply a suitable large buffer for the functions. It is more safe to use getnstr which limits the number of read characters.
char buffer[256];
int result = getnstr(buff... |
72,554,871 | 72,640,087 | How to know if a .tflite file can run on a specific edge device in C++ before attempting inference? | I am trying to write a logic that checks to see whether an Android device is capable of runniing an inference of a given .tflite file.
How can I go about implementing a logic for device-model compatibility in C++?
| If you compiled your TFLite library (or used gradle dependency) for arm/arm64 then it should work on the device no need for check here.
If you're trying to use a specific delegate or different hardware then please explain it so we can help.
|
72,554,913 | 72,555,095 | Do instances of this clone method point back to the original object? | I'm not a C++ guru, navigating some code from an open source project trying to resolve an issue we have with the Java interface and the documentation is terrible. We've resolved that it may be due to the fact that a cloned object is what is used and not the originally instantiated object. The clone is created in the fo... | This expression
new Computer(*this) calls the copy constructor Computer::Computer(const Computer&), whatever happens in there depends on its implementation.
Default implementation provided by the compiler (given the requirements for its generation are met) does member-wise copy of all attributes. "copy" means calling c... |
72,555,103 | 72,646,222 | udata.cpp: undefined reference to `icudt71_dat' | I am getting an odd ICU related linking error in the now project when building on Ubuntu 22.04.
/usr/bin/ld: /usr/bin/ld: DWARF error: invalid or unhandled FORM value: 0x23
/home/bkey1/vcpkg/installed/x64-linux/debug/lib/libicuuc.a(udata.ao): in function `openCommonData(char const*, int, UErrorCode*)':
udata.cpp:(.text... | First I would like to stress, that there is very little information provided, so the answers such as my own will most likely need to guess what is happening. On the other hand I understand your situation: you cannot include info, that you don't know is relevant to the topic.
Answer:
I would like to draw your attention ... |
72,555,442 | 72,556,632 | How to put my function into a thread Qt Concurrent | I have function like this
QList<MyObject*> list;
for (int i = 0; i < count; ++i)
{
auto *object = new MyObject(this);
ProcessFunc1(object);
ProcessFunc2(object);
ProcessFunc3(object); // a heavy function that I would like to parallelize
list.push_back(object);
}
return list;
I need to corre... | // create the objects in the main thread:
// creating objects in another thread can result in pain,
// see e.g. https://doc.qt.io/qt-6/qobject.html#thread-affinity
QList<MyObject *> list;
for (int i = 0; i < count; ++i)
list.emplaceBack(this); // equivalent to list.append(new MyObject(this))
// "map" (== "apply") y... |
72,555,869 | 72,557,773 | Deleting data while looping through a list | I'm having trouble figuring out how to delete an item from a list.
Please note that I would like to perform the deletion from the advance() function. This code is just boiled down from my actual project, to try to isolate the error.
#include <iostream>
#include <list>
#include <iterator>
#include <algorithm>
using nam... | So the problem is nothing to do with deletion from a list. Your logic is simply wrong given the stated goal.
You want to delete all SCT_OSC_FILLED items from the list when adding an item but the code you write deletes all items from the list when you add an item with SCT_OSC_FILLED. You are simply testing the wrong thi... |
72,556,628 | 73,031,442 | clangd cannot parse stl lib header | I met a issue when I config my neovim lsp. My lsp client is nvim-lspconfig and clangd is my lsp server.
Here is my clangd setup arguments
require('lspconfig')['clangd'].setup {
on_attach = on_attach,
flags = {
-- This will be the default in neovim 0.7+
debounce_text_changes = 150,
},
capabilities = capa... | After check the clangd logs. I think It's the same issue as
https://github.com/clangd/clangd/issues/1100
|
72,557,386 | 72,557,487 | virtual method ignored in tempate inheritance | I've tried searching for some explanations about how this exact pattern of inheritance works, but never found anything quite similar, so I hope some of you guys know what's going on.
So here's the behaviour I want to get:
#include <iostream>
template <typename T, typename F = std::less<T>>
class Base
{
protected:
... | virtual means that either Base::f or Derived::f is called depending on the dynamic type of the object.
The fact that you only call Derived<int>::f in main does not change that Base<std::pair<int,int>,std::less<int>::f is not valid.
A much simpler example with same issue is this:
#include <utility>
struct base {
v... |
72,557,450 | 72,557,546 | What does this function do? I understand the recursion aspect but am confused with the following operations | class Node{
public:
int data;
Node* next;
};
int func(Node* node, int number){
if(node){ //whilst the node does not equal null pointer
if(node->data > 0) // if the data is greater than 0
return func(node->next, number) - node->data; // this is where i get confused...
else if(node->data < 0)
re... |
subtracts the child nodes data from the parent node
No, it subtracts node->data from the result of the recursive call.
What is the function trying to achieve?
Ask the author. What we can tell you is what it does achieve. I am suspicious of the author's understanding of this function because number + node->data appe... |
72,557,597 | 72,558,416 | How to choose between `std::vector<char>` and `std::string`? | What aspects need to be considered when making such a choice?
My two cents about this question:
1.The std::string is still valid even if there is a \0 in the middle of data stream.
2.std::string have many useful methods which could manipulate strings, whereas std::vector<char> does not provide.
3.If the data is just bi... |
What aspects need to be considered when making such a choice?
What is the input data and what is it going to be used for in the future? That would be a big consideration.
If the input data is not going to be used as a string in the future, it may be clearer in the future if you used a container as specified in the co... |
72,557,697 | 72,557,882 | C++ gcc does associative-math flag disable float NAN values? | I'm working with statistic functions with a lot of float data. I want it to run faster but Ofast disable NAN (fno-finite-math-only flag), which is not allowed in my case.
In this case, is it safe to turn on only associative-math ? I think this flag allows things like vectorized sum of vector array, even if the array co... | From the docs:
NOTE: re-ordering may change the sign of zero as well as ignore NaNs
So if you want correct handling of NaNs, you should not use -fassociative-math.
|
72,557,698 | 72,558,253 | Constant value error in array declaration | While writing my code on Visual Studio 2022, I came across the error (E0028) that the expression must have a constant value in line 11.
#include <iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter"<<endl;
cin>>n;
int a[n]; //error line
for(int i = 0; i<n; i++)
{... | The size of an array variable must be compile time constant. n is not compile time constant, and hence the program is ill-formed. This is why the program doesn't compile, and why you get the error "expression must have a constant value".
But when I put the same code in any online compiler, it worked fine. How does thi... |
72,557,858 | 72,558,934 | Cannot construct an instance of a template class, within a member template function of that template class | I have a template class defined as so:
template<typename T> class C_SharedResource : public C_Instance
{
// ...
private:
std::shared_ptr<T> g_resource;
S_AutoDestructionData g_autoDestructionData{};
// ...
public:
C_SharedResource() {}
C_SharedResource(const T& in_resource, S_AutoDestructionDat... | You get the compiler error because struct S_AutoDestructionData is a nested type:
template<typename T> class C_SharedResource : public C_Instance
{
public:
struct S_AutoDestructionData
{
bool m_autoDestroyAllInstances = false;
bool m_transferAutoDestructionState = false;
};
// ...
... |
72,559,257 | 72,559,469 | Why are STL's iterators exposing their container's internals? Why are iterator's member variables mostly public? | std::list's iterator is a struct, not a class.
In some implementations, it has the node pointer public and accessible to the user. Therefore, a user should be able to "accidentally" modify a link and break the relationships within the list through an iterator. Why is this possible?
I do get that the member functions of... |
Why are STL's iterators exposing their container's internals?
They don't.
Why doesn't the standard require the iterators' internals to be private?
Because that would be of no gain. The standard does not specify that the members are publicly accessible and that should be enough to know that you shall not write code ... |
72,559,640 | 72,559,721 | Is there a way to initialize object, call its method, then pass it as function argument, in just the function call scope? | Is there a way to initialize an object, call a few of its method (it is not possible to just construct the object to be in the needed state), then pass it as an argument to a function, and possibly one-liner, just in the calling scope? Something like this:
#include <iostream>
#include <sstream>
void log(const std::ostr... | You can write it like this:
#include <iostream>
#include <sstream>
void log(const std::ostringstream& obj) {
std::cout<<obj.str();
//Do something meaningful with obj that doesn't modify it
}
void gol(const std::string& obj) {
std::cout<<obj;
//Do something meaningful with obj that doesn't modify it
}
i... |
72,559,885 | 72,560,102 | C++ call member method vs normal function overhead | Suppose whatever C++ class that performs an operation like this:
void MyClass::operation()
{
// final sum it's just a class member
finalSum = {0};
for (int i = 0; i < 100; i++)
if (i % 2 = 0)
finalSum += 2;
else
finalSum += 1;
}
Instead of write a bunch of operation... | Don't do premature optimization. Correctness is much more important than performance. The fastest code is worth nothing when it does not compile or produce wrong output.
Write code to be readable. Readable code is easier to test, debug and to refactor. Once you have working correct code you can measure to see where are... |
72,559,926 | 72,560,859 | C++ How do I put a lambda into a map? | I need to initialize a bunch of template classes by reading a "configuration file".
Template class is something like:
class generic_block {
protected:
std::string name;
std::size_t size;
public:
generic_block(std::string _name, std::size_t _size)
: name(_name)
, size(_size)
{
}
virtual... | You can use std::function to explicitly describe the lambda:
std::map<std::string, std::function<generic_block(char*, int)>> types = {
{"uint32_t", [](char *name, int count){
// ...
}},
{"float", [](char *name, int count){
// ...
}}
};
auto& block_generator = typ... |
72,560,446 | 72,560,741 | nested template struct in concept | I have struct like that :
struct i32 {
template<int32_t x>
struct val {
static constexpr int32_t v = x;
};
template<typename v1, typename v2>
struct add {
using type = val<v1::v + v2::v>;
};
template<typename v1, typename v2>
using add_t = typename add<v1, v2>::type;
};... | The typename in the requires-clause is followed by a type rather than a template. Since T::val is a class template that accepts a numeric value, simply instantiating T::val with 0 should be enough
template<typename T, typename val = typename T::template val<0>>
concept RingConcept = requires {
typename T::template ad... |
72,561,420 | 72,561,674 | factory creating different types according to enum values c++ | I have some auto generated structs each logically related to a enum value.
can I create a factory using a template function?
everything can be resolved at compiled time.
I tried something like this:
struct Type1
{
};
struct Type2
{
};
enum class type_t
{
first,
second
};
template <type_t typet>
auto Get_... | In C++11 (and above), you may use an auxiliary traits struct like the following:
template <type_t T>
struct type_selector;
template <>
struct type_selector<type_t::first> {
using type = Type1;
};
template <>
struct type_selector<type_t::second> {
using type = Type2;
};
// implement other specializations, if ... |
72,561,713 | 72,562,059 | Data race guarded by if (false)... what does the standard say? | Consider the following situation
// Global
int x = 0; // not atomic
// Thread 1
x = 1;
// Thread 2
if (false)
x = 2;
Does this constitute a data race according to the standard?
[intro.races] says:
Two expression evaluations conflict if one of them modifies a memory location (4.4) and the other one reads
or modi... | The key term is "expression evaluation". Take the very simple example:
int a = 0;
for (int i = 0; i != 10; ++i)
++a;
There's one expression ++a, but 10 evaluations. These are all ordered: the 5th evaluation happens-before the 6th evaluation. And the evaluations of ++a are interleaved with the evaluations of i!=10.... |
72,563,696 | 72,563,823 | I can't get output numbers with ctypes cuda | cuda1.cu
#include <iostream>
using namespace std ;
# define DELLEXPORT extern "C" __declspec(dllexport)
__global__ void kernel(long* answer = 0){
*answer = threadIdx.x + (blockIdx.x * blockDim.x);
}
DELLEXPORT void resoult(long* h_answer){
long* d_answer = 0;
cudaMalloc(&d_answer, sizeof(long));
... | cudaMemcpy is expecting pointers for dst and src.
In your function resoult, h_answer is a pointer to a long allocated by the caller.
Since it's already the pointer where the data should be copied to, you should use it as is and not take it's address by using &h_answer.
Therefore you need to change your cudaMemcpy from:... |
72,563,728 | 72,563,841 | loops missing the nested if | My loop is skipping the nested 3rd else if. What should I do so it does not skip it?
#include <iostream>
int main()
{
int loop, i;
loop = 0;
char choice, selection;
std::cout << "Welcome" << std::endl;
while (loop == 0)
{
std::cout << "Please a choice" << std::endl;
std::c... | Your loop runs only while i is in the range 1..4 inclusive, so i < 5 will always be true and i > 5 will never be true.
You should check the value of i after the loop exits. You should also check the user's input to make sure it matches your expectations.
Try something more like this:
#include <iostream>
#include <ccty... |
72,564,050 | 72,564,765 | Given list of horizontal lines in array, find the vertical lines that crosses the most lines | Problem
Horizontal lines such as (6 to 10), (9 to 11), (1, 20) which is point a to b are given and code should find a line that crosses maximum number of horizontal lines.
So, the following lines below, the answer is 3 because the maximum number a vertical line can be made goes through 3 lines.
Example
6 10
10 14
1 5
8... | Consider the example of two intervals
0 1000000
42 44
You don't need a loop from 0 till 1000000 to find that 43 is inside both intervals.
You only need to consider the end points of the intervalls. When they are sorted they are 0,42,44,1000000. Then loop those end points. When the end point is the start of an interv... |
72,564,400 | 72,564,578 | C++20 conditional import statements | There's a way to conditionaly use import statements with the C++20 modules feature?
// Pseudocode
IF OS == WINDOWS:
import std.io;
ELSE:
import <iostream>;
| You use macros, just like you would for most other conditional compilation operations. And yes, this means that modules have to be built differently for different command line options. But that was always going to be the case.
Also FYI: std.io is a thing provided by MSVC, not Windows. And you should avoid using it due ... |
72,564,729 | 72,565,222 | How can I return the turbulence sequence with a complexity of O(n)? | #include <iostream>
#include <utility>
using namespace std;
pair<int,int> findLongestTurbulence(int arr[], int n){
pair<int,int> ret = {0,-1};
int a = -1;
for(int start = 0; start < n ; start++ ){
a = -1;
for(int end = start+1; end < n ; end ++){
if(a == -1){
i... | I admit that your code is too complicated for me. I tried it, but I dont understand it. Anyhow, it can be done with a single loop. To keep it simple I would use two loops (though not nested!). One loop to see if arr[i] < arr[i+1] or arr[i] > arr[i+1].
Also too keep it simple you can exclude the case of arr[i] == arr[i+... |
72,564,805 | 72,564,972 | What is this C++ syntax for looping through variadic templates? | I came across this syntax while reading up on std::integer_sequence.
What does this double bracket do? It looks like some form of loop. Does it only work with non-type template parameters? Must it be in the same order as the parameters? Can we iterate backwards? Skip a number?
// pretty-print a tuple
template<class Ch,... | There is documentation about this: fold expression
In short, in this case ... means repeating the specified operator for all parameters in the pack. So, in this case, it will be unpacked as a sequence of expressions separated by commas for each subsequent element of Is, like this:
(os << "" << std::get<0>(t)), (os << "... |
72,565,139 | 72,565,808 | Guide C++ Function Template Type | I have the following, it accepts a function pointer type, and returns the typeid of each argument in a vector.
template <typename Ret, typename... Types>
auto ArgTypes(Ret(*pFn)(Types...))
{
std::vector<std::type_index> vec;
vec.insert(vec.end(), {typeid(Types)...});
return vec;
}
I invoke it like this:
ty... | Thanks everyone, I've combined the answers and comments with some external help into the following:
#include <iostream>
#include <typeinfo>
#include <typeindex>
#include <span>
typedef int (*tExampleFn) (int a,bool b,char* c,long long d);
template<typename T>
struct arg_types {};
template<typename R, typename... A>
... |
72,565,282 | 72,565,767 | Encountring error: no type named ‘iterator_category’ in ‘struct std::iterator_traits<std::vector<int> > | I am trying to create a program which will sort the sequence on integers based on iterators (whether forward iterator or random access iterator). But I am encountering this error when I am trying to pass vector:
error: no type named ‘iterator_category’ in ‘struct std::iterator_traits<std::vector<int> >
Same issue I a... | In your testSort() function, the Iter template argument (whose name is misleading, BTW) is receiving the container type, but iterator_traits wants an iterator type instead.
This will work in your example:
template<class Container>
void testSort(Container& c){
sort_helper(c.begin(), c.end(),
typename std::it... |
72,565,379 | 72,565,473 | How i could print n number of parameters of any data type to a debug? | I know of the WINAPI OutputDebugString(L"");
How I could go with a function able to receive n number of parameters which any data type, and print the value to a debug?
By debug I mean a window similar of the Visual Studio Output.
| This can be achieved with a template:
#include <utility>
#include <iomanip>
#include <sstream>
template <typename Arg, typename... Args>
void Print(Arg&& arg, Args&&... args)
{
std::stringstream ss;
ss<< std::forward<Arg>(arg);
using expander = int[];
(void)exp... |
72,565,403 | 72,625,505 | How to embed python into C++ aplication and then deploy/release? | I am currently working on a C++ gui application. The application uses the Python/C API to call some python scripts. The scripts are located in the solution directory, and I call them by simply providing the path. This is currently working fine while debugging the application or even running the generated .exe file, but... | PyImport_ImportModule("requests")
The parameter is "requests".
Put the py file aside exe file when distributing.
|
72,565,567 | 72,565,638 | Best way to apply a void function to a parameter pack | I would like to write a function that applies a function to each element of a parameter pack. The functions returns a std::tuple with the results of each invocation.
However, if the applied function returns void, I have to do something else, so I have a different overload for this case. But, almost all the ways I've fo... | This trick is the way to go pre-C++17, except that you need an extra , 0 in the array to support zero-length packs.
In C++17 and newer, use a fold expression: (f(args), ...);.
Note that you forgot perfect forwarding. You should be doing F &&f, Args &&... args, and then (f(std::forward<Args>(args)), ...);, and similarl... |
72,565,709 | 72,565,744 | C++ Linked list error: taking address of rvalue [-fpermissive] | I'm getting the error:
taking address of rvalue [-fpermissive]
31 | ListNode l = ListNode(2, &ListNode(4));
when executing the following code:
#include<iostream>
class ListNode {
public:
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
... | You would get exactly the same error with a struct. The problem is that you are taking the address of a temporary object, here &ListNode(4) and that's bad because the address will live longer than the object, and you end up with a pointer to an object which no longer exists.
To fix, turn the temporary object into a var... |
72,566,306 | 72,566,558 | Unable to find Boost libraries with CMake and vcpkg | I have installed boost-variant2 library using the vcpkg command:
vcpkg install boost-variant2:x64-windows
When vcpkg finished the installation, it prompted this:
The package boost is compatible with built-in CMake targets:
find_package(Boost REQUIRED [COMPONENTS <libs>...])
target_link_libraries(main PRIVATE... | Looks like variant2 is header-only lib and you can just use Cmake file like this:
cmake_minimum_required(VERSION 3.5)
project(project LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(Boost)
include_directories(${Boost_INCLUDE_DIRS})
add_executable(project main.cpp)
U can se... |
72,566,483 | 72,567,382 | std::atomic::notify_one could unblock multiple threads | According to cppreference, std::atomic<T>::notify_one() will notify at least one thread that is waiting on said atomic. This means that according to the standard it could unblock more than one thread. This is in contrast to std::condition_variable::notify_one(), which specifies that it will unblock (no more than) one t... | Both std::atomic::wait and std::condition_variable::wait are allowed to unblock spuriously at any time, including at the specific time that notify_one is called.
So in terms of the specification, although it does indeed seem that the standard uses different wording for the two ("at least one" in [atomics.types.operatio... |
72,566,613 | 72,566,731 | Call non-member function from inside class, but the nonmember function takes class as input (C++) | As the title suggests, I am wondering if I can call a non-member function (which is contained in the class header file) from inside the class, with the caveat that the nonmember function is using the class itself ? Normally I could just put the nonmember function above the class declaration, but that means I cannot pas... | You need to do two forward declarations. One for the Matrix class and one for the LUDecomposition function.
class Matrix; // This lets LUDecomposition know a Matrix type exists
std::tuple<Matrix, Matrix> LUDecomposition(Matrix& matrix); // this lets the Matrix class knows that a LUDecomposition function exists.
Put th... |
72,567,212 | 72,572,929 | How to refer to a class object by combining text and a number - C++ | is there a way to directly use the menuItem variable (which is an integer obviously) to put in the tft.print functions, so I don't have to use "if - else statements" like in the code below?
My idea is that it works kind of like this (I know that this code doesnt work - just the idea):
tft.print(dmx(menuItem).channelNam... | Thank you for all the answers. I managed to bring it to work!
we can initialize an object array with parameterized constructors (This is done outside main loop, but can also be done inside):
Dmx dmx[] = {Dmx("1","DMX CHANNEL 1"), Dmx("2","DMX CHANNEL 2"),Dmx("3","DMX CHANNEL 3"), Dmx("4","DMX CHANNEL 4"), Dmx("5","DMX ... |
72,567,286 | 72,568,260 | Write a macro to check function return code | Quite common that we have to call set of functions that have similar behavior - for example return negative value and set errno variable in case of failure. Instead of repeatedly write check code, sometimes it is useful to wrap it into macro:
#define CHECKED_CALL( func, ... ) \
do {\
auto ret = func( __VA_A... | Almost everything in your CHECKED_CALL macro can be turned into a function template, which has the advantage of passing through the C++ compiler's type system instead of the preprocessor's brute textual substitution.
So, for instance, we can write
template<class Callable, class... Args>
void checked_call(Callable t_cal... |
72,567,337 | 72,568,890 | How to remove `fromStdVector` method from Qt 6.3.0 c++ code | With Qt 6.3.0 QVector no longer has fromStdVector method. I didn't fully understand the answers in copying a std::vector to a qvector and would like to know how to modify the TreeWidgetController::getReponses method below.
In particular these templates were suggested:
std::vector<T> stdVec;
QVector<T> qVec = QVector<T... | There's no need to re-invent the wheel here, just have a look at the fromStdVector() method that is in qcorelib/tools/qvector.h in earlier versions of Qt:
static inline QVector<T> fromStdVector(const std::vector<T> &vector)
{
return QVector<T>(vector.begin(), vector.end());
}
You can either include that function ve... |
72,567,445 | 72,567,497 | Weird behavior dereferencing std::list iterator | I am running into strange behavior when using std::list<std::array<T>>::iterator.
I'm trying to run the following code:
#include <iostream>
#include <list>
#include <array>
#include <algorithm>
using namespace std;
struct S {
uint64_t x;
};
#define N 10000
typedef array<S, N> block;
typedef list<block>::ite... | The variable b is declared as a reference
block& b = l.front();
So in this statement
b = *(++i);
the second element of the list is assigned to the first element of the list.
So in this statement
std::cout << i->data() << " " << b.data() << "\n";
there are outputted values of returned by the member function data for ... |
72,567,976 | 72,592,097 | Output whole sentence when reversing words in string c++ | Have to create our own function that receives a sentence/sentences from an input file. It then should reverse the letters of each word individually and leaves all other (non-alphabetic) characters in the plaintext unchanged i.e "The cat sat on the mat!" will become
"ehT tac tas no eht tam!".
So I think I have found a w... | So here is code that can output the sentence from the input file, with each word being reversed and all these words then being outputted in one sentence in the order they were in the sentence. There is still some problems to it, like if there is a non-alphabetic character in the word, at the front or somewhere before t... |
72,568,387 | 72,568,959 | Why is an object's constructor being called in every exported WASM function? | I'm compiling some c++ for a WASM module
struct Test{
Test(){
printf("Constructed");
}
};
Test t;
EXPORT void init(){...}
EXPORT void update(){...}
EXPORT void uninit(){...}
I would expect the constructor to only be called once for t, but looking at chrome's debugger shows that the constructor for t ... | See https://github.com/WebAssembly/WASI/blob/main/legacy/application-abi.md
I think what is happening is that the linker in this case deciding that you using the command abi, and each entry point to your application is a standalone command.
What you are actually trying to build is that is referred to in that document a... |
72,568,460 | 72,570,562 | How to draw an arc between two known points in Qt? |
I want to draw an arc between point B to point D and it should touch to point E. ( I want to draw AND gate symbol )
I tried this way
QPainterPath path;
path.arcTo(60,30,46,100,30*16,120*16); // ( x,y,width,height, startAngle,spanAngle)
But it is drawing full circle and not in proper place.
Currently it is ... | I think you misunderstood the parameters for arcTo, especially the bounding rectangle.
Given your image, you should move path to (106, 80) (center of the bounding rectangle)
path.moveTo(106, 80);
The bounding rectangle of the arc should look like this:
x: 76
y: 30
width: 60
height: 100
The arc itsel should have a sta... |
72,568,783 | 72,575,748 | How to iterate through specific elements in a vector C++? | I'm making a game with C++ and SFML and was wondering if there's a way to iterate through specific elements in a vector. I have a vector of tiles which makes up the game world, but depending on the game map's size, (1000 x 1000 tiles) iterating through all of them seems very inefficient. I was wondering if there was a ... | Given the following assumptions:
Your tiles are likely arranged on a regular grid with a (column, row) index.
Your tiles are likely inserted into your vector in row-major order, and is also likely fully-populated. So the index of a tile in your vector is likely (row * numColumns + column).
Your view is likely axis-al... |
72,568,945 | 72,569,796 | Convert c++ std::string to c# byte array | I have a .NET program that uses a DLL export to get a name of a user.
public static extern string Name(byte[] buf);
This is the export, and I would really like to not change it, as a lot of code relies on it. So, I would like to know, in C++, how would I convert a char* array to the byte buffer?
I have tried this:
void... | Your C++ function implementation does not match the expectations of the C# function declaration.
The C# byte array is marshalled into the function as a pinned pointer to the array's raw memory. The syntax you are using in the C++ code for the parameter (std::byte buf[256]) is just syntax sugar, the compiler actually tr... |
72,568,992 | 72,569,123 | How to read total file line by line and set value to string | I would like to read and display the content of a file entered by user at run-time
My code :
#include<iostream>
#include<fstream>
#include<stdio.h>
using namespace std;
int main()
{
char fileName[30], ch;
fstream fp;
cout<<"Enter the Name of File: ";
gets(fileName);
fp.open(fileName, fstream::in);
... | If you need to read the whole content of a text file into a std::string, you can use the code below.
The function ReadTextFile uses std::ifstream ::rdbuf to extract the content of the file into a std::stringstream. Then it uses std::stringstream::str to convert into a std::string.
#include <iostream>
#include <fstream>... |
72,569,161 | 72,569,194 | xtensor: assigning view to double | I'm trying to implement a rolling mean ala pandas via the xtensor library. However I'm unable to assign the expression xt::mean(x_window) to the double result[i].
#include <iostream>
#include <xtensor/xarray.hpp>
#include <xtensor/xio.hpp>
#include <xtensor/xview.hpp>
#include <xtensor/xadapt.hpp>
#include <vector>
//... | The problem is that you're not actually calling the callable resulting from xt::mean but instead trying to assign the result of xt::mean to a double.
To solve this just call it by adding the parenthesis () and then assign that to the double as shown below:
//----------------------------vv---->added this parenthesis
res... |
72,569,547 | 72,569,621 | How can I call a method of a variable, which contains in a namespace? | I've this C++ code in interface.h:
#include <iostream>
class A{
public:
void foo();
};
namespace interface{
...
namespace Sounds{
A val;
};
}
I need to call .foo method.
I want to do it in interface.cpp:
#include "interface.h"
void A::foo(){
std:... | There are 2 ways to solve this both of which are shown below.
Method 1: Prior C++17
First method is using the extern kewyord in the header file for the declaration of val and then define val in the source file before using it as shown below:
interface.h
#pragma once
#include <iostream>
class A{
public: //public ad... |
72,569,781 | 72,569,840 | Every few attempts to run my build, I get a segmentation fault. I dont understand why | So i'm getting a Segmentation fault: 11 error and I know which block is causing it, but i'm trying to understand why.
std::vector<Entity> grassEntities;
for (int i = 0; i < 40; i++) {
grassEntities.push_back(Entity(i * 32, 592, grassTexture));
}
std::vector<Entity> dirtEntities;
for (int i = 0; i < 4; i++)... | Inside the game loop, in the first iteration of both for loops, it is equal to dirtEntities.end() and it2 is equal to grassEntities.end(). Dereferencing end iterators is undefined behaviour. The fact that the code doesn't crash is just "lucky".
If you want to iterate in reverse, use reverse iterators instead:
for (auto... |
72,569,974 | 72,570,173 | Question about the usage of shared_from_this() in practice | The below code snippet is seen at cppreference.
I am curious about what the intention of Best::getptr() is? When should I use this method in practice? Maybe a simple demo code helps a lot.
struct Best : std::enable_shared_from_this<Best> // note: public inheritance
{
std::shared_ptr<Best> getptr() {
return ... | shared_from_this() is intended to be used from within the shared class itself (hence its name), not so much by an external entity, which can always have access to a shared_ptr to that class.
For example, you can have a class Database that hands out Views, which have to keep a back-pointer to the Database:
struct View;
... |
72,570,092 | 72,591,890 | VS code doesn't recognize arduino specific syntax | I've installed C++ and Arduino extensions for my VS code, and most of it seem to work (it tries to connect to a board, for example), but the language recognition and IntelliSense keep marking Arduino keywords as errors and doesn't complete anything that isn't pure C++. what am I doing wrong?
Edit: I've figured out whe... | The solution that finally worked for me was to open an example (the arduino package comes with examples). then i chose a board and verified the code, the json file called c_cpp_properties, that up until now only had the configuration for Win32, was modified to contain the configs needed for arduino. its been e journey.... |
72,570,545 | 72,570,634 | free data asynchronously in c++ | I get a data structure like this:
struct My_data
{
MyArray<float> points;
MyArray<float> normals;
MyArray<float> uvCoords;
};
This function can be used to free them:
void ClearAlembicData(My_data* myData)
{
myData->points.clear();
myData->normals.clear();
myData->uvCoords.clear();
}
I want to asynchronous... | One of the solutions, implement MyArray::swap(MyArray&). Then
void ClearAlembicData(My_data* myData)
{
MyArray<float> old_points;
MyArray<float> old_normal;
MyArray<float> old_coords;
// Fast swap, myData arrays become empty
myData->points.swap(old_points);
myData->normals.clear(old_normals);
myData->uvC... |
72,570,659 | 72,570,817 | Is not catching an exception undefined behavior? | Consider the following code:
#include <iostream>
class Widget {
public:
~Widget() {
std::cout << "Destructor Called!";
}
};
void doStuff() {
Widget w;
throw 1;
}
int main() {
doStuff();
}
Because the exception is not caught in main, the compiler can arrange for the program to call termin... |
Is not catching an exception undefined behavior?
No, it is well-defined that this will result in a call to std::terminate (with no UB), albeit whether the stack is unwound before the call is implementation-defined, as per [except.terminate]:
/1 In some situations exception handling is abandoned for less subtle
error... |
72,570,811 | 72,570,900 | Why is std::vector::insert a no-operation with an empty initializer-list? | In the follwoing code:
#include <iostream>
#include <vector>
int main()
{
std::cout<<"Hello World";
std::vector<std::vector<int>> v;
while(v.size() <= 2){
v.insert(v.begin(),{}); //1
std::cout << "!";
}
return 0;
}
The output is getting increasingly aggressive with every iteration,... | Your code is asking to inert as many items as there are in the initialiser list into the vector. Since there are no items in the initialiser list nothing gets inserted.
I'm not sure what you were expecting instead, perhaps you were expecting a vector to be created from the initialiser list and that vector inserted, i.e... |
72,570,840 | 72,570,873 | error: pasting "->" and "object" does not give a valid preprocessing | I have the following macro:
#define FIELD_ACCESSOR_FUNCTIONS(typeName, fieldAccessorNamePrefix) \
JNIEXPORT jobject JNICALL my_pckg_NativeExecutor_get ## typeName ## FieldValue(JNIEnv* jNIEnv, jobject nativeExecutorInstance, jobject target, jobject field) { \
return environment-> ## fieldAccessorNamePrefix ## Field... | Drop the first ##. The name you are trying to generate is fieldAccessorNamePrefix ## FieldAccessor. The -> must not be part of the token.
|
72,571,227 | 72,571,495 | How to remove this kind of duplication (for cycle over types)? | I have code like this:
template<class Command>
void registerCmd() {
Command x{};
// do something with x...
}
namespace Cmd
{
struct GET { /* some methods */ };
struct GETSET { /* some methods */ };
struct DEL { /* some methods */ };
void registerCommands() {
registerCmd<GET>();
... | You can not have a collection of different types in a range based for loop, unless you have them in an array of std::variant, std::anyor such types.
If you're willing to make the registerCommands template function which has variadic template arguments as template parameter, with the help of fold expression (since c++1... |
72,572,158 | 72,572,246 | warning: top-level comma expression in array subscript changed meaning in C++23 [-Wcomma-subscript] | I have overloaded the 2D subscript operator in one of my classes. And for that I use the -std=c++23 option to compile the program.
Now when calling this operator, GCC complains:
warning: top-level comma expression in array subscript changed meaning in C++23 [-Wcomma-subscript]
331 | m_characterMatrix[... | The warning is there because the compiler's assumption is that you might have been expecting the pre-C++23 behaviour - that is, the "traditional" comma operator evaluation.
(While common sense would clearly indicate that you meant to use your overload and there is no problem, computer programs don't possess common sens... |
72,572,707 | 72,572,993 | If std::vector reallocates objects to new memory by using move constructor then why does it have to call the destructor on the original objects? | If the move constructor of your class is noexcept then std::vector will allocate new memory and then move construct your objects in the new memory. If it's not "noexcept" it will copy construct them. If it copy constructs them, then those objects still need to be destroyed before deallocating the old buffer. However wh... | To end an object's lifetime, its destructor must be called.
Also, what happens when an object it moved is up to the implementation of the class. You have two objects and the move constructor is allowed to move resources around how it sees fit.
An example of a simple string class which, when moving, leaves the moved-fro... |
72,572,740 | 72,856,917 | Visual Studio 2019 Linker tab not showing Unreal Engine | In a normal C++ project you can specify a library in Linker/Input/Additional Dependencies (image 1), but while working with Unreal Engine, in project property the tab for Linker isn't there (image 2). I was able to add the options from C/C++/General/Additional Include Directories (image 3) to VC++ Directories/Include D... | For my case i wanted to use jvm.lib that is located in the folder C:\\Program Files\\Java\\jdk1.8.0_333\\lib, and to do that the solution was this:
Go to this location: ProjectFolder\Source\ProjectName
There open the file: ProjectName.Build.cs
Then inside it in public ProjectName(ReadOnlyTargetRules Target) : base(T... |
72,572,822 | 72,627,406 | Qt: How to draw (and use) lineEdit inside delegate? | I have a custom list, and on the view (with the QStyledItemDelegate) I want display many things, including a text edit
(think about an online shopping cart where you have the items (photos and infos of them) and next to them you can change the quantity, but within a text edit, and not a spinbox).
This text edit should ... | I forgot several things in my implementation:
To "interact" with the lineEdit the Qt::ItemIsEditable flag must be set in the QAbstractListModel::flags(), otherwise the Editor functions in the Delegate won't get called.
To reimplement updateEditorGeometry() where you specify the lineEdit's position.
To reimplement se... |
72,573,458 | 72,573,543 | Checking if array isSorted using Recursion in c++ | In the below code i am trying to check if the array is sorted in ascending order using recursion;But have a few doubts:
I dont understand why we use arr[0] and arr[1] in place of using arr[i] and arr[i+1].
I understand why we would pass arr+1, but why are we reducing the size of array using size-1 ? shouldnt this resu... | In this case int *arr is not an array, it's pointer to the some element of the array. And arr[0] means this element, arr[1] means next element after *arr. arr[i] <=> *(arr + i). U can easily do something like that:
int *p = arr[5]; and now p[0] and arr[5] are the same things.
So in the first step arr looks at the first... |
72,573,489 | 72,573,845 | How to properly store asio connections and reuse them? (non-boost) | I am trying to understand basic ASIO (non-boost) but I am having issues understanding how you can store sockets to reuse them later. I was looking at this post: Storing boost sockets in vectors and tried to reimplement it in my code:
#include <iostream>
#include <string>
#include <vector>
#include <asio.hpp>
#include <... | It's strange that this line works: asio::write(socket, asio::buffer(message), ignored_error); because you moved a socket before std::shared_ptr<asio::ip::tcp::socket> newconn = std::make_shared<asio::ip::tcp::socket>(std::move(socket)); and later tried to use it. In a range based for you get x which is reference to a s... |
72,573,567 | 72,573,925 | How to make the player move towards the mouse in c++ SFML | What I want to do here: I want to make a top down game where you move your player by right clicking somewhere and making the player move towards that point with a constant speed like in league of legends.
Here's my code so far that almost works.
Player.cpp:
void player::initVarribles()
{
// player
movement... | For starters, you would do well to adopt sf::Vector2f to represent positions and speeds. Let us replace mX, mY and allowMove by a std::optional<sf::Vector2f> target.
We then have three situations:
target is empty: we do not need to move
target is not empty, and distance(player, target) < moveSpeed: we have arrived. Te... |
72,573,672 | 72,573,737 | Is it safe to compare const char* with == in C/C++? | Let's say I have a struct that keeps track of a type using a const char*:
struct Foo {
const char* type;
}
Suppose I only ever assign this value using a string literal throughout my program:
Foo bar;
bar.type = "TypeA";
Foo baz;
baz.type = "TypeB";
Is it safe to compare this value using a regular == as opposed to ... |
Is it safe to compare this value using a regular == as opposed to a strcmp?
No. It isn't safe in the sense that two string literals - even with same content - are not guaranteed to have the same storage address, and thus may compare different.
You can compare the address initially and only compare content if the addr... |
72,574,305 | 72,577,083 | C++/WinRT - process exited with code -1073741819 | I am using C++/WinRT to access the HumanInterfaceDevices API from Microsoft. I get
process exited with code -1073741819
when trying to call the GetDeviceSelector API. The program terminates for some reason, but I'm unable to understand why.
What's the issue with the following code and how do I fix it?
#include "pch.h... | When you execute the code under a debugger you'll get an exception message in the debug output window along the lines of:
Exception thrown at <some address> in <program>.exe: 0xC0000005: Access violation reading location 0x0000000000000000.
when evaluating the following expression:
hello.GetDeviceSelector(usagePage, ... |
72,574,412 | 72,575,526 | How to distinguish if console program is opened in Powershell or in Windows Terminal? | I'm programming a library which will make setting colors, modes, etc. easier in console program. But I've encountered a problem with Windows Terminal. For example I have a function:
void WindowsCLI::setUnderlinedFont()
{
auto consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
config.underlined = true;
SetCons... | Simple, but not foolproof solution:
Windows Terminal defines two application-specific environment variables, WT_SESSION and WT_PROFILE_ID, so you can test whether one of these variables is defined (with a non-empty value).
According to this answer, getenv("WT_SESSION") should work in C++ for retrieving the value of tha... |
72,574,708 | 72,575,103 | Moving first element to the back in the queue | I implemented the queue on my own. Also did rotate method which has to move n elements from the beginning to the end of the queue. But I missed some points and can not figure out what should I do exactly. Do you have any suggestions?
I really appreciate any help you can provide.
My output is:
3, 4, 5, 6, 7,
4, 5, 6, 0,... | Your code has issue with recurring memory allocation when push_back function is called. Condition check if(aftr == capacity) is always false.
It is better to allocated predefined memory during class constructor.
Here is the altered snippet. DEMO
struct Queue
{
private:
constexpr static int initialCapacity = 100;
... |
72,574,777 | 74,224,413 | Access current task PID in IBM Rhapsody 9.0.1 | I am using IBM Rhapsody 9.0.1
Following this link I am trying to obtain the current task's handle, or even the OS Pid, of the current process/thread. (we are migrating from an SDL tool called TAU to Rhapsody)
Unfortunately am not able to call/reference the function [getOsHandle()]2 of the OXF. My class is active hence,... | (int)(reinterpret_cast<intptr_t>(this->getOsHandle())))
|
72,575,443 | 72,575,515 | Can I safely move assign to `this`? | I was wondering if it's safe to write a reset method of some class A by using the move assignment operator on this.
So instead of
A a{};
... // Do something with a
a = A();
if I could write
A a{};
... // Do something with a
a.reset();
where
void A::reset()
{
*this = A();
}
I played arround a bit on godbolt (https:... | In general, assigning to *this is not wrong. Neither copy nor move.
Whether it's correct depends on what your move assignment operator does, and what you need the reset function to do. If the assignment does the right thing, then it's correct.
|
72,575,514 | 72,575,650 | Correct way to printf() a std::string_view? | I am new to C++17 and to std::string_view.
I learned that they are not null terminated and must be handled with care.
Is this the right way to printf() one?
#include<string_view>
#include<cstdio>
int main()
{
std::string_view sv{"Hallo!"};
printf("=%*s=\n", static_cast<int>(sv.length()), sv.data());
return... | This is strange requirement, but it is possible:
std::string_view s{"Hallo this is longer then needed!"};
auto sub = s.substr(0, 5);
printf("=%.*s=\n", static_cast<int>(sub.length()), sub.data());
https://godbolt.org/z/nbeMWo1G1
As you can see you were close to solution.
|
72,575,545 | 72,599,620 | How to reuse a clang AST matcher? | I'm using AST matchers from lib clang to ensures that some code is present in the body of a foo function.
So all my matchers starts like this:
auto matcher1 = functiondecl(hasname("foo"),
hasdescendant(...))));
auto matcher2 = functiondecl(hasname("foo"),
hasdescendant(...))));
I wo... | You can simply use
template <class T>
auto inFoo(T && f)
{
return functiondecl(hasname("foo"), hasdescendant(std::forward<T>(f)));
}
|
72,575,607 | 72,575,735 | QSlider reporting incorrect value for valueChanged() | I'm trying to connect a QSlider object to a QLineEdit such to enable a user to either specify a value using the slider or direct input into a form. The goal here is when the slider position changes, we update the text in the QLineEdit box and vice versa. However, when I try to report out the value of QSlider->valueChan... | Your call to setMapping hard-codes the value of sliderPosition to the initial version.
Good thing we have lambdas now, so you can replace the entire second paragraph with:
QObject::connect(decay_slider, &QSlider::valueChanged, le_decay_time,
[=](int value) { le_decay_time->setText(QString::number(value)); });
|
72,576,093 | 72,576,395 | Bubble sort not giving correct output c++ | I made this bubble sort code, but it doesn't seem to work can someone explain why?
#include <iostream>
using namespace std;
int main(){
int numbers[5]={2,7,9,3,4};
for(int i=0;i<5;i++){
for(int j=0;j<i;j++){
if(numbers[j]>numbers[j+1]){
int temp=numbers[j];
... | Your code will work when you change the condition of the inner loop to j < 4 - i: https://godbolt.org/z/TP9vWzbaP
But that's not bubble sort, Wikipedia has a page about bubble sort: https://en.wikipedia.org/wiki/Bubble_sort
The outer loop must run till it does not swap anymore.
#include <iostream>
using namespace std;
... |
72,576,177 | 72,576,267 | Initializing another class inside class c++ | I am trying to make a new Node class and set its coordinates in my class called Colony (my run function is inside of the Colony class). It is segfaulting though. I have tried using new but it isn't working. What should be the fix here? Heres a snippet of the code:
class Node {
public:
std::vector<double> coords;
ve... | In your run() method, you are trying to assign the 0th, 1st and 2nd elements of the start.coords vector, but these have not yet been assigned. Instead you should .push_back these values, like so:
void run() {
// Initializes a colony with starting point
Node start;
start.coords.push_back(100.0);
start.coor... |
72,576,275 | 72,576,338 | Why does C++ posix_memalign give the wrong array size? | I have the following C++ code, which tries to read a binary file, and print out the resulting 32 bit values as hex:
// hello.cpp file
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
int main()
{
int file_size; // font file size in bytes
int i;
std::cout ... | You allocated 211200 bytes, but you're trying to access 148481 * sizeof(int) bytes, which is far past the end of the buffer (and past the end of the file content).
|
72,576,822 | 72,577,698 | Specializing types from namespace std based on user-defined concepts | It is written in many places (for example here), that specialisations of types from namespace std are only allowed if the specialisation "depends on user-defined types". Does this definition in the standard explicitly exclude to specialise std types based on user-defined concepts?
For example, is this allowed?
namespac... | The general rule we have, in [namespace.std]/2 is:
Unless explicitly prohibited, a program may add a template specialization for any standard library class template to namespace std provided that (a) the added declaration depends on at least one program-defined type and (b) the specialization meets the standard librar... |
72,577,158 | 72,579,613 | how to get the data from a json from the web using wininet in C++? | I'm new to C++, I am trying to consume the ip-api.com API to fetch a geolocation based on an IP number. But I can't make a request correctly. What can I change in this code to get the JSON response correctly?
string GetLocation() {
DWORD size = 0;
DWORD wrt;
LPCWSTR down = L"Downloader";
string msg = ""... | Aside from your complete lack of any error handling, the main issue with your code is that you can't pass a URL to InternetConnect() and HttpOpenRequest(), as you are doing.
You need to break up the URL into its constituent pieces (see InternetCrackUrl()) - namely: scheme, hostname, port, and path - and then pass the a... |
72,577,406 | 72,578,697 | <function-style-cast>': cannot convert from 'char [256]' to 'std::wstring' and no instance for no instance of constructor matches the argument list | Looks like I am getting the same 2 errors on one line of code. Can you help me? What am I doing wrong?
auto get_proc_base = [&](std::wstring moduleName) {
MODULEENTRY32 entry = { };
entry.dwSize = sizeof(MODULEENTRY32);
std::uintptr_t result = 0;
const auto snapShot = CreateToolhelp32Snapshot(TH32CS_SN... | You can't construct a std::wstring from a char[] array, as you are trying to do. std::wstring does not have a constructor for that purpose. You would have to convert the char data to a wchar_t[] array using MultiByteToWideChar() or equivalent, or to a std::wstring using std::wstring_convert::from_bytes(), or any othe... |
72,577,547 | 72,577,700 | Can't use std::for_each() and std::bind() to filter elements in a vector and put those filtered elements into a new vector | Why doesn't the below code work when I'm trying to use std::for_each() and std::bind() to filter elements in a vector and put those filtered elements into a new vector?
void mypred(int a, int b, vector<int>& c){
if(a < b){
cout <<"yes" << endl;
c.push_back(a);
}
}
int main(){
vector<int> te... | Finally, I know what's happened. Thanks for the help from @MikeVine.
std::bind() will use a copy rather than a reference of a parameter. So we need to add std::ref() to let it use a reference.
|
72,577,896 | 72,579,315 | Use Double Pointers to access values instead of doubles | My question might be a bit confusing because I really did not know how to word it. Essentially, I have three classes in total and two of them are holding double pointers of a type defined in the third class.
class Wheel
{
unsigned m_orderID{};
std::string m_name{};
};
The other two classes - Car & Truck - have... | You are on the right track. Truck can just save the Wheel* pointers it is given, while Car can make its own copy of the Wheel objects. Simply destroy those copies in Car's destructor. That seems to be the piece you are missing. Simply store the extra objects as an additional member of the Car class, instead of usin... |
72,578,406 | 72,578,458 | Deletion on a non pointer array in c++ | When I have an array like this:
int* test = new int[50];
for (int i = 0; i < 50; i++)
{
test[i] = dist4(rng);
}
(Filled with random numbers for testing)
I can free the memory like this:
delete[] test;
But when I declare the array like this:
int test[50];
for (int i = 0; i < 50; i++)
{
test[i] = dist4(rng);
}
... |
What's the proper way of freeing the memory here?
No need to free memory explicitly using delete or delete[] in the latter case.
Assuming int test[50]; is declared inside a function, it has automatic storage duration and when test goes out of scope it will be automatically destroyed.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.