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 const int* and everything works as expected.
However on MSVC I'm getting a compiler error
C2664 cannot convert argument 1 from `std::_Array_const_iterator<_Ty,5>` to `const int*`
Is there a way to coerce the type conversion that I'm somehow missing? Or will I have to do data.data()[0] or something lame like that?
Changing the function signature is not really an option
| 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 can also work:
&(*iterator)
|
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 reshape it to the shape (1, 3, 640, 640).
How do I properly and efficiently transpose the tensor?
ncnn:Mat& preprocess(const cv::Mat& rgba) {
int width = rgba.cols;
int height = rgba.rows;
// Build a tensor from the image input
ncnn::Mat in = ncnn::Mat::from_pixels(rgba.data, ncnn::Mat::PIXEL_RGBA2RGB, width, height);
// Set the current shape of the tesnor
in = in.reshape(1, 640, 640, 3);
// Normalize
const float norm_vals[3] = {1 / 255.f, 1 / 255.f, 1 / 255.f};
in.substract_mean_normalize(0, norm_vals);
// Prepare the transposed matrix
ncnn::Mat transposed = new ncnn::Mat(in.w, in.c, in.h, in.d, sizeof(float));
ncnn::Mat shape = transposed->shape();
// Transpose
for (int i = 0; i < in.w; i++) {
for (int j = 0; j < in.h; j++) {
for (int k = 0; k < in.d; k++) {
for (int l = 0; l > in.c; l++) {
int fromIndex = ???;
int toIndex = ???;
transposed[toIndex] = in[fromIndex];
}
}
}
}
return transposed;
}
| 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 matrix to a wh layout matrix (slowest changing dimension first):
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
int fromIndex = i * w + j * 1;
// ^ ^
// | |
// i<h j<w <---- hw layout
int toIndex = j * h + i * 1;
// ^ ^
// | |
// j<w i<h <---- wh layout
}
}
So when computing fromIndex, you start with the source layout (hw), you remove the first letter (h) and what remains (w) is your coefficient that goes with i, and you remove the next letter (w) and what remains (1) is your coefficient that goes with j. It is not hard to see that the same kind of pattern works in any number of dimensions. For example, if your source layout is dchw, then you have
fromIndex = i * (c*h*w) + j * (h*w) + k * (w) + l * (1);
// ^ ^ ^ ^
// | | | |
// i<d j<c k<h l<w <---- dchw
What about toIndex? Same thing but rearrange the letters from the slowest-changing to the fastest-changing in the target layout. For example, if your target layout is hwcd, then the order will be k l j i (because i is the index that ranges over [0..d), in both source and target layouts, etc). So
toIndex = k * (w*c*d) + l * (c*d) + j * (d) + i * (1);
// ^ ^ ^ ^
// | | | |
// k<h l<w j<c i<d <---- hwcd
I did not use your layouts on purpose. Do your own calculations a couple of times. You want to develop some intuition about this thing.
|
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),
freq(frequency),
left(left_Node),
right(right_Node){};
};
I'm using pointers, so I'm not sure about how to store it.
Here is the way how I'm building the tree:
void buildTree(std::priority_queue<Node *, std::vector<Node *>, comp> &pq, std::multimap<int, char> &freqsTable)
{
for (auto pair : freqsTable)
{
Node *node = new Node(pair.second, pair.first, nullptr, nullptr);
pq.push(node);
}
while (pq.size() != 1)
{
Node *left = pq.top();
pq.pop();
Node *right = pq.top();
pq.pop();
int freqsSum = left->freq + right->freq;
Node *node = new Node('\0', freqsSum, left, right);
pq.push(node);
}
}
| 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. The tree will naturally complete, so there is no need for an end marker in the description.
|
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(15, '-');
std::string space(2, ' ');
std::stringstream hdr;
hdr << comment_symbol << space << " Begin of File." << std::endl;
hdr << comment_symbol << space << div << std::endl;
return hdr.str();
}
std::string c_header() { return create_header("//"); }
std::string python_header() { return create_header("#");
|
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 (&comment_symbol)[N]) {
const char one[] = " Begin of File.\n";
const char two[] = " -\n";
std::array<char,
N + (sizeof(one) - 1) +
N + (sizeof(two) - 1) + 1
> ret{};
auto it = ret.begin();
for (const char *i = comment_symbol; *i; ++i) *it++ = *i;
for (const char *i = one; *i; ++i) *it++ = *i;
for (const char *i = comment_symbol; *i; ++i) *it++ = *i;
for (const char *i = two; *i; ++i) *it++ = *i;
return ret;
}
std::string c_header() {
constexpr auto a = create_header("//");
return std::string{a.begin(), a.end()};
}
int main() {
std::cout << c_header() << '\n';
}
|
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::cout << test << std::endl;
Running the code returns 0 \n ". Thus, I'm able to open the tiff file but using the TIFFGetField routine doesn't seem to work. Can anyone explain what I'm doing wrong? What do I have to do in order to write the width of that .tif file into my variable?
Unfortunately, I don't understand the documentation provided.
The .tif file is a regular picture that can be opened with app's. Thus, it has to have a width.
| 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 >> n;
for(int i = 0; i < n; i++){
cin >> arr[n];
}
int sum = getSum(arr, n);
cout << "Sum is " << sum << endl;
return 0;
}
OUTPUT
3
1
2
3
Sum is -1827678256
When i run the code with custom input it gives the correct output. But when i input data from the user it gives an incorrect answer. Why so?
| 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 letter?
They could not have used the normal e|E notation in hex floating point constant because letter e|E is part of hexadecimal digit. But they could have used letter g|G which is usually used in printf format specifier for floating point value, or any other letter. Is there any specific reason for using the letter p?
| 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 have been something added to C.
Is there any specific reason for using the letter p?
Not really.
|
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;
cout << "A - Add a number" << endl;
cout << "M - Display mean of the numbers" << endl;
cout << "S - Display the smallest number" << endl;
cout << "L - Display the largest number" << endl;
cout << "Q - Quit" << endl;
// Storing their choice in the selection variable:
cout << "\nEnter your choice: ";
cin >> selection;
switch (selection) {
case 'a':
case 'A':
cout << "Enter an integer to add to the list: ";
cin >> list_adder;
list_items.push_back(list_adder);
cout << list_adder << " added" << endl;
break;
default:
cout << "Unknown selection, please try again";
}
} while (selection != 'q' && selection != 'Q');
How do i add a if else or loop or something so if the user already entered for example 5 added , he cant add 5 again, it will say , 5 is already in the list. And they will get the prompt again that "Enter an integer to add to the list. Please help me cant figure this out!
| 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) == list_items.end())
list_items.push_back(list_adder);
else
std::cout << "already in the list\n";
}
Another option is to use a std::set to store the items instead. A set can only contain unique values so you don't need to check if the value is already in it before inserting:
std::set<int> list_items;
if(std::cin >> list_adder) list_items.insert(list_adder);
... but you could check if it's in it if you'd like to inform the user:
if(std::cin >> list_adder) {
if(list_items.contains(list_adder)) std::cout << "already in the list\n";
else list_items.insert(list_adder);
}
About begin() and end() that was asked in the comments:
Most standard container classes have these member functions. They return iterators. An iterator is an object (like a pointer) that points to an element inside the container. begin() returns an iterator to the first element and end() returns an iterator one step after the last element.
To get the actual value from en iterator, you need to dereference it:
auto it = list_items.begin();
std::cout << *it; // dereferencing the iterator
Note that since end() is returning an iterator one step after the last element you are not allowed to dereference it.
A loop using iterators to print all values in your vector could look like this:
for(auto it = list_items.begin(); it != list_items.end(); ++it) {
std::cout << *it << '\n';
}
but nowadays, seeing such loops is rare since you can use range based for-loops instead:
for(auto& value : list_items) {
std::cout << value << '\n';
}
|
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->value = temp->next->value;
temp->next = temp->next->next;
}
}
temp = temp->next;
}
while(head != NULL){
cout<<head->value;
head = head->next;
}
}
What I'm doing is copying the value of the next node to the current one and changing the pointer to the next next node. By doing this I cannot delete the last node if the list has 10 nodes.
Any help would be appreciated
| 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, so you aren't even attempting to do anything with that last node, you just skip past it, which is why you are not removing it.
For every 5th node, you are copying the value of the next node into the current node, and then pointing the current node to skip the next node. In other words, you are not removing the 5th, 10th, 15th, etc nodes at all. You are actually removing the 6th, 11th, 16th, etc nodes instead. You need to remove the current node instead of the next node.
Which also means, you need to keep track of the previous node in the list so that you can re-link its next pointer to point at the next node that follows the current node being removed.
Try something more like this instead:
void removeDivFive(Node* head){
int count = 0;
Node *temp = head, *prev = NULL, *next;
while (temp != NULL){
++count;
next = temp->next;
if ((count % 5) == 0){
if (prev != NULL) {
prev->next = next;
}
delete temp;
}
else {
prev = temp;
}
temp = next;
}
}
Online Demo
Alternatively (as described by @GoswinvonBrederlow in comments):
void removeDivFive(Node* head){
int count = 0;
Node *temp = head, *next;
while (temp != NULL){
++count;
if ((count %4) == 0){
if (temp->next != NULL){
next = temp->next->next;
delete temp->next;
temp->next = next;
}
}
temp = temp->next;
}
}
Online Demo
|
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 locations can change, but what is the most common location I should place them?
Can something like this work?
install(FILES include/sort/sort.hpp DESTINATION ${CMAKE_INSTALL_PREFIX}/include/${CMAKE_PROJECT_NAME}/sort)
| 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 directories are not automatically available to the compiler.
This is the reason why you should try to use find_package, if package configuration scripts or find scripts are provided by the installation which has the added benefit of also adding any dependencies with just 2 commands in your cmake project (find_package and target_link_libraries). If the package is installed in the default location, find_package should be able to locate the scripts to load without specifying the install location manually.
For packages not providing this kind of info, writing a find script of your own creating imported targets allows for easy reuse.
Can something like this work?
install(FILES include/sort/sort.hpp DESTINATION ${CMAKE_INSTALL_PREFIX}/include/${CMAKE_PROJECT_NAME}/sort)
In general you should avoid hardcoding absolute destination paths into your install paths. Instead use destination paths relative to the install prefix, since the install prefix may be overwritten, e.g. if the user runs the installation via cmake --install <build dir> --prefix <install directory> or when using cpack to generate a package.
Usually you place public headers of your library in a separate directory, even in your sources (which you seem to be doing) and install the directory with
install(DIRECTORY include/sort TYPE INCLUDE)
Resulting in cmake choosing the exact location based on its defaults for the include files for the target system.
|
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 inside another class-- i.e.
class SomethingElse
{
public:
Something<float> mSomething(100);
};
It tells me that anything I put inside the parenthesis is a syntax error.
What exactly is the necessary syntax here-- or is this some quirk of templates and thus not possible?
Fail code example here:
https://wandbox.org/permlink/anaQz9uoWwV9HCW2
| 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>
class Something
{
public:
Something(t theValue) {mValue=theValue;}
t mValue;
};
class SomethingElse
{
public:
Something<float> mSomething{ 100 };
};
int main()
{
}
According to the C++ grammar
member-declarator:
declarator virt-specifier-seqopt pure-specifieropt
declarator brace-or-equal-initializeropt
identifieropt attribute-specifier-seqopt: constant-expression
See the term brace-or-equal-initializer.
|
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 buffer persistently, so should I just always use glMapBufferRange even though I want to map the entire buffer? I haven't seen anyone point out this rather important distinction between the two functions, so I was wondering if glMapBufferRange is a total and complete replacement for glMapBuffer, or if I should be prepared to use both in certain situations?
(I guess I'm just confused because, given the naming, I would think only the sub-range would be the difference between the two calls.)
| 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 bits).
glMapBufferRange reminds me of the options that are available nowadays in Vulkan (i.e cache invalidation and explicit synchronization). For some use cases, you might get better performance using the right flags with the new function. If you don't use any of the optional flags, the behaviour should be equivalent to the old function (except for the subrange part).
I think I would always use glMapBufferRange as it can do everything that the other does. Plus you can tweak for performance later on. Just my humble opinion :)
|
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 gotten passing a 2D array to C++ but cannot figure out the 3D part. I built the 2D part using this solution.
This is my C++ code right now (this works for 2D arrays):
float** testFunction(float **a)
{
printf("Hello from JNI!\n");
printf("Point at %d,%d is: %f\n", 1, 2, a[1][2]);
return a[1][2];
}
jfloat JNICALL Java_JNIArray_integrateWithTrapezoid(JNIEnv *env, jobject thisObj, jobjectArray jarr)
{
int sizex = env->GetArrayLength(jarr);
jfloatArray dim = (jfloatArray)env->GetObjectArrayElement(jarr, 0);
int sizey = env->GetArrayLength(dim);
float **localArray;
localArray = new float *[sizex];
for (int i = 0; i < sizex; i++)
{
jfloatArray oneDim = (jfloatArray)env->GetObjectArrayElement(jarr, i);
jfloat *element = env->GetFloatArrayElements(oneDim, 0);
localArray[i] = new float[sizey];
for (int j = 0; j < sizey; j++)
{
localArray[i][j] = element[j];
}
}
return testFunction(localArray);
}
Any help would be great. I am very in the dark on this. If I forgot to provide any needed information please let me know.
Thanks.
EDIT:
Thanks to @Botje, this worked:
void trapezoidalintegral(float ***a)
{
printf("Hello from JNI!\n");
printf("Point at %d, %d, %d is: %f\n", 1, 2, 2, a[1][2][2]);
return;
}
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);
float **ret = new float *[len];
for (int i = 0; i < len; i++)
{
jobject item = env->GetObjectArrayElement(arr, i);
ret[i] = thirdLevel(env, (jfloatArray)item);
env->DeleteLocalRef(item);
}
return ret;
}
float ***firstLevel(JNIEnv *env, jobjectArray arr)
{
jsize len = env->GetArrayLength(arr);
float ***ret = new float **[len];
for (int i = 0; i < len; i++)
{
jobject item = env->GetObjectArrayElement(arr, i);
ret[i] = secondLevel(env, (jobjectArray)item);
env->DeleteLocalRef(item);
}
return ret;
}
JNIEXPORT jobjectArray JNICALL Java_JNIArray_integrateWithTrapezoid(JNIEnv *env, jobject thisObj, jobjectArray jarr)
{
float ***returningArray;
returningArray = firstLevel(env, jarr);
trapezoidalintegral(returningArray);
jclass *pClass;
jclass cls1;
jclass jcls1;
jclass jcls2;
jobject obj2;
cls1 = env->GetObjectClass(thisObj);
// jfieldID fid1 = env->GetFieldID(cls1, "ptr", "J");
// pClass = (jclass *)env->GetLongField(thisObj, fid1);
jcls1 = env->FindClass("[[F");
jcls2 = env->FindClass("[F");
jobjectArray array1 = env->NewObjectArray(3, jcls1, NULL);
for (int i = 0; i < 3; i++)
{
jobjectArray array2 = env->NewObjectArray(3, jcls2, NULL);
for (int j = 0; j < 3; j++)
{
jfloatArray array3 = env->NewFloatArray(3);
env->SetFloatArrayRegion(array3, 0, 3, returningArray[i][j]);
env->SetObjectArrayElement(array2, j, array3);
}
env->SetObjectArrayElement(array1, i, array2);
}
env->DeleteLocalRef(cls1);
env->DeleteLocalRef(jcls1);
env->DeleteLocalRef(jcls2);
return array1;
}
| 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);
float** ret = new float*[len];
for (int i = 0; i < len; i++) {
jobject item = env->GetObjectArrayElement(arr, i);
ret[i] = thirdLevel(env, (jfloatArray)item);
env->DeleteLocalRef(item);
}
return ret;
}
float*** firstLevel(JNIEnv *env, jobjectArray arr) {
jsize len = env->GetArrayLength(arr);
float*** ret = new float**[len];
for (int i = 0; i < len; i++) {
jobject item = env->GetObjectArrayElement(arr, i);
ret[i] = secondLevel(env, (jobjectArray)item);
env->DeleteLocalRef(item);
}
return ret;
}
|
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:
std::transform(std::execution::par_unseq,
source.begin(), source.end(),
dest.begin(),
[](const T& elem) { return op(elem); }
);
However, when I first compiled and run this, to my surprise, I discovered that, although the transform "loops" for source.size() times, dest's content remains unchanged.
I discovered that this is because dest must have the same size of source prior to the transform.
However, I cannot do resize dest to the size of source, because T is not default constructible as it does not have a default constructor. I also would prefer not to provide a default constructor for it (first of all, it does not make sense in T's logic, but you can think that it would be expensive to call).
Does C++ STL offer any other algorithm for achieving what I have in mind?
What would suffice is an algorithm where each thread computes its own part of the source vector, and then the results are collected and joined into the same dest vector.
| 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 <iostream>
int main() {
const std::vector<T> source = {4, 5, 6, 7, 8, 9, 10, 11};
std::vector<std::optional<T>> dest(source.size());
std::transform(
std::execution::par_unseq,
source.begin(), source.end(),
dest.begin(),
[](const T& elem) { return op(elem); }
);
for (auto i : dest) {
std::cout << *i << " ";
}
std::cout << std::endl;
}
Sample output: 8 10 12 14 16 18 20 22
Godbolt demo: https://godbolt.org/z/ecf95cneq
This is admittedly not that idiomatic, as your dest array now has every element wrapped up in an std::optional<> container, but I believe it otherwise offers the semantics you specify.
|
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(t) {}
};
eventually, what I would like to be able to do is something like:
CFA<RGGB_ch> RGGB(cfa_type::RGGB);
std::cout << static_cast<int>(RGGB.ch::R);
but right now, I get compiler errors:
error: ‘ch’ is not a class, namespace, or enumeration
52 | std::cout << static_cast<int>(RGGB.ch::R);
| ^
which makes sense, but I am wondering is there a way to do this or something like this so I don't need to write a bunch of combinations and use enum classes instead of just numbers for the channels?
| 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 SDL's include folder to MyProject/lib/SDL2_lib/include and copied the lib folder to MyProject/lib/SDL2_lib/lib. SDL2.dll lives in MyProject/lib/SDL2_lib.
The following is a visual summary as well as my code.
main.cpp
#include <iostream>
#include <SDL.h>
const int WIDTH = 800, HEIGHT = 600;
int main( int argc, char *argv[] )
{
SDL_Init( SDL_INIT_EVERYTHING );
SDL_Window *window = SDL_CreateWindow( "Hello SDL WORLD", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_ALLOW_HIGHDPI );
if ( NULL == window )
{
std::cout << "Could not create window: " << SDL_GetError( ) << std::endl;
return 1;
}
SDL_Event windowEvent;
while ( true )
{
if ( SDL_PollEvent( &windowEvent ) )
{
if ( SDL_QUIT == windowEvent.type )
{ break; }
}
}
SDL_DestroyWindow( window );
SDL_Quit( );
return EXIT_SUCCESS;
}
Makefile
all:
g++ -I lib/SDL2_lib/include -Llib/SDL2_lib/lib -o Main src/main.cpp
tasks.json
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++.exe build active file",
"command": "C:\\MinGW\\bin\\g++.exe",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-I lib/SDL2_lib/include",
"-L lib/SDL2_lib/lib",
"-lmingw32",
"-lSDL2main",
"-lSDL2",
"-o",
"${workspaceFolder}/bin\\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "Task generated by Debugger."
}
],
"version": "2.0.0"
}
c_cpp_properties.json
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/**",
"${workspaceFolder}/lib/SDL2_lib/include"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"compilerPath": "C:\\MinGW\\bin\\g++.exe",
"cStandard": "gnu11",
"cppStandard": "c++14",
"intelliSenseMode": "windows-gcc-x86",
"configurationProvider": "ms-vscode.makefile-tools",
"compilerArgs": [
"-I lib/SDL2_lib/include",
"-L lib/SDL2_lib/lib",
"-lmingw32",
"-lSDL2main",
"-lSDL2"
]
}
],
"version": 4
}
Despite all this, I am getting the error;
Any help is appreciated!
Edit: I should also add that adding a random file name instead of SDL.h underlines the entire include statement instead of just the end. So clearly, VSCode does know it exists, its just not adding it to the program which is what I'm guessing
Edit2: Running make from powershell gives the following error;
| 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 libraries to link with. Technically, you only need libSDL2.la (assuming dynamic linking) since you already wrote your own main() function (therefore you don't need SDL2main.
So, the command line in your Makefile should look like this (not how I put the project's files before the libs to guarantee symbols are loaded correctly, this becomes more important when using intermediate files):
g++ -Ilib/SDL2_lib/include -Llib/SDL2_lib/lib src/main.cpp \
-lmingw32 -lSDL2main -lSDL2 -mwindows \
-o Main
If that doesn't work, please provide the compiler output (as text, not image) but not before trying this:
Option one: Specify the whole library filenamea
g++ -Ilib/SDL2_lib/include -Llib/SDL2_lib/lib src/main.cpp \
-lmingw32 -lSDL2main.la -llibSDL2.la -mwindows \
-o Main
Option two: Link statically (you won't need the DLL)
g++ -Ilib/SDL2_lib/include -Llib/SDL2_lib/lib src/main.cpp \
-lmingw32 lib/SDL2_lib/lib/libSDL2main.a lib/SDL2_lib/lib/libSDL2.a -mwindows \
-o Main
About VSCode:
I don't think there's anything wrong with your configuration. You may want to try switching to backslashes (which should't make a difference anyway) or (yes, for real) reloading VSCode.
|
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. So aa\$p\$aa works fine, and I get the expected string ("aa$p$aa").
Changing the function to add_flag() does not work either.
Is there a way to be able to pass arbitrary strings to a parameter as with either function calls above?
| 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 arguments, as parameters. Your C++ program has no means to control what has happened before it was even executed.
|
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 time? shows. But this method is not applicable for C++, e.g., as the result of objdump -T | grep GLIBCxx is not what I expect as below:
0000000000000000 DF *UND* 0000000000000000 GLIBCXX_3.4 _Znam
0000000000000000 DF *UND* 0000000000000000 GLIBCXX_3.4.21 _ZNKSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE7compareERKS4_
0000000000000000 DF *UND* 0000000000000000 GLIBCXX_3.4.19 _ZNSt6chrono3_V212system_clock3nowEv
0000000000000000 DF *UND* 0000000000000000 GLIBCXX_3.4.15 _ZNSt8__detail15_List_node_base7_M_hookEPS0_
0000000000000000 DO *UND* 0000000000000000 GLIBCXX_3.4.22 _ZTINSt6thread6_StateE
0000000000000000 DF *UND* 0000000000000000 GLIBCXX_3.4 _ZSt29_Rb_tree_insert_and_rebalancebPSt18_Rb_tree_node_baseS0_RS_
0000000000000000 DF *UND* 0000000000000000 GLIBCXX_3.4.21 _ZNSt14overflow_errorC1EPKc
0000000000000000 DO *UND* 0000000000000000 GLIBCXX_3.4 _ZTVSt9basic_iosIcSt11char_traitsIcEE
0000000000000000 DF *UND* 0000000000000000 GLIBCXX_3.4.14 _ZSt20__throw_future_errori
0000000000000000 DF *UND* 0000000000000000 GLIBCXX_3.4.21 _ZNSt7__cxx1119basic_ostringstreamIcSt11char_traitsIcESaIcEED1Ev
0000000000000000 DO *UND* 0000000000000000 GLIBCXX_3.4 _ZSt7nothrow
0000000000000000 DF *UND* 0000000000000000 GLIBCXX_3.4 _ZSt9terminatev
0000000000000000 DF *UND* 0000000000000000 GLIBCXX_3.4.21 _ZNKSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE7compareEPKc
0000000000000000 DF *UND* 0000000000000000 GLIBCXX_3.4 _ZNSt8ios_baseC2Ev
0000000000000000 DF *UND* 0000000000000000 GLIBCXX_3.4.21 _ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE9_M_appendEPKcm
0000000000000000 DF *UND* 0000000000000000 GLIBCXX_3.4 _ZNSt8ios_baseD2Ev
0000000000000000 DO *UND* 0000000000000000 GLIBCXX_3.4.21 _ZTTNSt7__cxx1118basic_stringstreamIcSt11char_traitsIcESaIcEEE
0000000000000000 DF *UND* 0000000000000000 GLIBCXX_3.4 _ZSt17__throw_bad_allocv
0000000000000000 DF *UND* 0000000000000000 GLIBCXX_3.4.14 _ZSt25__throw_bad_function_callv
0000000000000000 DF *UND* 0000000000000000 GLIBCXX_3.4.15 _ZNSt16invalid_argumentD2Ev
0000000000000000 DF *UND* 0000000000000000 GLIBCXX_3.4.21 _ZNSt13runtime_errorC1EPKc
I think I can use libclang to static analyze the source code to get such information, but is there any other method? Thanks!
| 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 happened.
Only analysis of the literal source text can tell you what you're looking for.
|
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 first line to:
#define PACK ...
Neither compiler will accept it. The error says that template type argument detection failed. Why can an individual type be detected, but not as a (degenerate) pack?
(Some background: I'm working with an application that takes advantage of the fact that, using reinterpret cast, typical ABIs guarantee it's safe to assign a function address to a function pointer if the function's argument types are prefix of the argument types of the pointed to function type, and the return types match. I was trying to write a template that would statically check for this condition.)
| 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 (*)(Args...)
//-----------------------^^^^------------------------------>order changed here
{
return reinterpret_cast<Result (*)(Args...)>(f);
}
int func(int, float, double, char, bool);
auto ptr = g(&func);
Demo
Method 2
//---------------------------------vvvv--------------------->Last comes before Args though this is not necessary here as it is deducible as shown in method 1 above
template <typename Result,typename Last, typename... Args>
auto g(Result (*f)(Last, Args...)) -> Result (*)(Args...)
//-----------------------^^^^------------------------------>order changed here
{
return reinterpret_cast<Result (*)(Args...)>(f);
}
int func(int, float, double, char, bool);
auto ptr = g(&func);
Demo
|
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;
}
int3 update_index = position_from_index(grid_centroid_positions[global_id], SIZE) -
offset_grid;
ndrange_t ndrange = ndrange_3d(size, size, size);
enqueue_kernel(get_default_queue(), ndrange,
^{update_surrouding_cells(offsets, global_id, update_index, update_edge_size, size, cost)});
}
But i get the following compiler error:
6:158:5: error: use of undeclared identifier 'ndrange_t'
ndrange_t ndrange = ndrange_3d(size, size, size);
^
6:161:5: error: implicit declaration of function 'enqueue_kernel' is invalid in OpenCL
enqueue_kernel(get_default_queue(), ndrange,
^
6:161:20: error: implicit declaration of function 'get_default_queue' is invalid in OpenCL
enqueue_kernel(get_default_queue(), ndrange,
^
6:162:163: error: expected ';' after expression
^{update_surrouding_cells(offsets, global_id, update_index, update_edge_size, size, cost)});
^
;
6:161:41: error: use of undeclared identifier 'ndrange'
enqueue_kernel(get_default_queue(), ndrange,
Compilation options are as follows:
-I "/home/development/cl" -g
-D SIZE=256
The device supports opencl 2.1, yet when compiling it seems none of the things for enqueue_kernel exist. Do i need a special extension or something? I am reading the spec here, but it doesn't seem to say anything about actually compiling the examples with dynamic parallelism.
| 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 anybody have any tips?
| 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(buffer,sizeof(buffer)-1);//Make space for '\0'
assert(results!=-1);
buffer[sizeof(buffer)-1] = '\0'; // Force null-termination in the edge case.
size_t length = strlen(buffer);
I am not 100% sure whether the limit on n read characters includes the null byte, if it works as strncpy, it might not and in that case it's better to leave a space for it and add it explicitly.
|
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 following method:
Base* Computer::Clone() const
{
Base *clone = new Computer(*this);
return (clone);
}
Computer is a subclass of Base so it returns a pointer to a Base object, created using the constructor of the same class, Computer and is done so via dereference (I believe thats what this is called here) with *this.
Now assuming Computer has an attribute bool isModeConfigured, if that is set to false for the original object, if the clone sets its to true does that replicate through? My inclination here is to say no, given the use of new.
| 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 copy constructors of all members, same as above.
If you have
class Computer{
bool member;
}
Then the new instance has a copy of member and changing it on one object leaves the other unaffected. Hence both objects are totally independent.
AFAIK all C++ containers have the sane semantics and copies are independent of each other. The problem is with any kind of pointer, since default implementation (even for smart ones) is to make shallow copies. If you had (and you shouldn't) bool* member, both objects would share the pointed-to object.
Note: Never use new (unless you have to but those cases are rare), the modern, safe implementation is
std::unique_ptr<Base> Computer::Clone() const
{
return std::make_unique<Computer>(*this);
}
|
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+0x23f7): undefined reference to `icudt71_dat'
/usr/bin/ld: udata.cpp:(.text+0x2458): undefined reference to `icudt71_dat'
The link command is as follows.
usr/bin/cmake -E cmake_link_script CMakeFiles/now.dir/link.txt --verbose=1
/usr/bin/c++ -std=c++2a -Wall -Wextra -Wfloat-equal -Wno-long-long -Wpedantic -funsigned-char -D_GNU_SOURCE=1 -rdynamic CMakeFiles/now.dir/GetStardate.cpp.o CMakeFiles/now.dir/GetTime.cpp.o CMakeFiles/now.dir/GetTimePlatformPOSIX.cpp.o CMakeFiles/now.dir/GetTimePlatformWin32.cpp.o CMakeFiles/now.dir/ISO8601_time.cpp.o CMakeFiles/now.dir/InitLocale.cpp.o CMakeFiles/now.dir/executable_path.cpp.o CMakeFiles/now.dir/now.cpp.o CMakeFiles/now.dir/nowStrings.cpp.o -o now /home/bkey1/vcpkg/installed/x64-linux/debug/lib/libboost_chrono.a /home/bkey1/vcpkg/installed/x64-linux/debug/lib/libboost_filesystem.a /home/bkey1/vcpkg/installed/x64-linux/debug/lib/libboost_locale.a /home/bkey1/vcpkg/installed/x64-linux/debug/lib/libboost_log.a /home/bkey1/vcpkg/installed/x64-linux/debug/lib/libboost_program_options.a /home/bkey1/vcpkg/installed/x64-linux/debug/lib/libboost_regex.a /home/bkey1/vcpkg/installed/x64-linux/debug/lib/libboost_system.a /home/bkey1/vcpkg/installed/x64-linux/debug/lib/libboost_thread.a /home/bkey1/vcpkg/installed/x64-linux/debug/lib/libboost_date_time.a /home/bkey1/vcpkg/installed/x64-linux/debug/lib/libboost_log_setup.a /home/bkey1/vcpkg/installed/x64-linux/debug/lib/libboost_atomic.a /home/bkey1/vcpkg/installed/x64-linux/debug/lib/libicudata.a /home/bkey1/vcpkg/installed/x64-linux/debug/lib/libicui18n.a /home/bkey1/vcpkg/installed/x64-linux/debug/lib/libicuuc.a
| 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 to the fact, that the symbol icudt71_dat does not appear anywhere in the code directly, but is generated using a macro. (Check .../source/common/unicode/utypes.h) So if the linker complains about not having found such a symbol it most probably means you are linking against a different version of the library than you have a header for. Now I don't know how specifically this could have happened, I would have to see your system, include path, link path etc. However I strongly suggest to revisit both include and link paths. You could perhaps recompile the library, verify, there is no other version recompile and start again. If the header corresponds to the source, it should work.
|
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 correctly parallelize this function. What is the best way to do it?
I wrote it like this, but I'm not sure it's correct:
QList<MyObject*> list;
QFutureSynchronizer<MyObject*> syncronizer;
for (int i = 0; i < count; ++i)
{
auto future = QtConcurrent::run([this]() -> MyObject* {
auto *object = new MyObject(this);
ProcessFunc1(object);
ProcessFunc2(object);
ProcessFunc3(object); // a heavy function that I would like to parallelize
return object;
});
syncronizer.addFuture(future);
}
syncronizer.waitForFinished();
for (int i = 0; i < syncronizer.futures().count(); ++i)
list.push_back(syncronizer.futures().at(i).result());
return list;
| // 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") your function to all objects in parallel, wait for the result
QtConcurrent::blockingMap(list, [] {
ProcessFunc1(object);
ProcessFunc2(object);
ProcessFunc3(object);
});
// here everything is done, since blockingMap waits for everything to finish
|
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 namespace std;
const int SCT_OSC_FILLED = 11;
class OrderInfo {
private:
std::string id;
public:
OrderInfo(std::string a, int aStatusCode);
std::string key();
int statusCode;
};
OrderInfo::OrderInfo(std::string a, int aStatusCode) {
id = a;
statusCode = aStatusCode;
}
std::string OrderInfo::key() {
return id;
}
std::list <OrderInfo> MasterOrders;
void testList();
void add(OrderInfo ordInfo);
void advance(OrderInfo ordInfo, std::list <OrderInfo> ::iterator& orderIter);
void testList() {
OrderInfo o1("1", 15);
OrderInfo o2("2", 16);
OrderInfo o3("3", SCT_OSC_FILLED);
OrderInfo o4("4", 17);
OrderInfo o5("5", SCT_OSC_FILLED);
OrderInfo o6("6", 18);
add(o1);
add(o1);
add(o2);
add(o3);
add(o4);
add(o5);
add(o6);
for (auto v : MasterOrders)
std::cout << v.key() << "\n";
}
void add(OrderInfo ordInfo) {
// Add to MasterOrders (if not already in list)
bool alreadyInList = false;
std::list <OrderInfo> ::iterator orderIter = MasterOrders.begin();
while (orderIter != MasterOrders.end())
{
OrderInfo oi = *orderIter;
alreadyInList = ordInfo.key() == oi.key();
if (alreadyInList) break;
advance(ordInfo, orderIter);
}
if (!alreadyInList) MasterOrders.push_front(ordInfo);
}
void advance(OrderInfo ordInfo, std::list <OrderInfo> ::iterator& orderIter) {
bool iterate = true;
if (ordInfo.statusCode == SCT_OSC_FILLED) {
orderIter = MasterOrders.erase(orderIter++); // https://stackoverflow.com/a/5265561/270143
iterate = false;
}
if (iterate) orderIter++;
}
int main()
{
testList();
return 0;
}
update: I forgot to state the actual goal
my goal is to just delete SCT_OSC_FILLED ordInfos from within the advance() method (that part is important) and leave the rest. My actual project code does more than what is shown, these names of functions are just made up for this example.. there is more code in them not directly related to manipulating the list (but related to processing OrderInfo) in my actual project. My goal is to leave one copy of o1 in the list as well as o2, o4 and o6 - removing o3 and o5 because they have an SCT_OSC_FILLED OrderInfo.statusCode
| 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 thing.
Change this
void advance(OrderInfo ordInfo, std::list <OrderInfo> ::iterator& orderIter) {
bool iterate = true;
if (ordInfo.statusCode == SCT_OSC_FILLED) {
orderIter = MasterOrders.erase(orderIter++);
iterate = false;
}
if (iterate) orderIter++;
}
to this
void advance(OrderInfo ordInfo, std::list <OrderInfo> ::iterator& orderIter) {
bool iterate = true;
if (orderIter->statusCode == SCT_OSC_FILLED) {
orderIter = MasterOrders.erase(orderIter);
iterate = false;
}
if (iterate) orderIter++;
}
Once you make that change you can see that the ordInfo parameter is unused. Add bit more cleanup and you end up with this much simpler function
void advance(std::list <OrderInfo> ::iterator& orderIter) {
if (orderIter->statusCode == SCT_OSC_FILLED) {
orderIter = MasterOrders.erase(orderIter);
}
else {
orderIter++;
}
}
|
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 = capabilities,
cmd = {
'clangd',
'--background-index',
'--query-driver="/app/vbuild/RHEL7-x86_64/clang/latest/bin/clang, \
/app/vbuild/RHEL7-x86_64/clang/latest/bin/clang++, \
/app/vbuild/RHEL7-x86_64/gcc/latest/bin/gcc, \
/app/vbuild/RHEL7-x86_64/gcc/latest/bin/g++"',
'--clang-tidy',
'--all-scopes-completion',
'--cross-file-rename',
'--completion-style=detailed',
'--header-insertion-decorators',
'--header-insertion=iwyu',
'--pch-storage=memory',
'--enable-config',
'--log=verbose'
},
filetypes = {"c", "cpp", "objc", "objcpp"}
}
And my g++ and clangd version as follow
g++ (GCC) 10.3.0
Copyright (C) 2020 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
clangd version 14.0.0
Features: linux
Platform: x86_64-unknown-linux-gnu
At the same time, I add the following include path into my CPATH
setenv CPATH "/app/vbuild/RHEL7-x86_64/gcc/latest/include/c++/10.3.0:/app/vbuild/RHEL7-x86_64/glibc/2.33/include"
setenv CPATH "/app/vbuild/RHEL7-x86_64/clang/latest/include/clang-c:/app/vbuild/RHEL7-x86_64/clang/latest/include/llvm-c:$CPATH"
But I still found these errors in my neovim
enter image description here
enter image description here
It seems like clangd cannot find related stl headers. But I checked my include path in $CPATH. It indeed has stl headers. Does anyone know how to fix this issue?
Thanks
| 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:
F obj;
public:
virtual bool f(T t1, T t2) { return obj(t1, t2); }
};
template <typename T>
struct Derived : public Base<T, std::less<T>>
{
public:
bool f(T t1, T t2) { return this->obj(t2, t1); }
};
int main()
{
Base<int> b;
std::cout << std::boolalpha << b.f(1, 2) << '\n';
Derived<float> d;
std::cout << std::boolalpha << d.f(1, 2) << '\n';
}
Here I redefine f() in Derived and change how the class behaves. The program prints out
true
false
just like it should.
However, when I try to modify it so that Derived could take a pair but only compare the .first fields like this
#include <iostream>
template <typename T, typename F = std::less<T>>
class Base
{
protected:
F obj;
public:
virtual bool f(T t1, T t2) { return obj(t1, t2); }
};
template <typename T>
struct Derived : public Base<std::pair<T, T>, std::less<T>>
{
public:
typedef std::pair<T, T> pair;
bool f(pair t1, pair t2) { return this->obj(t1.first, t2.first); }
};
int main()
{
Base<int> b;
std::cout << std::boolalpha << b.f(1, 2) << '\n';
Derived<int> d;
std::cout << std::boolalpha << d.f(std::make_pair(1, 2), std::make_pair(2, 2)) << '\n';
}
the compiler goes all agro on me:
file.cpp:9:41: error: no match for call to ‘(std::less<int>) (std::pair<int, int>&, std::pair<int, int>&)’
9 | virtual bool f(T t1, T t2) { return obj(t1, t2); }
| ~~~^~~~~~~~
...
/usr/include/c++/10/bits/stl_function.h:385:7: note: candidate: ‘constexpr bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = int]’
385 | operator()(const _Tp& __x, const _Tp& __y) const
| ^~~~~~~~
/usr/include/c++/10/bits/stl_function.h:385:29: note: no known conversion for argument 1 from ‘std::pair<int, int>’ to ‘const int&’
385 | operator()(const _Tp& __x, const _Tp& __y) const
| ~~~~~~~~~~~^~~
So it's clear that the Base::f() is called instead of the redefinition. But why is this happening when in the first example everything was fine and the virtual functions behaved as intended?
| 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 {
virtual std::pair<int,int> foo(std::pair<int,int> x) {
return x+x;
}
};
struct derived : base {
std::pair<int,int> foo(std::pair<int,int> x) override {
return x;
}
};
int main() {
derived d;
}
Resulting in error:
<source>: In member function 'virtual std::pair<int, int> base::foo(std::pair<int, int>)':
<source>:6:17: error: no match for 'operator+' (operand types are 'std::pair<int, int>' and 'std::pair<int, int>')
6 | return x+x;
| ~^~
| | |
| | pair<[...],[...]>
| pair<[...],[...]>
Compiler returned: 1
Depending on what you are actually trying to achieve you might want to make Base::f pure virtual, or provide a specialization of Base when T is a std::pair, or inherit from Base<std::pair<T,T>,std::less<std::pair<T,T>>>.
|
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)
return func(node->next, number) + node->data;
else
return func(node->next, number + node->data) + number;
}
return 0;
}
I see that it does a recursive call to the function to use the following node in the sequence, then it subtracts the child nodes data from the parent node? Is my understanding thus far correct? What is the function trying to achieve? In my mind I was thinking the function is trying to set the data of all nodes in the linked list to 0? Would that be a correct assumption.
|
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 appears where node->data is known to be 0.
The first two conditions are the same as subtracting the absolute value of each node->data, and the last condition adds number every time there is a 0.
|
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 binary stream, it's better to choose std::vector<char> other than std::string.
|
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 comments e.g. std::vector<std::byte>.
|
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 contains NAN.
| 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++)
{
cin>>a[i];
}
for(int i = 0; i<n; i++)
{
cout<<" "<<a[i];
}
return 0;
}
But when I put the same code in any online compiler, it worked fine. How does this happen? Also how to resolve the issue in Visual Studio 2022.
What I have tried:
I think that the best way to deal with this is dynamic array allocation using vectors, but I would like to hear your views. Also, why don't we have the same error in online compilers?
| 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 this happen
This happens because some compilers extend the language and accept ill-formed programs.
how to resolve the issue in Visual Studio 2022.
Don't define array variables without compile time constant size.
I think that the best way to deal with this is dynamic array allocation using vector
You think correctly. Use a vector.
|
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_AutoDestructionData in_autoDestructionData = { false, false });
C_SharedResource(const std::shared_ptr<T>& in_resource, S_AutoDestructionData in_autoDestructionData = { false, false });
template<typename T2> C_SharedResource<T2> dynamic_cast_resource() const;
// ...
}
With the definition of dynamic_cast_resource being:
template<typename T>
template<typename T2>
C_SharedResource<T2> C_SharedResource<T>::dynamic_cast_resource() const
{
T2* tempResourcePtr = dynamic_cast<T2*>(g_resource.get());
if (tempResourcePtr == nullptr)
{
return C_SharedResource<T2>();
}
// This lines causes the compiler error.
C_SharedResource<T2> tempSharedResource(std::dynamic_pointer_cast<T2>(g_resource), g_autoDestructionData);
return tempSharedResource;
}
The idea behind the function is to down cast the stored shared pointer, and then return a newly constructed shared resource with the appropriate derived type.
An example of it being used:
// C_ITransformEntityComponent publicly inherits from C_IEntityComponent, which is also virtual.
std::shared_ptr<C_ITransformEntityComponent> transformComponent = std::make_shared<C_ITransformEntityComponent>();
C_SharedResource<C_IEntityComponent> sharedTC_1(transformComponent);
C_SharedResource<C_ITransformEntityComponent> sharedTC_2;
C_SharedResource<C_ITransformEntityComponent> sharedTC_3 = sharedTC_1.dynamic_cast_resource<C_ITransformEntityComponent>();
However the line:
C_SharedResource<T2> tempSharedResource(std::dynamic_pointer_cast<T2>(g_resource), g_autoDestructionData);
Fails to compile, with the error:
Error C2664 'C_SharedResource<C_ITransformEntityComponent>::C_SharedResource(const T &,C_SharedResource<T>::S_AutoDestructionData)': cannot convert argument 1 from 'std::shared_ptr<C_ITransformEntityComponent>' to 'const T &'
I am using Visual Studio 2022, with the C++ standard set to C++20.
Edit:
Minimal reproducible example:
#include <iostream>
#include <memory>
class C_Instance
{
public:
virtual void some_func() {}
};
template<typename T> class C_SharedResource : public C_Instance
{
public:
struct S_AutoDestructionData
{
bool m_autoDestroyAllInstances = false;
bool m_transferAutoDestructionState = false;
};
private:
std::shared_ptr<T> g_resource;
S_AutoDestructionData g_autoDestructionData{};
public:
C_SharedResource() {}
C_SharedResource(const T& in_resource, S_AutoDestructionData in_autoDestructionData = { false, false });
C_SharedResource(const std::shared_ptr<T>& in_resource, S_AutoDestructionData in_autoDestructionData = { false, false });
template<typename T2> C_SharedResource<T2> dynamic_cast_resource() const;
void some_func() override {}
};
class C_IEntityComponent
{
public:
virtual void some_other_func() {}
};
class C_ITransformEntityComponent : public C_IEntityComponent
{
public:
void some_other_func() override {}
};
template<typename T>
template<typename T2>
C_SharedResource<T2> C_SharedResource<T>::dynamic_cast_resource() const
{
T2* tempResourcePtr = dynamic_cast<T2*>(g_resource.get());
if (tempResourcePtr == nullptr)
{
return C_SharedResource<T2>();
}
C_SharedResource<T2> tempSharedResource(std::dynamic_pointer_cast<T2>(g_resource), g_autoDestructionData);
return tempSharedResource;
}
int main()
{
std::shared_ptr<C_ITransformEntityComponent> transformComponent = std::make_shared<C_ITransformEntityComponent>();
C_SharedResource<C_IEntityComponent> sharedTC_1(transformComponent);
C_SharedResource<C_ITransformEntityComponent> sharedTC_2;
C_SharedResource<C_ITransformEntityComponent> sharedTC_3 = sharedTC_1.dynamic_cast_resource<C_ITransformEntityComponent>();
return 0;
}
| 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;
};
// ...
C_SharedResource(const T& in_resource, S_AutoDestructionData in_autoDestructionData = { false, false });
// ^ C_SharedResource<T>::S_AutoDestructionData
C_SharedResource(const std::shared_ptr<T>& in_resource, S_AutoDestructionData in_autoDestructionData = { false, false });
// ^ C_SharedResource<T>::S_AutoDestructionData
// ...
};
So, in this line:
// T = C_IEntityComponent
// T2 = C_ITransformEntityComponent
C_SharedResource<T2> tempSharedResource(std::dynamic_pointer_cast<T2>(g_resource), g_autoDestructionData);
C_SharedResource<T2>'s constructor expects a C_SharedResource<T2>::S_AutoDestructionData as the second argument; while you're passing a C_SharedResource<T>::S_AutoDestructionData.
Those are not the same type.
If you pull struct S_AutoDestructionData out from class C_SharedResource:
struct S_AutoDestructionData
{
bool m_autoDestroyAllInstances = false;
bool m_transferAutoDestructionState = false;
};
template<typename T> class C_SharedResource : public C_Instance
{
public:
// ...
};
struct S_AutoDestructionData wont be nested anymore and your code will compile.
|
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 containers (the ones that modify the container) frequently need to extract the underlying pointers from the iterators, but can't the container itself be a friend to the iterator? And the internals of it [the iterator] be declared private?
Doesn't this violate encapsulation and OOP principles?
Can you explain the logic behind this decision? Why doesn't the standard require the iterators' internals to be private?
|
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 that assumes the members are publicly accessible.
If you are working with an implementation where those members are public and you do access them then you are relying on implementation details and your code is not portable.
|
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::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
}
int main() {
log(std::ostringstream oss << "Foo" << 123 << 'B');
gol(std::string str .append("Foo").append(std::to_string(123)).append("Bar"));
}
By "in the calling scope", I mean that the object "oss" is automatically destroyed after "log" returns. The same goes for "str".
I could do it like this:
int main() {
{
std::ostringstream oss;
oss << "Foo" << 123 << 'B';
log(oss);
}
{
std::string str;
str.append("Foo").append(std::to_string(123)).append("Bar"));
gol(str);
}
}
But then it's not really one-liner anymore.
| 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
}
int main() {
log(std::ostringstream{} << "Foo" << 123 << 'B');
gol(std::string{}.append("Foo").append(std::to_string(123)).append("Bar"));
}
Though, I am not aware of a way to give it a name, call methods, and pass it to another function, all in the same expression.
In general, trying to squeeze as much code into a single line is not something that is actually desirable.
|
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 operations inside just one method, you refactor part of that calculations to a new method, so code now looks like this:
void MyClass::operation()
{
// finalSum it's just a class member
finalSum = {0};
for (int i = 0; i < 100; i++)
calculateIncrement(i);
}
MyClass::calculateIncrement(int i)
{
if (i % 2 = 0)
finalSum += 2;
else
finalSum += 1;
}
So, two questions:
There's a little bit of overhead for make that method call? It's really relevant?
It's cheaper (in terms of memory and CPU usage) to call a method of an instance that
calling an external function (any non-member fn that performns the same operation than calculateIncrement(), but with a return value?
What if you pass the instance of your object by non-const reference or pointer to that
external function? It's the overhead the same?
Code it's minimal, but you can argue with more complicated values that the language primitives, and suppose larger and complicated calculations than the proposed above.
Thanks.
| 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 the bottlenecks.
Anyhow, compilers are smart enough to see the pattern of loops similar to this one:
int sum = 0;
for (int i=0; i < 100; ++i) sum += i;
Knowing this, I changed your calculations to this (without this transformation I didn't get the desired output):
int main() {
// final sum it's just a class member
int finalSum = {0};
for (int i = 0; i < 100; i+=2)
finalSum += 2;
for (int i = 1; i < 100; i+=2)
finalSum += 1;
return finalSum;
}
Turned on optimizations (-O3) to get as a result:
main:
mov eax, 150
ret
There is no need to write a loop and no need to call a function. Even though I did write two loops in the code, the compiler was smart enough to see that the final result can be determined at compile time. This is the kind of optimizations that make C++ code run fast. Human-driven optimizations must always be based on profiling and measurements, and it is really hard to beat a good compiler. Though in this case you could have noticed that the final result is just 150 and that there is no need for the loop.
Conclusion: Write code to be simple and readable. The code you posted effectively assigns 150 to finalSum and the most simple way to express this is finalSum = 150;.
You may argue that I missed the point of the question. But my point is that details matter. Different code will have different opportunities to make it simpler and more expressive. It is difficult/impossible to make a general statement about whether a function call introduces too much overhead. Anyhow the compiler is much better at making this decision. It may inline the call or not when it sees that it will be worth it.
|
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 ~generic_block() {}
};
template <class T> class block: public generic_block {
private:
T *ptr;
public:
block(std::string _name, T *_ptr, std::size_t _size)
: generic_block(_name, _size)
, ptr(_ptr)
{
}
virtual ~AWblock() {}
...
}
I have tentative issuing code:
std::map<std::string, auto> types = {
{"uint32_t", [](char *name, int count){
uint32_t *ary = (uint32_t *)calloc(count, sizeof(uint32_t));
return block<uint32_t>(name, ary, count);
}},
{"float", [](char *name, int count){
float *ary = (float *)calloc(count, sizeof(float));
return block<float>(name, ary, count);
}}
};
generic_block b = types[type](name, count);
Compilation bombs with: error: ‘auto’ not permitted in template argument, which is understandable.
Question is: what should I use instead of "auto"?
Note: in real code I plan to use a preprocessor macro to generate "types", but I'm unsure if this approach is "best practice"; comments welcome, of course.
| 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 = types[type];
generic_block b = block_generator(name, count);
Of course, the requirement is that all functions in the map have the same signature. So unless all Ts are the same, you'll have to use generic_block instead of block<T>.
|
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;
};
Obviouly, I have many more methods and nested types in that struct. And I have also other similar structs, such as i64 and so on, which I name "Rings".
Later in the code, I have a template struct,
template<typename Ring>
struct FractionField {
// many things here
};
I'd like to have a c++ concept for my Ring type, so I can check at compile type that user defined "Rings" have the appropriate nested types and operations.
My attempt look like that :
template<typename T>
concept RingConcept = requires {
typename T::val; // how to express that val must be a template on a numeric value ??
typename T::template add_t<typename T::val, typename T::val>; // same here ??
};
However, none of my attempts have been conclusive.
Basically, I always get that kind of errors, without knowing how to fix them :
error: constraints not satisfied for alias template 'FractionField' [with Ring = i32]
using Q32 = FractionField<i32>;
note: because 'typename T::template add_t<typename T::val, typename T::val>' would be invalid: typename specifier refers to class template member in 'i32'; argument deduction not allowed here
typename T::template add_t<typename T::val, typename T::val>;
I hope I don't need to write a concept for every numeric types used for the nested template val.
| 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 add_t<val, val>;
};
Or
template<typename T>
concept RingConcept = requires {
typename T::template val<0>;
typename T::template add_t<typename T::template val<0>,
typename T::template val<0>>;
};
Demo
|
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_()
{
static_assert(typet == type_t::second);
return Type2();
}
template <type_t typet>
auto Get_()
{
static_assert(typet == type_t::first);
return Type1();
}
template <type_t typet>
auto Get_()
{
static_assert(false, "no overload");
}
int main()
{
auto relatedType1 = Get_<type_t::first>();
auto relatedType2 = Get_<type_t::second>();
}
| 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 needed
Then, your Get_ function template is simply:
template <type_t typet>
auto Get_() -> typename type_selector<typet>::type {
return {};
}
|
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 modifies the same memory location.
The execution of a program contains a data race if it contains two potentially concurrent conflicting actions,
at least one of which is not atomic, and neither happens before the other, except for the special case for
signal handlers described below. Any such data race results in undefined behavior.
Is it safe from a language-lawyer perspective, because the program can never be allowed to perform the "expression evaluation" x = 2;?
From a technical standpoint, what if some weird, stupid compiler decided to perform a speculative execution of this write, rolling it back after checking the actual condition?
What inspired this question is the fact that (at least in Standard 11), the following program was allowed to have its result depend entirely on reordering/speculative execution:
// Thread 1:
r1 = y.load(std::memory_order_relaxed);
if (r1 == 42) x.store(r1, std::memory_order_relaxed);
// Thread 2:
r2 = x.load(std::memory_order_relaxed);
if (r2 == 42) y.store(42, std::memory_order_relaxed);
// This is allowed to result in r1==r2==42 in c++11
(compare https://en.cppreference.com/w/cpp/atomic/memory_order)
| 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.
So, in
int a = 0;
for (int i = 0; i != 0; ++i)
++a;
there are 0 evaluations. And by a trivial rewrite, that gets us
int a = 0;
if (false)
++a;
Now, if there are 10 evaluations of ++a, we need to worry for all 10 evaluations if they race with another thread (in more complex cases, the answer might vary - say if you start a thread when a==5). But if there are no evaluations at all of ++a, then there's clearly no racing evaluation.
|
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));
kernel<<<10,1000>>>(d_answer);
cudaMemcpy(&h_answer, d_answer, sizeof(long), cudaMemcpyDeviceToHost);
cudaFree(d_answer);
}
main.py
import ctypes
import numpy as np
add_lib = ctypes.CDLL(".\\a.dll")
resoult= add_lib.resoult
resoult.argtypes = [ctypes.POINTER(ctypes.c_long)]
x = ctypes.c_long()
print("R:",resoult(x))
print("RV: ",x.value)
print("RB: ",resoult(ctypes.byref(x)))
output in python:0
output in cuda: 2096
I implemented based on c language without any problems but in cuda mode I have a problem how can I have the correct output value
Thanks
| 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:
cudaMemcpy(&h_answer, d_answer, sizeof(long), cudaMemcpyDeviceToHost);
To:
cudaMemcpy(h_answer, d_answer, sizeof(long), cudaMemcpyDeviceToHost);
|
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::cout << "a. Run" << std::endl;
std::cin >> selection;
if (selection == 'a')
{
for (i = 1; i < 5; i++)
{
std::cout << "run" << std::endl;
std::cout << "do you want to continue running? (y/n)";
std::cin >> choice;
if (i < 5 && choice == 'y')
{
continue;
}
else if (i < 5 && choice == 'n')
{
break;
}
else if ( i > 5 && choice == 'y')
{
std::cout << "Limit Reached";
}
}
}
I want it to print "limit reached" when i > 5, but somehow the loop skips it. What am I doing wrong?
Previous StackOverflow questions did not help much. I tried their solutions, but they did not solve my issue.
Edit:
For example: Nesting if statements inside a While loop? I have looked if I have initialized any of my int which might be messing my loop.
Looks like my else if didn't work because the condition I gave it would never be true. I feel stupid. But thanks everyone for your time. I really appreciate it.
| 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 <cctype>
bool shouldContinue(const char *prompt)
{
char choice;
do
{
std::cout << prompt << " (y/n)";
if (!(std::cin >> choice)) throw ...;
if (choice == 'y' || choice == 'Y' || choice == 'n' || choice == 'N') break;
std::cout << "Invalid choice" << endl;
}
while (true);
return (choice == 'y' || choice == 'Y');
}
int main()
{
bool loop = true;
int i;
char selection;
std::cout << "Welcome" << std::endl;
while (loop)
{
std::cout << "Please a choice" << std::endl;
std::cout << "a. Run" << std::endl;
std::cin >> selection;
if (selection == 'a')
{
for (i = 1; i < 5; ++i)
{
std::cout << "run" << std::endl;
if (!shouldContinue("do you want to continue running?"))
break;
}
if (i == 5)
std::cout << "Limit Reached";
}
...
}
return 0;
}
|
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 11
13 15
10 12
12 16
2 7
Any suggestions for how to solve this problem efficiently?
What I have tried
I have tried making an array and increasing the value of it by iterating through the line's starting point to the end. This way, the maximum number can be detected. Runtime error and the code is slow.
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
using namespace std;
int N, x, y, cnt, max_cnt = 0;
vector<pair<int, int>> end_points;
int main()
{
cin >> N;
for (int i = 0; i < N; i++) {
cin >> x >> y;
end_points.push_back(make_pair(x, 1));
end_points.push_back(make_pair(y, -1));
}
sort(end_points.begin(), end_points.end());
for (const auto &e : end_points)
{
cnt += e.second;
max_cnt = max(max_cnt, cnt);
}
cout << max_cnt;
}
| 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 interval you increment the count when it is the end of an interval you decrement the count. Thats 4 iterations instead of 1000000.
The following assumes that there is no overlap between intervals that have an end point in common, eg with two intervals (0,10) and (10,20) there is no point with count 2 (ie the intervals are open, for closed intervals only a small modification is necessary).
#include <sstream>
#include <vector>
#include <iostream>
#include <algorithm>
#include <utility>
int main()
{
std::istringstream input {"6 10 \
10 14 \
1 5 \
8 11 \
13 15 \
10 12 \
12 16 \
2 7"};
std::vector<std::pair<int,int>> end_points;
int sta,sto;
while (input >> sta >> sto) {
end_points.push_back({sta,1});
end_points.push_back({sto,-1});
}
std::sort(end_points.begin(),end_points.end());
int count = 0;
int max_count = 0;
for (const auto& e : end_points) {
count += e.second;
max_count = std::max(max_count,count);
}
std::cout << max_count;
}
|
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 to its non-standard (and likely not-going-to-be-standard) status. If you must use one of MSVC's standard library modules, use import std;.
|
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){
if(arr[end] > arr[end-1])
a=1;
else if( arr[end] < arr[end-1])
a=0;
else {
// no sequence can be generated starting with start
if(end - start > ret.second - ret.first)
ret = {start,start};
break; // CHECK FOR NEXT STARTING POINT
}
}
else if(a == 0){
if(arr[end] > arr[end-1]){
a = 1;
}
else{
// return this start and end point as this sequence cannot be extended more
if(end - start > ret.second - ret.first)
ret = { start, end-1};
break;
}
}
else{
if(arr[end] < arr[end-1]){
a = 0;
}
else{
// return this start and end point as this sequence cannot be extended more
if(end - start > ret.second - ret.first)
ret = { start, end-1};
break;
}
}
}
}
return ret;
}
int main()
{
int arr[] = {1,8,5,2,6,3,9,7,4,2,3}; // provided sequence
int n = sizeof(arr)/sizeof(arr[0]);
pair<int,int> ans = findLongestTurbulence(arr,n);
for(int i=ans.first;i<ans.second;i++){
cout<<arr[i]<<", ";
}
cout<<arr[ans.second]<<endl;
}
My assumption was that it is O(n^2) as it has two nested for loops. The goal this code is trying to achieve is to find a longest turbulence in the
sequence.
‘Turbulence’ is a consecutive sub-sequence where the numbers rise and drop alternately. Every subsequence of a turbulence is also a turbulence.
For example,
• 1 and 8 and 5 are all turbulences because each of them contains only one number.
• 1,8 and 8,5 are both turbulences because 1 rises to 8 in the first sequence and 8 drops to 5 in the second.
• 1,8,5 is a turbulence because 1 rises to 8 and then drops to 5.
• 8,5,2 is not a turbulence because 8 drops twice (first to 5 and then to 2).
• The longest turbulence in the given sequence is 5,2,6,3,9,7 which is also the output.
I think the time complexity of this function is O (n^2) as there are two nested for loops. How would I return the turbulence sequence with a complexity of O(n)?
| 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+1] because when the array has subsequent elements that are equal then you can apply the algorithm on sub arrays. A turbulence never contains elements arr[i] == arr[i+1].
To invent some fance name I call it "polarity" +1 when arr[i] > arr[i+1] and -1 when arr[i] < arr[i+1] at even i. At odd indices polarity is reversed (ie -1 when arr[i] > arr[i+1]).
This is what you'll get:
#include <vector>
#include <iostream>
#include <iomanip>
int main()
{
int arr[] = {1,8,5,2,6,3,9,7,4,2,3};
std::vector<int> polarity;
int flip = 1;
for (size_t i = 0; i < std::size(arr) -1; ++i){
if (arr[i] > arr[i+1]) polarity.push_back(1*flip);
else polarity.push_back(-1*flip);
flip *= -1;
}
for (size_t i = 0; i< std::size(arr); ++i) {
std::cout << std::setw(5) << arr[i] << " ";
}
std::cout << "\n";
for (size_t i = 0; i < std::size(arr)-1; ++i) {
std::cout << std::setw(5) << polarity[i] << " ";
}
}
Output:
1 8 5 2 6 3 9 7 4 2 3
-1 -1 1 1 1 1 1 -1 1 1
I'll leave it to you to find the longest subsequence of equal elements in polarity. In this example it is polarity 1 starting at the element with value 5 till 7 (the last entry with polarity 1 corresponds to elements 9 and 7, thats why 7 is included).
|
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, class Tr, class Tuple, std::size_t... Is>
void print_tuple_impl(std::basic_ostream<Ch,Tr>& os,
const Tuple& t,
std::index_sequence<Is...>)
{
((os << (Is == 0? "" : ", ") << std::get<Is>(t)), ...);
}
| 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 << ", " << std::get<1>(t)), (os << ", " << std::get<2>(t)), (os << ", " << std::get<3>(t))
|
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:
typedef int (*tExampleFn) (int a,bool b,char* c,long long d);
tExampleFn fakePtr = (tExampleFn)0;
auto argTypes = ArgTypes(&fakePtr);
As you can see, I have to make this fake function pointer for the template to work. I would instead like it to work like this:
template <typename Ret, typename... Types> // guide Ret and Types into shape Ret(*pFn)(Types...) somehow
auto ArgTypes()
{
std::vector<std::type_index> vec;
vec.insert(vec.end(), {typeid(Types)...});
return vec;
}
typedef int (*tExampleFn) (int a,bool b,char* c,long long d);
auto argTypes = ArgTypes<tExampleFn>();
I cannot get the template to work this way. The first template arg Ret gets assinged the full type of the typedef tExampleFn. How can I guide the template to use the shape Ret(*pFn)(Types...), but without having to pass an intermediate function pointer.
| 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>
struct arg_types<R(*)(A...)> {
inline static const std::type_index value[] = {typeid(A)...};
};
template<typename T>
static constexpr std::span<const std::type_index> arg_types_v = arg_types<T>::value;
int main()
{
auto vec = arg_types_v<tExampleFn>;
for (const auto& t : vec)
{
std::cout << t.hash_code() << std::endl;
}
}
|
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 am encountering while passing forward_list also:
error: no type named ‘iterator_category’ in ‘struct std::iterator_traits<std::forward_list<int> >’
Here is my code:
#include<iostream>
#include<vector>
#include<forward_list>
#include<iterator>
#include<algorithm>
#include<typeinfo>
using namespace std;
template<typename Ran>
void sort_helper(Ran beg, Ran end, random_access_iterator_tag){
/*
Random access iterator version of sort
*/
sort(beg, end);
}
template<typename For>
void sort_helper(For beg, For end, forward_iterator_tag){
/*
The version for forward iterators is almost as simple; just copy the list into a vector, sort, and copy
back again:
*/
vector<decltype(*beg)> vec{beg, end};
sort(vec.begin(), vec.end());
copy(vec.begin(), vec.end(), beg);
}
template<class Iter>
void testSort(Iter& c){
sort_helper(c.begin(), c.end(), typename std::iterator_traits<Iter>::iterator_category{});
}
int main(int argc, char** argv){
vector<int> vec = {3, 5, 1, 2, 3, 1, 5, 88};
forward_list<int> flst = {6, 4, 6, 1, 4, 77, 1, 23, 2, 4};
testSort(vec);
testSort(flst);
for(auto& x:vec){
cout<<x<<" ";
}cout<<"\n";
for(auto& x:flst){
cout<<x<<" ";
}cout<<"\n";
}
| 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::iterator_traits<typename Container::iterator>::iterator_category{}
);
}
However, that will not work for raw C-style arrays, which don't have begin(), end(), or iterator members. But this will work for them:
template<class Container>
void testSort(Container& c){
sort_helper(std::begin(c), std::end(c),
typename std::iterator_traits<decltype(std::begin(c))>::iterator_category{}
);
}
Another problem is, this line also fails to compile:
std::vector<decltype(*beg)> vec{beg, end};
This is because dereferencing an iterator returns a reference to the element being referred to, so decltype(*beg) returns a reference type, which prevents the vector::pointer and vector::const_pointer members from being declarable:
error: forming pointer to reference type ‘int&’
This will work:
std::vector<typename std::remove_reference<decltype(*beg)>::type> vec{beg, end};
However, you can use iterator_traits here instead, which has a value_type member:
std::vector<typename std::iterator_traits<For>::value_type> vec{beg, end};
|
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)expander {
0, (void(out << std::forward<Args>(args)), 0)...
};
OutputDebugStringA(ss.str().c_str());
}
int _tmain(int argc, _TCHAR* argv[])
{
Print( 1, "abcde", 2, 3, "foo");
}
|
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 I am wondering how this could work if I want to release and distribute the application onto a different computer for someone to use. How can these scripts be deployed with the application?
I also have a .ttf font file with the same situation. How can this resource file be deployed with the application?
In other words, I want to deploy/release a C++ application with the scripts and resource files.
FYI: the C++ application is a Visual Studio project.
Thanks for the help in advance, and let me know if any more information is needed!
Update:
I just wanted to clear up the way my project is working currently:
PyObject* pArgs = PyTuple_New(5); // I setup the arguments the python function needs
PyImport_ImportModule("requests"); // imports...
// make python call
PyObject* pResult = PyObject_CallObject(pFunc, pArgs);
So this is (for the most part) how I call the scripts with the C++ source code. The scripts are located in a folder that is located in the solution directory.
I hope this explains my problem a little better.
Update:
Just another little update... Using some answers to other similar questions got me to the following point:
I need to obtain a python library, compile and link it with my C++ application, and then bundle the dependencies with the application (How to distribute C++ application which calls Python?)
So I guess my question is now shifting to how I would be able to get this done. What are the specific steps to do this? I also got a link (https://docs.python.org/3.5/using/windows.html#embedded-distribution) to an embedded distribution of a python environment (maybe this should somehow be used?). Also, I am able to statically link python into the application. I just don't know how to bundle and deploy the scripts I created and use in the application.
| 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 found to expand the parameter pack do not work with void expressions, so I had to resort to what you see below, which seems a weird trick.
template<typename F, typename ...Args>
requires requires { std::tuple{std::declval<F>(Args)...}; }
auto for_each(F f, Args ...args) {
return std::tuple{f(args)...};
}
template<typename F, typename ...Args>
auto for_each(F f, Args ...args)
[[maybe_unused]] int a[] = {(f(Members), 0)...};
}
Note that I have to declare a unused variable and mark it with the attribute.
Which is the best way to obtain the expected result here?
| 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 similarly for the first function.
I also question the value of having such a function. I'd understand doing this to a tuple, but if you already have a pack, you can do this manually at the call site.
|
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) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
int main(){
ListNode l = ListNode(2, &ListNode(4));
return 0;
}
I don't really know how to use classes in C++ but I would like to use a Class here for the LinkedList instead of a struct.
| 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 variable
ListNode m = ListNode(4);
ListNode l = ListNode(2, &m);
Now the ListNode(4) object is held by a variable, so it's safe to take the address of it.
But usually in a linked list class you solve this problem by using dynamic memory allocation with new.
|
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 Boost::boost Boost::<lib1> Boost::<lib2> ...)
so in my CMakeLists.txt I added the following lines:
find_package(Boost COMPONENTS variant2 REQUIRED)
target_link_libraries(MyTarget PRIVATE Boost::variant2)
However, when I run cmake -DCMAKE_TOOLCHAIN_FILE:STRING=/path_to_vcpkg/scripts/buildsystems/vcpkg.cmake I get the following error:
-- Configuring incomplete, errors occurred!
Could NOT find Boost (missing: variant2) (found version "1.78.0")
| 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 see list of libs required to be built for here for Windows and here for Unix-like systems
|
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 thread.
Where does this difference come from? Does this not use the same underlying mechanism? As far as implementations of the standard library go, do all of the prevalent ones have a chance of actually unblocking multiple with this call, or are there some that always unblock exactly one?
| 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.operation]/32 but just "one" in [thread.condition.condvar]/5), I don't think there is any normative difference here. The implementation is free to unblock any number of threads for both waiting operations when notify_one is called, as long as it is at least one (if any are waiting). This is true for std::atomic::notify_one as well as std::condition_variable::notify_one (i.e. "(no more than)" is wrong).
In an earlier revision of the proposal [P1135R4] for the std::atomic waiting operations it still said "one" instead of "at least one" in the proposed wording.
That was changed with revision [P1135R5], according to which wording improvements were made partly in response to feedback from LWG teleconferences. I don't think any documentation of these teleconferences is publicly available, so I can't tell whether there was a specific intent in this wording change.
Maybe it is supposed to avoid misunderstandings since the spurious unblocking is mentioned in a different paragraph or maybe it is meant to convey that there are implementations which do unblock multiple/all waiting operations that are specifically intended to be supported as such. See also comments under the question and this answer.
|
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 pass it the class as input because it is not identified by then.
For reference this is what a slimmed down version of my "Matrix" class looks like, with the nonmember function "LUDecomposition", which I am trying to call from the "Determinant" member class:
#pragma once
#include <vector>
#include <tuple>
enum MatrixType
{
Identity,
Zeros,
Ones
};
class Matrix
{
private:
int col, row;
typedef std::vector<double> Row;
std::vector<Row> data;
public:
Matrix(int columns, int rows): row(rows), col(columns), data(columns, std::vector<double>(rows))
{
}
Matrix(int columns, int rows, MatrixType matrixType) : row(rows), col(columns), data(columns, std::vector<double>(rows))
{
switch (matrixType)
{
case Identity:
this->MakeIdentity();
break;
case Zeros:
this->Fill(0);
break;
case Ones:
this->Fill(1);
break;
default:
break;
}
}
Row& operator[](int i)
{
return data[i];
}
std::tuple<int,int> Size() const
{
return std::make_tuple(col, row);
}
double Determinant() const
{
if (col != row) throw std::exception("Matrix must be square");
Matrix tempMatrix = *this;
std::tuple<Matrix, Matrix> LU = LUDecomposition(tempMatrix);
}
};
std::tuple<Matrix, Matrix> LUDecomposition(Matrix& matrix) //This function decomposes input square matrix A into lower triangular matrix L and upper triangular matrix U such that A=LU (Doolittle)
{
std::tuple<int, int> size = matrix.Size();
int col = std::get<0>(size);
int row = std::get<1>(size);
Matrix lower(col, row);
Matrix upper(col, row);
for (int i = 0; i < col; i++)
{
for (int k = i; k < col; k++)
{
int sum = 0;
for (int j = 0; j < i; j++)
{
sum += lower[j][i] * upper[k][j];
}
upper[k][i] = matrix[k][i] - sum;
}
for (int k = i; k < col; k++)
{
if (i == k) lower[i][i] = 1;
else
{
int sum = 0;
for (int j = 0; j < i; j++)
{
sum += lower[j][k] * upper[i][j];
}
lower[i][k] = (matrix[i][k] - sum) / upper[i][i];
}
}
}
return std::make_tuple(lower, upper);
}
Is there any way at all to call this function from inside the class ? I don't mind if it remains a nonmember function, or is moved somewhere, just trying to find a way to do this.
| 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 them before the definitions of the class and function (e.g. below enum MatrixType) and it compiles.
|
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).channelName);
the "dmx" and "menuitem (1, 2,3...)" need to form a new word like in the code below. as example dmx1 or dmx2, which is a class object.
its basically adding a number to a text to form the object name, that has already been initialized. (dmx1, dmx2, dmx3 and so on...)
Here Is a snippet of my code:
void print_keyboard() {
tft.fillScreen(BLACK);
tft.drawRoundRect(11, 40, 220, 35,5, WHITE);
tft.setCursor(15,50);
tft.setTextColor(WHITE);
if (menuItem == 1){
tft.print(dmx1.channelName);
}
else if (menuItem == 2){
tft.print(dmx2.channelName);
}
else if (menuItem == 3){
tft.print(dmx3.channelName);
}
else if (menuItem == 4){
tft.print(dmx4.channelName);
}
else if (menuItem == 5){
tft.print(dmx5.channelName);
}
else if (menuItem == 6){
tft.print(dmx6.channelName);
}
}
I am really a beginner in programming, and its hard to search for the right questions, as I don't know all the right expressions.
| 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 CHANNEL 5"),
Dmx("6","DMX CHANNEL 6"), Dmx("7","DMX CHANNEL 7"), Dmx("8","DMX CHANNEL 8"), Dmx("9","DMX CHANNEL 9"), Dmx("10","DMX CHANNEL 10")};
By then calling:
tft.print(dmx[menuItem-1].channelName);
the menuItem variable is assigned to the index of dmx object. This way, when at menuItem 1 page, dmx[0] is called. Its not the cleanest solution. But it works.
Here is the code example but with the new changes:
void print_keyboard() {
tft.fillScreen(BLACK);
tft.drawRoundRect(11, 40, 220, 35,5, WHITE);
tft.setCursor(15,50);
tft.setTextColor(WHITE);
tft.print(dmx[menuItem-1].channelName);
}
|
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_ARGS__ );\
if( ret < 0 ) {\
std::cerr << #func "() failed with ret " << ret << " errno " << errno << std::endl;\
throw std::runtime_error( #func "()" failed" );\
}\
while(false)
then use is simple:
CHECKED_CALL( func1, 1, 2, 3 );
CHECKED_CALL( func2, "foobar" );
etc. Now let's say I need to get result of the call in case it did not fail. Something like:
auto r = CHECKED_CALL( func3, 1.5 );
Obviously this would not work as written and of course I can write another macro, but question is, is it possible to write macro that would work in both cases? Or maybe not macro but not very complicated code, that will take me 10 times more time to implement than to write yet another macro for value return. Especially not to generate warning of unused code etc.
| 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_callable, std::string t_functionName, Args&&... t_args)
{
auto ret = t_callable(std::forward<Args>(t_args)...);
if( ret < 0 )
{
std::cerr << t_functionName << "() failed with ret " << ret << " errno " << errno << std::endl;
throw std::runtime_error( t_functionName + "() failed" );
}
}
One downside here is that checked_call requires us to explicitly pass a std::string representing the name of a function.
Example calling code:
int failingFunction()
{
return -1;
}
int main(){
checked_call(failingFunction, "failingFunction");
}
We can introduce a macro that automatically pairs a function with a string representation of its name to use with checked_call, like so:
#define NAMED_FUNCTION(func) func, #func
int main(){
checked_call(NAMED_FUNCTION(failingFunction));
}
We could also adapt the definition of checked_call to return ret if we wanted to, by changing the return type from void to auto and adding a return ret; if it doesn't throw. However, you may need to examine your functions' actual signature to figure out where the true return value is, assuming the nominal return value is actually an error code.
|
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>(stdVec.begin(), stdVec.end());
foreach is referenced Qt foreach loop ordering vs. for loop for QList and here https://doc-snapshots.qt.io/qt6-dev/foreach-keyword.html
The area I am unclear about is:
ResponsePtr could replace T but how would the new ResponseItem be handled?
// This is a sample of the code, I would like to upgrade
void TreeWidgetController::getResponses()
{
// First remove all possible previous children.
removeAllChildren(_rootResponses);
// Retrieve the list of available responses.
vector<ResponsePtr> responses = dbSubsystem().getResponses();
// Create a new ResponseItem for every response.
foreach (ResponsePtr r, QVector<ResponsePtr>::fromStdVector(responses))
new ResponseItem(_rootResponses, r);
}
| 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 verbatim in one of your own headers and leave your code unchanged, or use it as an example of how you can modify your code.
|
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>::iterator it;
int main() {
list<block> l;
l.emplace_back();
block& b = l.front();
it i = l.begin();
l.emplace_back();
std::cout << i->data() << " " << b.data() << "\n";
b = *(++i);
std::cout << i->data() << " " << b.data() << "\n";
}
It gives me the following output:
0x55c2b63cbec0 0x55c2b63cbec0
0x55c2b63df760 0x55c2b63cbec0
When accessing the .data() through the iterator, it correctly points to the next element. However, dereferencing the incremented iterator gives me a reference to the same old element. I have been scratching my head over this for some hours now. Am I doing something wrong or misunderstanding how iterators work?
When I try the same code but with just list<int>, it works as expected.
list<int> l;
l.emplace_back(0);
int& b = l.front();
list<int>::iterator i = l.begin();
l.emplace_back(1);
std::cout << *i << " " << b << "\n";
b = *(++i);
std::cout << *i << " " << b << "\n";
Produces the expected output:
0 0
1 1
| 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 the second element of the list and the first element of the list.
In the second example there is returned the same integer value that was assigned to the first element of the list.
You could get in the first program a similar result as in the second program if instead of using the member function data you would try to output values of arrays (provided that they are initialized for visibility).
|
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 way to reverse words individually but don't know how to find a way to output everything in one sentence. I feel like I would need to somehow use arrays or vectors to help store each word, and then output all the words together at the end, but I have not been successful.
I also want to find a way for it to know when to stop and to output the blank spaces between words.
Here is my code so far:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void reverse(string input);
int main(){
ifstream inData;
ofstream outData;
string input;
inData.open("input.txt");
outData.open("output.txt");
while(getline(inData, input)){
// cout << input;
outData << input;
}
reverse(input);
inData.close();
outData.close();
return 0;
}
void reverse(string input){
int counter =0;
while(counter != 14){
int idx = input.find(" ");
cout << idx << endl;
string word = input.substr(0, idx);
cout << word << endl;
string x;
for (int i = idx-1; i >= 0; i--)
{
x= word.at(i);
cout << x;
}
cout << endl;
input.erase(0,idx+1);
cout << input << endl;
cout << endl << "new" << endl;
counter++;
}
}
| 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 the end, that character will be pushed to the back of the word, so this needs to be improved on. Feel free to nicely add constructively criticism if have any. However, think this still provides for the original question. Thank you all for the help.
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
void reverse(string input);
int main(){
ifstream inData;
ofstream outData;
string input;
inData.open("input.txt");
outData.open("output.txt");
while(getline(inData, input)){ //get sentence from input line
reverse(input); //Reverse the sentence
cout << endl; //end line for next sentence
}
inData.close();
outData.close();
return 0;
}
void reverse(string input){
string nonAlpha = "";
bool end = false;
bool nonLetter = true;
while(end != true){
int idx = input.find(" "); //Finds index of blank space
int lastIdx = input.size(); //Finds the last index
if(idx <= 0){ //If it is the last index, then that becomes idx
idx = lastIdx;
end = true;
}
string word = input.substr(0, idx); //Word usually starts from index 0, until the blank space
string x;
for (int i = idx-1; i >= 0; i--){ //Then outputs each letter according to the index of the word
// but starts from last index and decrements thereby reversing the word
if((isalpha(word.at(i))==false)){ //If that index is not a letter then it is stored and will be outputted after word
nonAlpha.push_back(word[i]); //However this can be a problem for non-letter if not at end of word
nonLetter = true;
}
else{
x= word.at(i);
cout << x; //Prints the letter
}
}
if(nonLetter == true){
cout << nonAlpha; //Prints the non-letter
nonAlpha.erase(); //Erases whatever is inside for future non-letters
nonLetter = false; //Makes it false and will be used agaian when there is another non-letter
}
cout << " "; //Space between words
input.erase(0,idx+1); //Erases word when finished reversing and outputting it so can start next word
}
}
|
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 is called near the top of every exported function (func18 is the constructor):
...
(func $init (;23;) (export "init")
(local $var0 i32) (local $var1 i32) (local $var2 i32) (local $var3 i32) (local $var4 i32) (local $var5 i32)
call $func18
...
(func $update (;24;) (export "update")
(local $var1 i32)
call $func18
...
(func $uninit (;25;) (export "uninit")
(local $var0 i32) (local $var1 i32) (local $var2 i32)
call $func18
...
I know that the constructor has to be called somewhere, but how can I control where it's called and stop every function from calling it? Is it possible to control this through the command line arguments for clang++?
This is the command I've been using to compile this:
clang++
-Wall
--target=wasm32
-Ofast
-flto
--no-standard-libraries
-Wl,--export=init
-Wl,--export=update
-Wl,--export=uninit
-Wl,--no-entry
-Wl,--lto-O3
-Wl,-allow-undefined-file=wasm.syms
-Wl,--import-memory
-o ./bin/main.wasm
-I./src
./src/lib.cpp
./src/main.cpp
I should note that I'm not using Emscripten or any libraries/frameworks.
| 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 as a reactor.
The easiest way to build a reactor is to include some kind of crt1.c file such as the one that wasi-sdk uses: https://github.com/WebAssembly/wasi-libc/blob/main/libc-bottom-half/crt/crt1-reactor.c
If you export the _iniitialize function, which in turn references the __wasm_call_ctors function, that is a signal the linker that you the ctors are to be called just once and you are building a reactor.
|
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 looking like this
After getting suggestion I tried like this :
path.moveTo(106, 80);
path.arcTo(76.0, 30.0, 60.0, 100.0, 90.0, -180.0);
How to get rid of that vertical line ( inside AND gate ) ?
Why it is appearing ?
| 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 start angle at 90° and should span 180° in negative direction.
This results in:
path.arcTo(76.0, 30.0, 60.0, 100.0, 90.0, -180.0);
Update
arcTo
path.moveTo(106, 30);
path.cubicTo(QPointF(156.0, 30.0), QPointF(156.0, 130.0), QPointF(106.0, 130.0));
|
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 way to say "for each tile in vector of tiles that (fits a condition)". Right now, my code for drawing these tiles looks like this:
void Tile::draw()
{
for (const auto& TILE : tiles)
{
if (TILE.sprite.getGlobalBounds().intersects(Game::drawCuller.getGlobalBounds()))
{
Game::window.draw(TILE.sprite);
}
}
}
As you can see, I'm only drawing the tiles in the view (or drawculler). If the vector is too large, it will take a really long time to iterate through it. This greatly impacts my fps. When I have a 100 x 100 tile map, I get around 800 fps, but when I use a 1000 x 1000 tile map, I get roughly 25 fps due to the lengthy iteration. I know that I could separate my tiles into chunks and only iterate through the ones in the current chunk, but I wanted something a little easier to implement. Any help would be appreciated :)
| 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-aligned to the grid (where you can't rotate your view - as is the case with many 2d tile-based games)
If those assumptions hold true, then you can easily iterate through the appropriate range of tiles with a nested loop.
for (int row = minRow; row <= maxRow; ++row) {
for( int column = numColumn; column <= maxColumn; ++column) {
int index = row * numColumns + column;
// Here you can...
doSomethingWith(tiles[index]);
}
}
This just requires that you can compute the minRow, maxRow, minColumn, and maxColumn from your Game::drawCuller.getGlobalBounds(). You haven't disclosed the details, but it's likely something like a rectangle in world coordinates (which might be in some units like meters). It's likely either a left, top, width, height style rectangle or a min, max style bounds rectangle. Assuming the latter:
minViewColumn = floor((bounds.minInMeters.x - originOfGridInMeters.x) / gridTileSizeInMeters);
maxViewColumn = ceil((bounds.maxInMeters.x - originOfGridInMeters.x) / gridTileSizeInMeters);
// similarly for rows
minViewRow = floor((bounds.minInMeters.y - originOfGridInMeters.y) / gridTileSizeInMeters);
maxViewRow = ceil((bounds.maxInMeters.y - originOfGridInMeters.y) / gridTileSizeInMeters);
The originOfGridInMeters is the global coordinates of top-left corner of the tile at (row=0, column=0), which may very well be (0, 0), conveniently, if you set up your world like that. And gridTileSizeInMeters is, well, just that; presumably your tiles have a square aspect ratio in world space.
If the view is permitted to go outside the extents of the tile array, minViewColumn, (and the other iterator ranges) may now be less than 0 or greater than or equal to the number of columns in your tile array. So, it would then be necessary to compute minColumn from minViewColumn by clipping it to the range of tiles stored in your grid. (Same goes for the other iteration extents.)
// Clip to the range of valid rows and columns.
minColumn = min(max(minViewColumn, 0), numColumns - 1);
maxColumn = min(max(maxViewColumn, 0), numColumns - 1);
minRow = min(max(minViewRow, 0), numRows - 1);
maxRow = min(max(maxViewRow, 0), numRows - 1);
Now do that loop I showed you above, and you're good to go!
|
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 Name(std::byte buf[256])
{
std::string s{ "test" };
std::byte* ptr = reinterpret_cast<std::byte*>(s.data());
buf = ptr;
return;
}
When I print out the string that I convert, I get nothing, it is empty.
| 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 treats it as a pointer (std::byte* buf). Which is fine in this situation. However, your C++ function is not actually copying anything into the memory that the pointer is pointing at. You are simply changing the pointer itself to point at a different memory address. And the pointer itself is a local variable, so when the function exits, the pointer will no longer exist, and it won't matter what it is pointing at.
Also, the C# declaration is expecting the function to return something that can be marshalled to a .NET string, but the C++ function is not actually return'ing anything at all. The default marshalling behavior for a string return value is as UnmanagedType.LPStr, so the C++ function needs to return a pointer to a null-terminated char* string. The memory for that string must be allocated with CoTaskMemAlloc(), as the marshaller will take ownership of the memory and free it with CoTaskMemFree() after converting the char data to a string.
Also, the C++ function has no calling convention defined, so it is going to use the compiler's default (which is usually __cdecl, unless you change your compiler's settings). However, the default calling convention that .NET's DllImport expects the C++ function to use is __stdcall instead (for compatibility with Win32 APIs). This mismatch won't matter in 64bit, but it matters alot in 32bit.
Without changing your C# declaration, try this on the C++ side:
char* __stdcall Name(std::byte buf[256])
{
std::string s{ "test" };
size_t size = s.size() + 1;
memcpy(buf, s.c_str(), size);
void *ptr = CoTaskMemAlloc(size);
memcpy(ptr, s.c_str(), size);
return ptr;
}
That being said, it is weird to have a function that returns a string in both a byte array output parameter and in a return value. Are you sure the byte array is not meant to be used as an input parameter instead, where the function parses its content to extract amd a string? That would make more sense. It would really help if you would update your question to show how your .NET code is actually calling the C++ function and using the byte array.
|
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(!fp)
{
cout<<"\nError Occurred!";
return 0;
}
cout<<"\nContent of "<<fileName<<":-\n";
while(fp>>noskipws>>ch)
cout<<ch;
fp.close();
cout<<endl;
return 0;
}
output :
C:\Users\prade\Desktop>g++ -o file file.cpp&file.exe
Enter the Name of File: tt.txt
Content of tt.txt:-
Hello , I am c++.
I am from us.
I am a programmer.
C:\Users\prade\Desktop>
I want to set the content of file to value of string str. I want to print the whole file's content by using cout<<str;
How can I do that ?
| 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>
#include <sstream>
#include <string>
bool ReadTextFile(std::string const & fileName, std::string & text)
{
std::stringstream strStream;
std::ifstream fileStream(fileName);
if (!fileStream.is_open())
{
return false;
}
strStream << fileStream.rdbuf();
fileStream.close();
text = strStream.str();
return true;
}
int main()
{
std::string text;
if (!ReadTextFile("t.txt", text))
{
std::cout << "failed" << std::endl;
return 1;
}
std::cout << text << std::endl;
return 0;
}
A side note: better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.
|
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>
// implement rolling mean
template<typename T>
xt::xarray<T> rolling_mean(const xt::xarray<T> &x, const int window) {
const auto nan = std::numeric_limits<T>::quiet_NaN();
xt::xarray<T> result = xt::full_like(x, nan);
for (int i = 0; i < x.shape()[0] - window + 1; i++) {
auto x_window = xt::view(x, xt::range(i, i + window));
result[i + window - 1] = xt::mean(x_window); // <-- problematic step
}
return result;
}
int main(int argc, char *argv[]) {
using T = double;
std::vector<T> v = {1, 2, 3, 4, 5};
xt::xarray<T> a = xt::adapt(v);
std::cout << rolling_mean(a,2) << std::endl; // [nan, 1.5, 2.5, 3.5, 4.5] expected
}
How do I fix this?
The compilation fails with the error message
error: assigning to 'double' from incompatible type 'xt::xfunction<xt::detail::divides, xt::xreducer<xt::xreducer_functors<xt::detail::plus, xt::const_value<double>>, const xt::xview<xt::xarray_container<xt::uvector<double, xsimd::aligned_allocator<double, 16>>, xt::layout_type::row_major, xt::svector<unsigned long, 4, std::allocator<unsigned long>, true>> &, xt::xrange<long>> &, xt::svector<unsigned long, 4, std::allocator<unsigned long>, true>, xt::reducer_options<double, std::tuple<xt::evaluation_strategy::lazy_type>>>, xt::xscalar<double>>'
| 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
result[i] = xt::mean(x_window)();
|
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::cout<<1;
}
interface::Sounds::val.foo();
But Clion warns me:
No type named 'val' in namespace 'interface::Sounds'
What should I do?
Edit: public was added
| 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 added here
void foo();
};
namespace interface{
namespace Sounds{
//note the extern here . This is a declaration
extern A val;
};
}
interface.cpp
#include "interface.h"
void A::foo(){
std::cout<<1;
}
//definition
A interface::Sounds::val;
main.cpp
#include <iostream>
#include "interface.h"
int main()
{
//call member function foo to confirm that it works
interface::Sounds::val.foo();
return 0;
}
Working demo
The output of the above modified program is:
1
Method 2: C++17
You can use inline instead of extern with C++17 and onwards to define val in the header:
interface.h
#pragma once
#include <iostream>
class A{
public: //public added here
void foo();
};
namespace interface{
namespace Sounds{
//note the inline used here
inline A val{};
};
}
interface.cpp
#include "interface.h"
void A::foo(){
std::cout<<1;
}
//nothing needed here as we used inline in the header
main.cpp
#include <iostream>
#include "interface.h"
int main()
{
//call member function foo to confirm that it works
interface::Sounds::val.foo();
return 0;
}
Working demo
|
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++) {
for (int j = 0; j < 41; j++) {
dirtEntities.push_back(Entity(j * 32, (688 - (i * 32)), dirtTexture));
}
}
bool gameRunning = true;
SDL_Event event;
while (gameRunning) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT)
gameRunning = false;
}
window.clear();
std::vector<Entity>::iterator it;
std::vector<Entity>::iterator it2;
for (it = dirtEntities.end(); it >= dirtEntities.begin(); it--){
window.render(*it);
}
for (it2 = grassEntities.end(); it2 >= grassEntities.begin(); it2--){
window.render(*it2);
}
window.display();
}
this issue lies with this section
for (it2 = grassEntities.end(); it2 >= grassEntities.begin(); it2--){
window.render(*it2);
}
which for me is odd because this section seemed to work just fine:
for (it = dirtEntities.end(); it >= dirtEntities.begin(); it--){
window.render(*it);
}
| 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 it = dirtEntities.rbegin(); it != dirtEntities.rend(); it++){
window.render(*it);
}
for (auto it2 = grassEntities.rbegin(); it2 != grassEntities.rend(); it2++){
window.render(*it2);
}
|
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();
}
// No public constructor, only a factory function,
// so there's no way to have getptr return nullptr.
[[nodiscard]] static std::shared_ptr<Best> create() {
// Not using std::make_shared<Best> because the c'tor is private.
return std::shared_ptr<Best>(new Best());
}
private:
Best() = default;
};
I wrote a simple code snippet to use shared_from_this(), but I still can't see anything meaningful.
If I want to create a new instance, I just call Foo::Create(). If I have not called Foo::Create, Foo::getPtr() is meaningless (i.e. it could not be invoked at all) since there is no valid instance yet.
If I miss something, please let me know.
#include <iostream>
#include <memory>
class Foo : public std::enable_shared_from_this<Foo> {
private: //the user should not construct an instance through the constructor below.
Foo(int num):num_(num) { std::cout << "Foo::Foo\n"; }
public:
~Foo() { std::cout << "Foo::~Foo\n"; }
int DoSth(){std::cout << "hello world" << std::endl; return 0;}
std::shared_ptr<Foo> getPtr() { return shared_from_this();}
static std::shared_ptr<Foo> Create() {
Foo* foo = new Foo(5);
return std::shared_ptr<Foo>(foo);
}
private:
int num_;
};
int main()
{
auto sp = Foo::Create();
sp->DoSth();
Foo& foo = *sp.get();
auto sp1 = foo.getPtr();
std::cout << sp.use_count() << std::endl;
}
| 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;
struct Database : enable_shared_from_this<Database>
{
auto GetView() { return make_unique<View>(shared_from_this()); }
};
struct View
{
shared_ptr<Database> db;
View(shared_ptr<Database> db) : db(move(db)) {}
};
|
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 where things go wrong. the C++ configuration is set to Win32, but the Arduino config does not exist. it isn't in the json either. seems like the arduino extension failed to modify the c_cpp_properties.json, but still I can't fix it because i don't know what is supposed to be the content of the json.
| 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 asynchronously clean the myData so that the program will not wait util all the xxx.clear() are done. Here is my actual code:
My_data myData;
myData.point.push_back(point);
myData.nomals.push_back(nomals);
myData.uvCorrds.push_back(uvCorrds);
ClearAlembicData(&myData);
myData.point.push_back(point);
myData.nomals.push_back(nomals);
myData.uvCorrds.push_back(uvCorrds);
Could you show me how to do it in C++? thanks
| 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->uvCoords.clear(old_coords);
// Assumed to be passed to async function
old_points.clear();
old_normals.clear();
old_coords.clear();
}
There is no enough information about MyArray abilities, such as support of move semantics, a real function clear, thus this is just an idea.
|
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 terminate immediately after the throw with ~Widget not called.
Since the standard does not specify whether or not the destructors are called, is this undefined behavior?
Note: The example is from this CppCon 2015 talk by Fedor Pikus.
Edit: This question asks about the compiler's freedom for destructor elision, however it is in a special, different situation. The answer to that question does not apply to this question.
|
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 handling techniques.
[...]
when the exception handling mechanism cannot find a handler for a thrown exception ([except.handle]), or
/2 In such cases, the function std::terminate is called. In the
situation where no matching handler is found, it is
implementation-defined whether or not the stack is unwound before
std::terminate is called. [...] An implementation is not permitted to finish stack unwinding prematurely based on a determination that the unwind process will eventually cause a call to the function std::terminate
|
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, because the v.size() never increases, despite the insert operation.
However, when the initializer_list has an element in it, or replaced with a temporary, the cycle runs as many times as expected.
...
v.insert(v.begin(),{0}); //1
...
...
v.insert(v.begin(),std::vector<int>()); //1
...
Why is that? Shouldn't there be a compile error if implicit conversion fails?
| 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.
v.insert(v.begin(),std::vector<int>{})
but that doesn't happen because vector<T>::insert has an overload that takes an initializer_list<T> directly (and which behaves as I described above).
|
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 ## FieldAccessor->getValue(jNIEnv, target, field); \
}
FIELD_ACCESSOR_FUNCTIONS(Object, object)
And when I start the compilation I get the following error:
NativeExecutor.cpp:59:20: error: pasting "->" and "object" does not give a valid preprocessing token
return environment-> ## fieldAccessorNamePrefix ## FieldAccessor->getValue(jNIEnv, target, field); \
^~
How can I solve?
| 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>();
registerCmd<GETSET>();
registerCmd<DEL>();
}
}
I like how the code turns out. I was wondering if there is a way this code to be changed to something like this:
namespace Cmd
{
void register() {
// this does not compile
for (TYPE in{ GET, GETSET, DEL })
registerCmd<TYPE>();
}
}
May be with variadic templates?
| 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++17) you might do (provided that the number types are known at compile time):
template<typename... Types>
void registerCommands() {
(registerCmd<Types>(), ...);
}
and function calling
Cmd::registerCommands<Cmd::DEL, Cmd::GETSET, Cmd::GETSET>();
Live Demo
|
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[ x1, y1 ] = ch.value( );
| ~~~~~~~~~~~~~~~~~^
So what is this warning for? Should I take it seriously?
| 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 sense.)
You can disable that warning with -Wno-comma-subscript.
|
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 why is it the case that if the object is moved it still calls the destructors on all the old objects. I don't see why this is necessary. Any destructor call on a moved-from object is not going to do anything, apart from some conditional checks. You could argue that the "object is technically not destroyed", and that's true, but since that memory is being deallocated, and the next time that memory is used the only defined way to access objects there is to construct them first, I don't see why this needs to be done:
struct Foo
{
void* buffer;
Foo() : buffer(new char[16]) {}
Foo(Foo&& other) { buffer = other.buffer; if (other.buffer != nullptr) other.buffer = nullptr; }
~Foo()
{
if (buffer != nullptr) delete buffer;
}
};
int main()
{
Foo foo;
Foo foo2 = std::move(foo);
foo.~Foo(); /* NO EFFECT */
/* BUT ASSUMING WE DIDN'T CALL THE CONSTRUCTOR, WE JUST CONSTRUCT OVER IT */
new (&foo) Foo{};
/* THEN THE OLD FOO CEASES TO EXIST EVEN IF THE DESTRUCTOR IS NEVER CALLED */
}
Here is a quick program showing that std::vector calls the destructors on the old moved-from objects:
#include <iostream>
struct Foo
{
Foo() {}
Foo(uint32 id) { }
Foo(const Foo& other)
{
std::cout << "Copy constructor called\n";
}
Foo(Foo&& other) noexcept
{
std::cout << "Move constructor called\n";
};
~Foo()
{
std::cout << "Destructor called\n";
}
};
int main()
{
Foo foo;
std::vector<Foo> v;
v.push_back(std::move(foo));
v.push_back(std::move(foo));
v.push_back(std::move(foo));
v.push_back(std::move(foo));
}
| 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-from object in a valid state:
class string {
public:
string(const char* s) : m_len(std::strlen(s)), m_data(new char[m_len + 1]) {
std::copy_n(s, m_len + 1, m_data);
}
string(string&& rhs) :
m_len(std::exchange(rhs.m_len, 0)),
m_data(std::exchange(rhs.m_data, new char[1]{}))
{}
~string() {
delete[] m_data;
}
private:
size_t m_len;
char* m_data;
};
Without calling the destructor of the moved-from object, it would leak. An implementation like above is not uncommon. Just because an object has been move-from, it doesn't mean that it's void of resources to free.
|
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 Directories (image 4) but I still need to add the library as well, so can anyone explain how can I do this?
C/C++ isn't what I normally use, and so in Unreal Engine I'm using blueprints to get around this, but for some things I still need to use it and write code like in this case.
Image 1:
Image 2:
Image 3:
Image 4:
| 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(Target) { } I had to add the following lines:
PublicDefinitions.Add("WITH_MYTHIRDPARTYLIBRARY=1");
PublicIncludePaths.Add(Path.Combine(ModuleDirectory, "C:\\Program Files\\Java\\jdk1.8.0_333\\include"));
PublicIncludePaths.Add(Path.Combine(ModuleDirectory, "C:\\Program Files\\Java\\jdk1.8.0_333\\include\\win32"));
PublicAdditionalLibraries.Add(Path.Combine(ModuleDirectory, "C:\\Program Files\\Java\\jdk1.8.0_333\\lib\\jvm.lib"));
As a side note, don't forget to add double \\ in paths, I was in a rush and I only used one \ and it took me a few moments to realize what the error was about.
|
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 be able to communicate with the model. Currently I can only draw an empty textEdit, but I don't know how to connect it properly to the editorEvent ( and createEditor, setEditorData).
void CustomDelegate::paint(QPainter *painter,
const QStyleOptionViewItem &opt,
const QModelIndex &idx) const
{
// My other painting stuff (labels, shapes...)
QStyleOptionFrame panelFrame;
QLineEdit lineEdit;
panelFrame.initFrom(&lineEdit);
panelFrame.rect = rectLE;
panelFrame.state |= QStyle::State_Sunken;
QApplication::style()->drawPrimitive(QStyle::PE_PanelLineEdit, &panelFrame, painter);
}
QWidget *CustomDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
auto editor = new QLineEdit(parent);
editor->setText("test");
return editor;
}
void CustomDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
auto lineEdit = dynamic_cast<QLineEdit*>(editor);
if(lineEdit)
{
lineEdit->setText("test2");
}
}
As a the result I can only see an empty lineEdit and can't really interact with it.
If I would have multpiple lineEdits inside one modelIndex delegate, how could I differentiate them in the setEditorData and createEditor?
Thanks
| 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 setModelData() where you can communicate with the model.
To draw the text in the Delegate's paint() function after drawPrimitive (drawPrimitive just draws the frame, but you want to draw the text you wrote in lineEdit as well. You can get it from the model)
|
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 result in the nth part of the array to be reduced ?
bool isSorted(int *arr, int size){
if(size == 0 || size == 1){
return true;
}
//compare two adjacent elements and reduce the size
if(arr[0] > arr[1]){
return false;
}
bool ans = isSorted(arr+1, size-1);
return ans;
}
| 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 element and compares first and second. On next step arr looks at the second element and compares second and third etc. And u have to understand a distance between current element and end of array that's why you decrease size
|
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 <memory>
std::vector<std::shared_ptr<asio::ip::tcp::socket>> clients;
int main() {
std::cout << "Starting server..." << "\n";
try {
asio::io_context io_context;
asio::ip::tcp::acceptor acceptor(io_context, asio::ip::tcp::endpoint(asio::ip::tcp::v4(), 6666)); /* Ports below 1025 doesn't work due to permission problem? */
for (;;) {
asio::ip::tcp::socket socket(io_context);
acceptor.accept(socket);
std::string message = std::to_string(clients.size());
asio::error_code ignored_error;
asio::write(socket, asio::buffer(message), ignored_error);
std::shared_ptr<asio::ip::tcp::socket> newconn = std::make_shared<asio::ip::tcp::socket>(std::move(socket));
clients.push_back(newconn);
/* This does not work */
for(auto &x : clients) {
std::string msg = "hello";
asio::write(x, asio::buffer(msg), ignored_error);
}
}
} catch (std::exception &e) {
std::cerr << e.what() << std::endl;
}
return EXIT_SUCCESS;
}
But the code snippet for looping over the clients does not seem to work. Am I implementing this incorrectly or is my understanding of shared_ptr's just too poor?
Question: how can I store asio sockets in a vector and reuse them later to send messages?
| 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 shared_ptr<socket>. I think you should use asio::write(*x, asio::buffer(message), ignored_error); if function write uses socket and not shared_ptr<socket>.
|
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
movementSpeed = 2.0f;
tempB = false;
allowMove = false;
movedTimes = 0;
mX = 0.0f;
mY = 0.0f;
}
void player::update(RenderWindow* Twin)
{
if (Mouse::isButtonPressed(Mouse::Right))
{
allowMove = true;
tempB = false;
}
// Movement
if (tempB == false)
{
mX = Mouse::getPosition(*Twin).x;
mY = Mouse::getPosition(*Twin).y;
tempB = true;
}
if (allowMove == true)
{
if (mX > playerS.getPosition().x)
{
playerS.move(movementSpeed, 0.0f);
}
if (mX < playerS.getPosition().x)
{
playerS.move(-movementSpeed, 0.0f);
}
if (mY > playerS.getPosition().y)
{
playerS.move(0.0f, movementSpeed);
}
if (mY < playerS.getPosition().y)
{
playerS.move(0.0f, -movementSpeed);
}
}
}
Player.h:
#include "Libs.cpp"
class player
{
public:
player();
virtual ~player();
void update(RenderWindow* Twin);
void render(RenderTarget* target);
private:
void initBody();
void initVarribles();
// player
Texture playerT;
Sprite playerS;
bool allowMove;
int movedTimes;
float mX;
float mY;
bool tempB;
float movementSpeed;
};
I don't think showing void initBody(), void render(), player() and virtual ~player() is necessary.
So if I run this, the player will go towards where the mouse was right clicked. But it follows a weird path, like it doesn't go straight to the mouse it kinda zigs zags. I think it's because the delta between playerX ... mouseX and playerY ... mouseY can differ. For example:
player_X = 500,
player_Y = 500,
Mouse_X = 760,
Mouse_Y = 124,
Mouse_X - player_X = 260
Mouse_Y - player_Y = 376
So if 376 is higher than 260 that means player_X will become Mouse_X first than player_Y.
I want it make them go smoothly, arive at the same time. I tried to do that but it didn't really work, well my code almost worked but honestly it's such a mess and creates other issues like the player shaking, whatever Im not gonna post that code. But if anyone knows how to make it smooth please.
| 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. Teleport to the target position and clear target.
target is not empty, and distance(player, target) >= moveSpeed: move one moveSpeed increment towards target.
So update becomes:
void player::update(RenderWindow* Twin)
{
if (Mouse::isButtonPressed(Mouse::Right) && !mouseDown) {
mouseDown = true;
target = Mouse::getPosition(*Twin);
}
if (!Mouse::isButtonPressed(Mouse::Right)) {
mouseDown = false;
}
// Movement
if (target)
{
sf::Vector2f vectorToTarget = *target - playerS.getPosition();
float distanceToTarget = sqrt(vectorToTarget.x * vectorToTarget.x + vectorToTarget.y * vectorToTarget.y);
if (distanceToTarget < movementSpeed) {
playerS.move(vectorToTarget);
target = {}; // clear target
} else {
sf::Vector2f movementDirection = vectorToTarget / distanceToTarget;
playerS.move(movementDirection * moveMentSpeed);
}
}
}
|
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 a strcmp?
if (bar.type == baz.type) {
printf("Same\n");
} else {
printf("Different\n");
}
I would like to do this for performance reasons.
|
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 address differs. You can return early if the address matches.
|
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"
#include <iostream>
#include <string>
using namespace winrt;
using namespace Windows::Foundation;
using namespace winrt::Windows::Devices::HumanInterfaceDevice;
int main()
{
//uint16_t const pid[] = { 0xBA0, 0x5C4, 0x09CC }
init_apartment();
int const product = 0x09CC;
int const vid = 0x054C;
int const usagePage = 0x01;
int const usageId = 0x02;
IHidDeviceStatics hello;
try {
printf("trying");
winrt::hstring data = hello.GetDeviceSelector(usagePage, usageId, vid, product);
}
catch (...) {
printf("error\n");
}
}
| 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, usageId, vid, product)
The code is trying to read from address zero. That address isn't mapped into any process, raising an Access Violation (SEH) exception with error code 0xC0000005 (that's the hexadecimal representation of -1073741819; use the MagNumDB if you need quick help with any numeric error code on Windows).
hello here is a default-constructed IHidDeviceStatics object, a C++/WinRT smart pointer type holding a nullptr. Dereferencing it will consequently trigger the Access Violation exception.
That said, you rarely ever need to interact with IXyzStatics interfaces; C++/WinRT deals with that for you already, and instead provides static class members on the corresponding projected Windows Runtime type (HidDevice)1.
The fix is simple:
winrt::hstring data = HidDevice::GetDeviceSelector(usagePage, usageId, vid, product);
std::wcout << data.c_str() << std::endl;
produces the following output:
System.Devices.InterfaceClassGuid:="{4D1E55B2-F16F-11CF-88CB-001111000030}" AND System.Devices.InterfaceEnabled:=System.StructuredQueryType.Boolean#True AND System.DeviceInterface.Hid.UsagePage:=1 AND System.DeviceInterface.Hid.UsageId:=2 AND System.DeviceInterface.Hid.VendorId:=1356 AND System.DeviceInterface.Hid.ProductId:=2508
1 This is somewhat involved. Raymond Chen covered this in On static methods in the Windows Runtime and C++/WinRT.
|
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;
SetConsoleTextAttribute(consoleHandle, getTextAttribute(config));
}
and it uses COMMON_LVB_UNDERSCORE attribute from windows.h to make text underlined. And the result of this function in powershell looks like this:
, and in Windows Terminal like this:, so apparently in the second case my function didn't work properly. I thought that the problem is that the Windows Terminal runs in virtual terminal mode. So I made another function for virtual terminals:
void WindowsVirtualCLI::setUnderlinedFont()
{
printf("\x1b[4m");
}
and now it didn't work for Powershell: , and worked properly for Windows Terminal: . But now I have another problem. How to distinguish that the program is run in Powershell or Windows Terminal. I tried using this function:
CLI& cli()
{
DWORD consoleMode;
auto consoleHandle = GetStdHandle(STD_INPUT_HANDLE);
GetConsoleMode(consoleHandle, &consoleMode);
if ((consoleMode & ENABLE_PROCESSED_OUTPUT) && (consoleMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING))
{
return windows::WindowsVirtualCLI::getInstance();
}
else
{
return windows::WindowsCLI::getInstance();
}
}
But it turned out that both Powershell and Windows Terminal have ENABLE_PROCESSED_OUTPUT and ENABLE_VIRTUAL_TERMINAL_PROCESSING enabled. And now, I have no other idea how can I distinguish these terminals in runtime. Do you have any idea how?
P.S.
I have changed cli() method to this:
CLI& cli()
{
DWORD consoleMode;
auto consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleMode(consoleHandle, &consoleMode);
SetConsoleMode(consoleHandle, consoleMode);
if ((consoleMode & ENABLE_PROCESSED_OUTPUT) && (consoleMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING))
{
return windows::WindowsVirtualCLI::getInstance();
}
else
{
return windows::WindowsCLI::getInstance();
}
}
And still it doesn't work as I need to.
| 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 that variable, if defined.
In PowerShell itself, [bool] $env:WT_SESSION returns $true if the variable has a non-empty value.
This approach isn't foolproof, because if you launch a regular console window (conhost.exe) from a shell running in Windows Terminal - e.g. with Start-Process cmd.exe - it'll inherit the WT_SESSION variable and thus produce a false positive in such sessions.
More elaborate, but robust solution:
A robust solution is to walk the chain of parent processes starting with the current process until the first process with an associated main window handle is found:
If that process' name is WindowsTerminal, it is safe to assume that the process is running in Windows Terminal - possibly indirectly, in a (by definition console-subsystem) process launched from the shell running directly in Windows Terminal.
Otherwise, it is safe to assume that a different application is hosting the process, possibly the process itself (a process running in a regular console window itself owns that window, and has a conhost.exe child process).
The following are PowerShell implementations:
PowerShell (Core) 7+ implementation:
$runningInWindowsTerminal =
if ($IsWindows) {
$ps = Get-Process -Id $PID
while ($ps -and 0 -eq [int] $ps.MainWindowHandle) { $ps = $ps.Parent }
$ps.ProcessName -eq 'WindowsTerminal'
} else {
$false
}
Windows PowerShell and cross-edition implementation:
Unfortunately, Windows PowerShell doesn't decorate the System.Diagnostics.Process objects output by Get-Process with a .Parent property reporting the parent process, which complicates the solution and requires a Get-CimInstance call to retrieve the parent information.
$runningInWindowsTerminal =
if ($env:OS -eq 'Windows_NT') {
$ps = Get-Process -Id $PID
while ($ps -and 0 -eq [int] $ps.MainWindowHandle) {
$ps = Get-Process -ErrorAction Ignore -Id (Get-CimInstance Win32_Process -Filter "ProcessID = $($ps.Id)").ParentProcessId
}
$ps.ProcessName -eq 'WindowsTerminal'
} else {
$false
}
|
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, 3,
6, 0, 0, 0, 5,
But instead, it should look like this:
3, 4, 5, 6, 7,
4, 5, 6, 7, 3,
5, 6, 7, 3, 4,
struct Queue
{
private:
int *data = nullptr;
int capacity = 100;
int counter = 0;
int first = 0;
int aftr = 0;
public:
void push_back(int value)
{
if (aftr == capacity)
{
if (counter < capacity)
{
for (int i = 0; i < counter; i++)
{
data[i] = data[first + i];
}
first = 0;
aftr = counter;
}
}
else
{
capacity = capacity * 2;
int *tmp = new int[capacity];
for (int i = 0; i < counter; i++)
tmp[i] = data[i];
delete[] data;
data = tmp;
}
data[aftr] = value;
aftr++;
counter++;
}
bool empty()
{
return counter == 0;
}
int pop_front()
{
if (counter == 0)
{
std::cout << "Queue is empty" << std::endl;
}
int value = data[first];
first++;
counter--;
return value;
}
void print()
{
if (counter == 0)
{
std::cout << "Empty queue" << std::endl;
}
else
{
for (int i = 0; i < counter; i++)
{
std::cout << data[first + i] << ", ";
}
std::cout << std::endl;
}
}
int front()
{
if (counter == 0)
std::cout << "Queue is empty" << std::endl;
int firstElement = data[first];
return firstElement;
}
int back()
{
if (counter == 0)
std::cout << ("Queue is empty") << std::endl;
int lastElement = data[aftr - 1];
return lastElement;
}
void rotate(int n)
{
for (int i = 0; i < n; i++)
{
const int tmp = front();
pop_front();
push_back(tmp);
}
}
};
int main()
{
Queue q;
q.push_back(3);
q.push_back(4);
q.push_back(5);
q.push_back(6);
q.push_back(7);
q.print();
q.rotate(1);
q.print();
q.rotate(2);
q.print();
}
| 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;
int capacity = 0;
int *data = nullptr;
int counter = 0;
int first = 0;
int aftr = 0;
public:
Queue():data{new int[initialCapacity]},capacity{initialCapacity}{}
void push_back(int value)
{
if ((aftr == capacity) && (counter < capacity))
{
for (int i = 0; i < counter; i++)
{
data[i] = data[first + i];
}
first = 0;
aftr = counter;
}
else if(counter == capacity)
//^^^ here memory allocation happens only when current queue memory exhausted
{
capacity = capacity * 2;
int *tmp = new int[capacity];
for (int i = 0; i < counter; i++)
tmp[i] = data[i];
delete[] data;
data = tmp;
}
data[aftr] = value;
aftr++;
counter++;
}
//rest of the code follows here
};
|
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, I can see the import of <oxf\omthread.h> in the generated code but i cannot call the function or even use the type RiCOSHandle
How can I add the OSAL classes to my package?
| (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://godbolt.org/z/Edc3TT1aT ) and the resulting debug assembly is almost identical with gdb for this example.
| 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 0;
}
(or use it with any other printf-style function?)
| 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 would like to deduplicate the functiondecl(hasname("foo"), hasdescendant(...) part.
So for example if I want to find a constructor, I can write
auto ctor = inFoo(cxxConstructorExpr());
It seems that I could write my own matcher using AST_MATCHER_P, but I can't figure out how.
Can you show me an example of custom matcher to deduplicate the beginning of my matchers?
| 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->valueChanged(), I'm just getting back a value of 1, regardless of where the slider position is set to. What am I doing incorrectly?
Here is my MWE:
QSlider* decay_slider = new QSlider(Qt::Horizontal, this);
decay_slider->setMinimum(1);
decay_slider->setMaximum(11000); // increments of 0.1 years
decay_slider->setTickPosition(QSlider::TicksBothSides);
QLineEdit* le_decay_time = new QLineEdit(this);
// Map slider position signal to LineEdit text update
QSignalMapper* mapper = new QSignalMapper(this);
QObject::connect(mapper,
SIGNAL(mapped(const QString&)),
le_decay_time,
SLOT(setText(const QString&)));
QObject::connect(decay_slider, SIGNAL(valueChanged(int)), mapper, SLOT(map()));
mapper->setMapping(decay_slider,
QString::number(decay_slider->sliderPosition()));
(This is Qt-5.15, if it matters.)
| 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];
numbers[j]=numbers[j+1];
numbers[j+1]=temp;
}
}
}
for(int i=0;i<5;i++){
cout<<numbers[i]<<endl;
}
}
| 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;
int main(){
int numbers[5] = {2, 7, 9, 3, 4};
int n = std::size(numbers);
bool swapped;
do {
swapped = false;
for (int j = 0; j < n - 1; j++){
if(numbers[j] > numbers[j + 1]){
swapped = true;
int temp=numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
n--;
} while (swapped);
for(int i=0;i<5;i++){
cout<<numbers[i]<<endl;
}
}
https://godbolt.org/z/E53dcejW5
|
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;
vector<Node> parent;
vector<Node> childList;
vector<Attract> closestAtts;
};
class Colony {
public:
double D, dk, di;
vector<Attract> attlist;
vector<Node> nodelist;
std::vector<vector<double> > attractors;
std::vector<vector<double> > centroids;
void run() {
// Initializes a colony with starting point
Node start;
start.coords[0] = 100.0;
start.coords[1] = 100.0;
start.coords[2] = 100.0;
nodelist.push_back(start);
}
| 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.coords.push_back(100.0);
start.coords.push_back(100.0);
nodelist.push_back(start);
}
|
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 << "Hello World\n";
std::string binary_data_file("font.dat");
struct stat statbuff;
stat(binary_data_file.c_str(), &statbuff);
file_size = statbuff.st_size;
void *data_buffer;
posix_memalign(&data_buffer, 4096, file_size);
std::ifstream data_input_file(binary_data_file.c_str(), std::ios::in | std::ios::binary);
data_input_file.read((char *) data_buffer, file_size);
data_input_file.close();
int * debug_buffer = (int * ) data_buffer;
for (int j = 0; j< 148481; j++) {
std::cout << "Data size: " << std::dec << file_size << std::endl;
std::cout << "Element: " << j << " Value: " << std::hex << *(debug_buffer + j) << std::endl;
}
return 0;
}
This code causes a Segmentation Fault when j == 148480
Data size: 211200
Element: 148477 Value: 0
Data size: 211200
Element: 148478 Value: 0
Data size: 211200
Element: 148479 Value: 0
Data size: 211200
Segmentation fault (core dumped)
Why is this the case? Surely the buffer size should be equal to 211200, right, so j should be able to go up to 211200?
| 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?
namespace std {
template<MyConcept T>
struct hash<T> {
size_t hash(T const& v) const { ... }
};
}
This would greatly simplify many specialisations in my code where I have a lot of different but similar classes adhering to the same concept which can be hashed all in the same way.
| 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 library requirements for the original template.
For this specialization:
template<MyConcept T>
struct hash<T> { /* ... */ };
If it is the case that (a) for all T that satisfy MyConcept, T depends on at least one program-defined type and (b) this specialization meets the requirements for hash (i.e. it's invocable, swappable, satisfies the normal hash requirements, etc.), then this is fine.
By depends on at least one program-defined type, it's not just that it's like my::Type, but it could also include std::vector<my::Type> and std::tuple<int, char, my::Type*>, etc. As long as something in there somewhere is program-defined.
|
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 = "";
/*wstring ipConvert(ipAdr().begin(), ipAdr().end());
LPCWSTR ip = ipConvert.c_str();*/
string url = "http://ip-api.com/json/168.197.155.244";
wstring urlConvert(url.begin(), url.end());
LPCWSTR urlFinal = L"http://ip-api.com/json/168.197.155.244";
LPCWSTR headers = L"Content-Type: application/json\r\n";
HINTERNET open = InternetOpen(down, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
HINTERNET connect = InternetConnect(open, urlFinal, NULL, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
HINTERNET request = HttpOpenRequest(connect, NULL, urlFinal, NULL, NULL, 0, 0, 0);
HttpAddRequestHeaders(request, headers, -1, HTTP_ADDREQ_FLAG_ADD);
HttpSendRequest(request, NULL, 0, NULL, 0);
InternetQueryDataAvailable(request, &size, 0, 0);
char* buff = new char[size + 1];
memset(buff, 0, size + 1);
InternetReadFile(request, buff, size, &wrt);
msg += buff;
InternetCloseHandle(open);
InternetCloseHandle(connect);
InternetCloseHandle(request);
return 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 approach pieces to each function as needed:
InternetConnect() wants the server's hostname and port (ie "ip-api.com" and "80"), and the INTERNET_FLAG_SECURE flag when connecting to an HTTPS server.
HttpOpenRequest() wants the resource's path on the server (ie "/json/168.197.155.244").
Alternatively, you can use InternetOpenUrl() instead. In which case, you don't need to use HttpOpenRequest() and HttpSendRequest() at all (and BTW, your use of HttpAddRequestHeaders() can be removed completely, as you are not sending any data to the server, so there is no need to add a Content-Type header to the request). See Handling Uniform Resource Locators in WinInet's documentation for more details about that.
|
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_SNAPMODULE, r6_pid);
while (Module32Next(snapShot, &entry)) {
if (std::wstring(entry.szModule) == moduleName) {
result = reinterpret_cast<std::uintptr_t>(entry.modBaseAddr);
break;
}
}
if (snapShot)
CloseHandle(snapShot);
return result;
};
No instance of constructor "std::basic_string<_Elem, _Traits, _Alloc>::basic_string [with _Elem=wchar_t, _Traits=std::char_traits<wchar_t>, _Alloc=std::allocator<wchar_t>]" matches the argument list
'<function-style-cast>': cannot convert from 'char [256]' to 'std::wstring'
| 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 other Unicode API/library conversion of your choosing (iconv, ICU, etc).
However, you don't actually need to do that in this case. Since your lambda is taking a std::wstring as input, just use the Unicode-specific version of the Module32 API functions instead, ie using the MODULEENTRY32W struct with Module32FirstW()/Module32NextW().
Also, you do need to call Module32First/W() before you can then call Module32Next/W().
Try this instead:
auto get_proc_base = [&](const std::wstring &moduleName) {
MODULEENTRY32W entry = { };
entry.dwSize = sizeof(entry);
std::uintptr_t result = 0;
const auto snapShot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, r6_pid);
if (snapShot)
if (Module32FirstW(snapShot, &entry)) {
do {
if (moduleName == entry.szModule) { // alternatively: if (moduleName.compare(entry.szModule) == 0) {
result = reinterpret_cast<std::uintptr_t>(entry.modBaseAddr);
break;
}
}
while (Module32NextW(snapShot, &entry));
}
CloseHandle(snapShot);
}
return result;
};
|
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> test = {1,2,3,4,5,6,7};
vector<int> final;
final.reserve(10);
for_each(test.begin(), test.end(), bind(mypred, placeholders::_1, 3, final));
for(auto i = final.begin(); i != final.end(); i++){
cout << *i << endl;
}
return 0;
}
This code can only print out two yes. But nothing in the vector final.
| 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 identical private members:
class Car{
const Wheel** m_ptrToArray{};
size_t m_count{};
};
My problem is that, in main(), I am making changes to the Wheel class values, where the Truck needs to have values that change, but the Car class needs to remain unchanged. Because the Car and Truck are both using double pointers, any update to the Wheel values changes the output for both because they are accessing the information via address, if I'm understanding correctly.
I believe my problem lies in the constructor used to create a Car object:
Car::Car(const Wheel* wheels[], size_t count)
I am trying to make a copy of the Wheel array that's passed in, so that I can assign the copy to the Wheel** m_ptrToArray member. That way, if I update the original array in main(), only Truck will change and Car will remain untouched. But I can't figure out how to do it.
If I use the following code in my constructor:
m_ptrToArray = new const Wheel*[m_count];
for (auto i = 0u; i < m_count; i++)
{
m_ptrToArray[i] = wheels[i];
}
It doesn't do what I want, because I'm just assigning the address of the wheels array.
If I do:
Wheel* temp = new Wheel[m_count];
for (auto i = 0u; i < m_count; i++)
{
temp[i] = *wheels[i];
}
m_ptrToArray = new const Wheel*[m_count];
for (auto i = 0u; i < m_count; i++)
{
m_ptrToArray[i] = &temp[i];
}
It works correctly, changing Truck but not Car. However, I run into memory loss because I'm using the new keyword without delete - because I have no idea how to pass it other than &temp[i] which means if I delete it, it won't be able to reach the value any more.
I am at a loss. Hopefully, this explanation makes sense to somebody who knows what they are doing. Let me know if you need any more information at all!
| 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 using a local variable in the constructor.
Try something like the following (FYI, I'm ignoring the need for copy/move constructors and assignment operators, per the Rule of 3/5/0. I'll leave that as an exercise for you to implement).
For Car:
class Car{
const Wheel** m_ptrToArray{};
size_t m_count{};
Wheel* m_wheels{};
public:
Car(const Wheel* wheels[], size_t count);
~Car();
};
...
Car::Car(const Wheel* wheels[], size_t count)
{
m_count = count;
m_wheels = new Wheel[count];
m_ptrToArray = new const Wheel*[count];
for (auto i = 0u; i < count; ++i)
{
m_wheels[i] = *(wheels[i]);
m_ptrToArray[i] = &m_wheels[i];
}
}
Car::~Car()
{
delete[] m_ptrToArray;
delete[] m_wheels;
}
Or simpler:
class Car{
const Wheel** m_ptrToArray{};
size_t m_count{};
public:
Car(const Wheel* wheels[], size_t count);
~Car();
};
...
Car::Car(const Wheel* wheels[], size_t count)
{
m_count = count;
m_ptrToArray = new const Wheel*[count];
for (auto i = 0u; i < count; ++i)
{
m_ptrToArray[i] = new Wheel(*(wheels[i]));
}
}
Car::~Car()
{
for (auto i = 0u; i < m_count; ++i)
{
delete m_ptrToArray[i];
}
delete[] m_ptrToArray;
}
And for Truck:
class Truck{
const Wheel** m_ptrToArray{};
size_t m_count{};
public:
Truck(const Wheel* wheels[], size_t count);
~Truck();
};
...
Truck::Truck(const Wheel* wheels[], size_t count)
{
m_count = count;
m_ptrToArray = new const Wheel*[count];
for (auto i = 0u; i < count; ++i)
{
m_ptrToArray[i] = wheels[i];
}
}
Truck::~Truck()
{
delete[] m_ptrToArray;
}
|
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);
}
I can't free the memory with delete or delete[].
What's the proper way of freeing the memory here?
The "dist4" function is just a random number generator:
random_device dev;
mt19937 rng(dev());
uniform_int_distribution<mt19937::result_type> dist4(1,4); // distribution in range [1, 4]
|
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.