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,136,219 | 72,136,351 | Creating a tuple from a folding expression return values | I try using the returning values of DecodeInternal function to create a tuple like this.
std::tuple<Types...> Decode(const uint8_t *bufferBegin)
{
uint8_t *offset = (uint8_t *)bufferBegin;
// (DecodeInternal<Types>(f, &offset), ...);
return std::make_tuple<Types...>((DecodeInternal<Types... | (DecodeInternal<Types>(&offset), ...) is a comma operator whose value is equal to the result of the last expression. Also, you don't need to explicitly specify template arguments for make_tuple, so just
return std::make_tuple(DecodeInternal<Types>(&offset)...);
|
72,136,480 | 72,136,627 | comparing bytes in google unit test framework | I have a following test case where I want to compare bytes in google test. In Unity unit test frame work we have
TEST_ASSERT_BYTES_EQUAL(0xaa, output[4]);
Is similar ASSERT available in google test. I have following code in google test and test case failing.
TEST(sprintf, NoBufferOverRunsForNoFormatOperations) {
c... | The problem is that you are comparing 0xaa, a literal of type int with a value of decimal 170, with the value of output[4] which is itself of type char. char is a signed type in C and C++. You wrote 0xaa or binary 10101010 into the byte in question. Because it is interpreted as a signed number, the leading 1 is conside... |
72,136,940 | 72,137,133 | How to put a part of variable argument list into another function? | I'm dealing with such a problem, I have function f(std::initializer_list<double> list),and I want to put a part of variable argument list (the second variable argument to end) into another function like:
void f(std::initializer_list<double> list){
f1(*(list.begin()+1,...,*(list.end-1));
}
The f1 function is normal... | An initializer list does not seem to have constructors which take a pair of iterators, see here. But you can use a span for that:
#include<iostream>
#include<span>
void f1(double a, double b)
{
}
void f2(auto list)
{
for(auto i : list)
{
std::cout<<i<<std::endl;
}
}
void f(std::initializer_list<d... |
72,137,275 | 72,137,788 | C++ union struct with struct member works on Clang and MSVC but not GCC | I am trying to define a union struct with some struct and primitive members overlapping in memory with a simple array. This works perfectly in Clang and MSVC, but it doesn't compile with GCC (G++).
struct Vector3 {
float x;
float y;
float z;
Vector3() {}
};
struct Plane {
union {
struct {
... |
Is the code example I gave valid C++?
No. Anonymous structs are not allowed, so the program is ill-formed.
What is the reason that it works in Clang and MSVC
When an ill-formed program works, it is often due to a language extension.
but not in GCC
Differences in implementation of similar language extension perhap... |
72,137,715 | 72,138,601 | Handle multiply cameras in Vulkan | I'm trying to implement rendering with different cameras.
When I use only one camera, everything is ok. But when I have two cameras with different transformation, rendering doesn't work properly, first scene is rendered with second camera transformation.
void Setup() {
...
// create uniform buffer (vmaCreateBuf... | Looking at your code, you change the same uniform buffer between two draw calls at command buffer creation time. But the contents of the bound uniform buffer are consumed at submission time instead and not at creation time. So by the time you submit your command buffer, it uses the uniform buffer contents from your las... |
72,138,134 | 72,138,598 | How to subtract char out from string in c++? | Hello I want to know how to subract string from string
For example
If string s = "124ab"
I can easily extract integer by using sstream but I don't know how to extract string
I want to extract ab from s;
I have tons of string and they don't have any rule.
s can be "3456fdhgab" or "34a678"
| You can use std::isdigit to check if a character is a digit. You can use the erase-remove idiom to remove characters that are digits.
Because std::isdigit has an overload it has to be wrapped in a lambda to be used in the algorithm:
#include <string>
#include <iostream>
#include <algorithm>
#include <cctype>
int main(... |
72,138,147 | 72,138,226 | Weird bug in pointers | I was trying to access single bytes of an int value via the code below. My problem is that whenever I try to remove long int i=0; from the code, it gives me a segmentation fault. Is there any reason this happens? I am not using I anywhere in the code.
// Online C++ compiler to run C++ program online
#include <iostream>... | This exhibits undefined behavior:
unsigned int* a;
*a= 4294967295; //set to max val (4 bytes)
The pointer variable a is never initialized to anything, so it points to a random memory address. Writing anything to that random garbage address (typically) causes a segmentation fault. It's just coincidence that adding ano... |
72,138,637 | 73,205,183 | Remote Desktop - getting session information (id, session name, etc.) from client side | Let's consider the following scenario: take a Windows Server instance (2012 or newer), with multiple user accounts. Each of those accounts needs to run an individual instance of a target application, which requires an active GUI as well as orchestration, in an automated fashion. We have no control over this target appl... | To come back on this, I have not found any viable way of setting custom session id for newly created session using freerdp. It might be possible if someone studied the whole protocol and reverse engineered the freerdp project, but it's a titanic task.
In the end, we imposed a restriction of a single active session per ... |
72,138,731 | 72,138,798 | Vector point std::vector<cv::Point> | I am trying to draw a trajectory on an image and saving these trajectory points as std::vector<cv::Point> trajectoryPoint and I would like to access the data inside.
This a short snippet from my code:
cv::line(currentFrame, trajectoryPoint.back(), cv::Point(x, y), Scalar(255, 255, 255), 1, 8);
trajectoryPoint.push_bac... | you can try to wrap a cv::Mat around it (which has nice printing ops):
std::vector<cv::Point> trajectoryPoint = ...
cv::Mat viz(trajectoryPoint);
std::cout << viz << std::endl;
|
72,138,745 | 72,138,836 | Incrementing iterator from end to begin | I want to iterate over a vector and when reaching the end it should loop back to the front.
This is a small example which does not compile
#include <vector>
std::vector<int>::iterator Next(const std::vector<int>& vec,
const std::vector<int>::iterator it)
{
auto itNext = it+1;
if (itNext == vec.end())
... | You cannot convert a const_iterator to an iterator because this would break const-correctness.
You basically have two options. When it is ok to return a const_iterator then return a const_iterator:
#include <vector>
std::vector<int>::const_iterator Next(const std::vector<int>& vec,
std::vector<int>::const_iterato... |
72,139,268 | 72,139,527 | Why does an optional argument in a template constructor for enable_if help the compiler to deduce the template parameter? | The minimal example is rather short:
#include <iostream>
#include <array>
#include <type_traits>
struct Foo{
//template <class C>
//Foo(C col, typename std::enable_if<true,C>::type* = 0){
// std::cout << "optional argument constructor works" << std::endl;
//}
template <class C>
Foo(typename ... | Template argument deduction does not work this way.
Suppose you have a template and a function using a type alias of that template:
template <typename T>
struct foo;
template <typename S>
void bar(foo<S>::type x) {}
When you call the function, eg foo(1) then the compiler will not try all instantiations of foo to see ... |
72,139,531 | 72,139,662 | why do i getting boost.URL linking error? | This is my project :
https://github.com/Naseefabu/HFTBOT/blob/master/src/main.cpp
When i try to build it,
Error :
https://gist.github.com/Naseefabu/5a114956f39b6c853916bcaf66f939e4
Is it because that i included boost/url/src.hpp in both httpClient.cpp and httpClient.hpp ??
What's the solution here ?
please help and adv... | From the URL library:
To use as header-only; that is, to eliminate the requirement to link a program to a static or dynamic Boost.URL library, simply place the following line in exactly one new or existing source file in your project.
#include <boost/url/src.hpp>
[Emphasis mine]
You include that header file in one o... |
72,139,656 | 72,139,888 | Unique_ptr in a class | The Human class turned out to be non-copied, since it contains a field of type unique_ptr, for which the copy constructor and the copying assignment operator have been removed. This prevents the compiler from automatically generating a copy constructor and assignment operator for the Human class.
How can I implement a ... | Your copy constructor might look like
Human::Human(const Human& rhs) :
name_(rhs.name_),
cat_(rhs.cat_ ? std::make_unique<Cat>(*rhs.cat_) : std::nullptr)
{}
but getting rid of std::unique_ptr and having Cat by value (or std::optional<Cat>) would be simpler:
Human::Human(const Human&) = default;
If Cat is poly... |
72,139,821 | 72,139,959 | Pass reference to function that takes `std::unique_ptr` | I have a reference to my object of type MyType, but I need to call a function, say myFunction that takes a std::unique_ptr<MyType>. What is the correct way to call myFunction? My attempt below seems to cause an "invalid pointer" error:
#include <memory>
class MyType {};
MyType myGlobalObj;
MyType& myGetter () {
r... | What you are trying to do is not possible without either doing a (deep-)copy of myGlobalObj or modifying myFunction.
A std::unique_ptr takes ownership of the memory that is used to store the contained object. That means that the std::unique_ptr may free (or reallocate, or whatever) the memory that it 'owns'. What it wo... |
72,140,255 | 72,140,567 | Tokenize a std::string to a struct | Let's say I have the following string that I want to tokenize as per the delimiter '>':
std::string veg = "orange>kiwi>apple>potato";
I want every item in the string to be placed in a structure that has the following format:
struct pack_item
{
std::string it1;
std::string it2;
std::string it3;
std::str... | You don't need an intermediate variable.
pack_item pitem;
std::stringstream veg_ss(veg);
std::getline(veg_ss, pitem.it1, '>');
std::getline(veg_ss, pitem.it2, '>');
std::getline(veg_ss, pitem.it3, '>');
std::getline(veg_ss, pitem.it4, '>');
You might want to make that a function, e.g. operator >> (with a similar ope... |
72,140,974 | 72,141,207 | What is underlying data structure of std::deque and how does it's iterator work? | I know that std::deque has the different chunks of contiguous memory and iterator is invalidated by inserting or erasing the middle of deque.
In addition to it, if I insert to the end side of element of deque, iterator is not valid but reference is valid.
There are some other unintuitive behavior of iterator of deque. ... | The key point is that a deque is made of several chunks of contiguous memory.
When you add an element in the first position then there are two situations:
Either the first chunk has still place to add an element:
| | | first element | second element | .... | ...
^
inserted element can be placed here
... |
72,141,695 | 72,141,778 | How arrays with an empty size works in c++? | I'm reading some materials about C++ and I just saw that array can be declared without a size (ex. int arr[], char x[][10]) and I'm wondering how/when it's actually used. Could someone explain both examples, please?
A more explicit example:
void foo(char[][10]);
Does that mean that any array like a[n][10], a[m][10] ca... |
Does that mean that any array like a[n][10], a[m][10] can be passed to the above function?
Yes. The function signature void foo(char[][10]); is allowed as long as you pass a compatible argument, i.e. a char array with 2 dimensions in which the second has size 10.
In fact, technically, the argument will decay to a poi... |
72,142,124 | 72,142,944 | Datetime parse and format in C++ | I'm using time_point the first time.
I want to parse datetime from string and found a difference when returning back to string from 1 hour.
std::chrono::system_clock::time_point timePoint;
std::stringstream ss("2021-01-01 00:00:09+01");
std::chrono::from_stream(ss, "%F %T%z", timePoint);
// timePoint == {_MyDur={_M... | This is the expected behavior.
Explanation:
system_clock::time_point, and more generally, all time_points based on system_clock, have the semantics of Unix Time. This is a count of time since 1970-01-01 00:00:00 UTC, excluding leap seconds.
So when "2021-01-01 00:00:09+01" is parsed into a system_clock::time_point, th... |
72,142,269 | 72,143,598 | How to interpret the explicit cast operator | As we can invoke the explicit cast operator, using static_cast, a C-style cast, or a constructor style cast. I am confusing how exactly the operator interpret to these three casts.
For example, consider the following code. The const Money& balance in display_balance() can be cast to double in three ways. So what are th... | Type Casting
It isn't the syntax you use when casting that determines how that cast is performed, it's the context based on the variable types.
When the compiler sees that you're trying to cast from Money to double, it tries to figure out a way to accomplish that - in every case, it uses the Money::operator double() op... |
72,142,363 | 72,142,548 | How to get characters from a file and display on console? |
I got this code from notes about file handling. From what I understand about this code, I want to get characters till x is reached in the file using this code. Why am I getting only the first character? If this code is incorrect, how should I alter the code to get characters till x is reached? Please help me understan... | a is a character and std::getline() returns an istream. Isn't there something wrong here? You cannot assign an istream to a char, so the code doesn't even compile.
You can simplify your code into this working example:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstre... |
72,142,518 | 72,144,807 | What will be the time complexity of this brute force apporach of finding largest valid bst in a binary tree? |
int size(Node* root){
if (root == nullptr) {
return 0;
}
return size(root->left) + 1 + size(root->right);
}
bool isBST(Node* node, int min, int max)
{
if (node == nullptr) {
return true;
}
if (node->data < min || node->data > max) {
return false;
}
return isB... | The size function is only ever used once and is O(n). So the complexity is O(n^2 + n) == O(n^2).
Update: Let me rephrase this as my reasoning wasn't clear at all.
The size function gets called many times. Either because a tree is BST or somewhere down there for each subtree when findLargestBST is called with each subtr... |
72,142,979 | 72,143,479 | Returning a struct pointer from class method | EDIT: Changed example code to code from my project that doesn't work.
I'm writing code in C++, learning templates and got stuck with some problem.
There's a class:
template<class T, class Cmp>
class AVLtree {
public:
AVLtree(const Cmp& _cmp) : root(nullptr), cmp(_cmp) {}
AVLtree(const AVLtree& ref);
~AVLtre... | Thanks for answers. Got a solution:
Just added typename before method definition outside of class. It looks like this:
template<class T, class Cmp>
typename AVLtree<T, Cmp>::Node* AVLtree<T, Cmp>::addNode(Node* node, const T& key) {
...
}
It seems that this is some spicialization of Visual Studio because I can see... |
72,143,184 | 72,143,362 | Are there any good mappings between GCC and MSVC warnings? E.g. -Wredundant-move on MSVC | This question is somewhat two fold, one being more general than the other. The specific question is; does MSVC have equivalent warnings to -Wredundant-move? More generally, is there anywhere online, even if it's someone's blog, that has a reasonable mapping between GCC and MSVC warnings?
I'm aware that warnings don't h... |
The specific question is; does MSVC have equivalent warnings to -Wredundant-move?
From what I've found, no, MSVC doesn't.
The subset of the warning messages that are generated by the Microsoft C/C++ compiler (Compiler warnings C4000 - C5999) does not have any similar warning.
The Compiler Warnings by compiler versio... |
72,143,535 | 72,143,648 | It is legal this approach for create a local variable in C++ | I'm new to C++ and try to understand how to create and use a class in C++.
For this I have the following code:
class MyClass
{
public:
MyClass()
{
_num = 0;
_name = "";
}
MyClass(MyClass* pMyClass)
{
_num = pMyClass->_num;
_name = pMyClass->_name;
}
voi... | You have a memory leak at MyClass myLocalObject = new MyClass();, since the dynamically-allocated object is used to converting-construct the new myLocalObject (this was almost but not quite a copy constructor) and then the pointer is lost.
You also didn't show the code using the vector, but if it doesn't delete the poi... |
72,143,753 | 72,143,862 | Is it possible to calculate the value after overflow? | I understand that if 1 is added to INT_MAX it will overflow and we will get the negative maximum. It is connected in a cycle. In the code below can I calculate the value after overflow.
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a = 100000;
int b = 100000;
int c = a*b;
cout<<c;
re... |
I understand that if 1 is added to INT_MAX it will overflow and we will get the negative maximum.
You've misuderstood. If 1 is added to INT_MAX, then the behaviour of the program is undefined.
can I calculate the value after overflow.
After signed integer overflow, the behaviour of the program is undefined, so doin... |
72,143,926 | 72,144,069 | std::stringstream's seekg does not work after while loop | I have this std::stringstream object whose contents I have to read (only) twice. For this I thought I could use its seekg member function to repeat the reading. But I can't make it work. Here's a MWE that reproduces the issues I'm having (adapted from the example in the docs).
#include <iostream>
#include <string>
#inc... | seekg first constructs and checks the sentry object (used by cppstreams to represent any stream failure), if that sentry object represents any failure then the function just returns without doing anything.
After the while loop, ss's failbit and eofbit will be set. The call to seekg will behave as described before (won'... |
72,144,090 | 72,144,215 | Receiving error: "error: static assertion failed: result type must be constructible from value type of input range" when constructing class vectors | I am trying to create a script that uses polymorphism to create a set of linking vectors within parent/child class structure. So far I have got the classes setup, but when trying to test the code I receive an error involving static assertion. When analysing the code line by line, I run into the error when I call 'vecto... | Upcast to a base class is ill-formed if the inheritance is not public. i.e
struct base {};
class derived : base {}; // private inheritance
int main(){
derived a;
auto & b = static_cast<base &>(a); // invalid
}
That's exactly what that last assignment expression is trying to do. You will need to inherit public... |
72,144,214 | 72,145,624 | How to constrain class template by disabling type argument of specialization itself, and why does(n't) it work? | Is it currently possible to constrain a class template that rejects type argument which is the specialization of the class template itself without using static_assert?
Since I cannot use requires expression to check if it is a valid typename, I have to create a class template instantiation validator that checks whether... | Not sure it is what you want, but
template <typename T> struct is_Hello;
template <typename T> requires (!is_Hello<T>::value) class Hello;
template <typename T> struct is_Hello : std::false_type{};
template <typename T> struct is_Hello<Hello<T>> : std::true_type{};
template <typename T>
requires (!is_Hello<T>::value)... |
72,144,761 | 72,145,006 | Why hasn't not_null made it into the C++ standard yet? | After adding the comment "// not null" to a raw pointer for the Nth time I wondered once again whatever happened to the not_null template.
The C++ core guidelines were created quite some time ago now and a few things have made into into the standard including for example std::span (some like string_view and std::array ... | There is one big technical issue that is likely unsolvable which makes standardizing not_null a problem: it cannot work with move-only smart pointers.
The most important use case for not_null is with smart pointers (for raw pointers a reference usually is adequate, but even then, there are times when a reference won't ... |
72,144,944 | 72,145,346 | Mask from bitfield in C++ | Here's a little puzzle I couldn't find a good answer for:
Given a struct with bitfields, such as
struct A {
unsigned foo:13;
unsigned bar:19;
};
Is there a (portable) way in C++ to get the correct mask for one of the bitfields, preferably as a compile-time constant function or template?
Something like this:
co... | Unfortunately, there is no better way - in fact, there is no way to extract individual adjacent bit fields from a struct by inspecting its memory directly in C++.
From Cppreference:
The following properties of bit-fields are implementation-defined:
The value that results from assigning or initializing a signed bit-f... |
72,145,179 | 72,145,260 | Recomended formating for temporarily inverting data at pointer and then passing pointer to temporarily inverted data | Long story short, I have a pointer to a value that is stored inverted, so when we are calculating a hash to verify data integrety, we need to invert the data that is used in the hash. The hash function, however, takes a pointer as input. So what we need to do is take our pointer, dereference it to get to the data, temp... | You need the temp variable. This expression:
hash = Algorithim::Calculate(&~pStartAddress[i], hash);
Is invalid because the result of the ~ operator is not an lvalue, and the & operator requires an lvalue.
On a side note, you can reduce repetition in your code by using the temp value in both cases:
uint32_t data ... |
72,145,613 | 72,145,836 | malloc(): corrupted top size Process finished with exit code 134 (interrupted by signal 6: SIGABRT) | please tell me why memory is not allocated in the line CLNAME* tmp=new CLNAME[this->Capacity_Ram]; the second day I'm looking for a problem, I can not understand what the problem is. The task is to write self-written vectors
Code:
header:
#pragma once
#include <iostream>
#include <memory.h>
using namespace std;
templ... | In MyVector<CLNAME>::PushBack
if (this->Size_Ram==0){
Array = new CLNAME[this->Capacity_Ram]; // already done in constructor, leaks.
// sets capacity of 5
this->Capacity_Ram=Capacity_Ram*2; // advertises a capacity of 10, not 5.
}
makes 2 mistakes. 1) storage w... |
72,146,555 | 72,146,594 | Is there an alternative to the builder pattern that is preferred in C++? | I'm coming from Java where the builder pattern is used heavily, e.g.
Foo foo = new FooBuilder()
.setBar(43)
.setBaz("hello, world!")
.enableCache(true)
.build();
Automapper for example is popular library that generates this pattern via Java annotations.
I don't see any such library for C++—only gists a... | A common pattern is aggregate initialisation:
Foo foo = {
.bar=43,
.baz="hello, world!",
.enableCache=true,
};
Note that designated initialisers such as used here were introduced in C++20. Prior to that, you could only initialise sub objects positionally.
Another pattern, common in absence of designated in... |
72,146,745 | 72,151,959 | Repeat a cubemap texture on a cube face with OpenGL | Is it possible to make a cube map texture (GL_TEXTURE_CUBE_MAP_POSITIVE_X...) repeat on a given face with OpenGL?
I have a simple unit cube with 24 vertexes centered around the origin (xyz between (-0.5, -0.5, -0.5) and (0.5, 0.5, 0.5)). Among its attributes, initially I set the uvw coords to the xyz position in the fr... | No, it's not possible to have wrapping with GL_REPEAT for cubemaps. You should probably look to the alternatives people have suggested in the comments.
The reason for this, is that the coordinates that you pass to the cubemap sampler are interpreted as a direction. The length of this direction is ignored. You can think... |
72,146,860 | 72,146,922 | Different C++ fork() behavior between CentOS 7.5 & RockyLinux 8.4, Ubunu 20.04 | I'm working with some legacy code. It works fine on a CentOS 7 system. The args array gets hosed on both a Rocky 8.4 and Ubuntu 20.04 system. I've simplified the problem and added print statements. The execv() was launching another program. The args going into the execv get messed up. Without the fork, the code works a... | THis loop
for(uint8_t i = 0; i < stringArgs.size(); i++) {
std::string tmp(stringArgs[i]);
args[i] = const_cast<char*>(tmp.c_str());
std::cout << "\n\t"<<args[i]<<"'\n\n";
}
is creating an array of pointers to a temporary on the stack, or some internal implementation defined part of std:... |
72,147,214 | 72,147,349 | How can I repair this error that occurs occasionally when my code is running? | Sometimes the code runs till the end without any errors while other times it stops in the middle and gives me this error Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT) here is a picture of it (https://i.stack.imgur.com/uZDX1.png). The error is in my header file named Functions, and the compiler used in this picture is ... | For starters these lines:
receipt* head = NULL;
head = new receipt;
do not make a great sense. The operator new creates an uninitialized object of the type receipt (for example the data member link can have an indeterminate value) that is a reason of undefined behavior when the pointer used in functions. What you need... |
72,147,303 | 72,147,740 | Programs which accept uppercase and lowercase commands as input | I'm trying to add a help/information box in my program that pops whenever someone type in a /h, /?, /help commands. I want to make sure that my program accepts all characters in both upper and lower case. From what I have, I can check the most frequent cases of these commands, but not all (ie. /HeLp). Looking for way t... | With the Microsoft compiler (which you seem to be using), you can use the function _wcsicmp instead of wcscmp to perform a case-insensitive compare.
Other platforms have similar functions, such as strcasecmp and wcscasecmp on Linux.
ISO C++ itself does not provide a function which performs a case-insensitive compare. H... |
72,147,549 | 72,148,008 | How do you use std::distance in a range-based loop? | This is my code that won't compile:
for( auto occurances : occ ){
if( occurances == 1 )
cout << distance( occ.begin(), occurances )
}
It gave me the following error:
candidate template ignored: deduced conflicting types for parameter '_InputIter'
('std::__wrap_iter<int *>' vs. 'int')
This is the fifth time I e... | You could count the iterations round the loop yourself:
size_t loop_count = 0;
for( auto occurances : occ ){
if( occurances == 1 )
cout << loop_count;
++loop_count;
}
But that's really no easier than just coding the for loop explicitly, and you might forget to bump the counter.
OK, since the OP is interested ... |
72,147,678 | 72,153,669 | Meshes loaded via Assimp look distorted | So I'm trying to load and render mesh with assimp and DirectX11.(Im loosely following tutorials on youtube) The problem is that it looks weird and distorted. I've checked my meshes - blender and assimp viewer load them correctly.
Results of rendering suzanne from obj file:
Suzanne from obj file
It looks kinda like the ... | So I've figured it out. The issue was that in some other file i already defined structure named Vertex. That structure contained also uv's so ultimately my vertex buffer ended up being a mess. Silly mistake.
|
72,148,047 | 72,152,028 | Intel MKL for matrix multiplication when rows are not memory-contiguous | Our hardware is Intel Xeon Phi so we are encouraged to get the most out of it by replacing hand-written linear algebra ops (e.g. square matrix multiplications) using Intel MKL.
The question is which should be the correct MKL usage for this case, as the problem of our matrices' rows not being contiguous in memory may fo... | Dense BLAS operations can operate on matrices with a given fixed stride but in your case the stride is not constant. Sparse matrices are meant to operate on matrices containing a lot of zeros which is apparently not your case (at least not in the provided example).
Since your matrices is huge in practice (20k x 20k), t... |
72,148,345 | 72,148,368 | Array gives different values in main() and in a function() | I am trying to store a 1d array that stores random numbers into another 2d array.
So as you can see, I am trying to store the passed random array a1 from the main() function to the test() function. And then I am adding it into p[][]. But I don't know why when I am trying to output the array p[][] in the main function, ... | You have two different p arrays: One in main and one global. The print loop in main is accessing the local p in main while test accesses the global one. That means only the global p gets filled with data and main is stuck with a different array that wasn't filled with data.
Remove the int p[9][9]; in main. That line cr... |
72,148,673 | 72,152,877 | Win32 application not finding icon for window | I created a icon as a resource
I checked explorer and it works just fine, my exe now has that icon
Next, I used hIcon to set the icon of my window but it says that IDI_ICON1 is undefined
Code:
wc.hIcon = LoadIcon (hInstance, MAKEINTRESOURCE(IDI_ICON1));
Is there any idea of why this is happening?
| Symbolic constants for resource identifiers (such as IDI_ICON1) are usually stored in a separate header file called Resource.h by default. This allows both the resource script (.rc file) as well as source code to access the same symbols.
To use the constants in source code you need to introduce them through an #include... |
72,149,102 | 72,164,672 | Add Serialize to SFML Color | I am working on serialization of color data for SFML objects and ran into an issue where they are not supported by default, as they are not a default type. I tried making a wraparound class, which failed but I found info of adding the type to cereal itself. Based off of what I read at Serialize/deserialize SFML Vectors... | dergvern47 on Reddit helped me with this. The issue was 2 fold. Accessing the values inside cannot be done with this, but with the object inside the function, and that the .h file this is inside needs to be #include in the highest .h file existing in the project. The original post can be found here https://www.reddit.c... |
72,150,508 | 72,151,922 | How to represent the relationship for this demo code snippet? | How to represent the relationship between class ResMulti and class Do_work when drawing a class diagram for this demo code snippet (see on godbolt):
#include <thread>
#include <future>
#include <functional>
class Res4ClassA{};
class Res4ClassB{};
Res4ClassA Calculate_A(){return Res4ClassA{};}
Res4ClassB Calculate_B()... | There is no direct relationship between ResMulti and Do_work:
Do_work may be dependent on Res4ClassA because it may need to know about that type (not formally in C++, because the pointer is used without ever being dereferenced, but if possibly in the design, if we’d expect the operation to to anything maningful with t... |
72,151,124 | 72,151,358 | why alignas(64) not aligned with 64 | why alignas(64) not aligned with 64? for example:
struct alignas(32) st32
{
float a;
uint16_t b;
uint64_t c;
};
struct alignas(64) st64
{
float a;
uint16_t b;
uint64_t c;
};
int main()
{
st32 x;
st64 y;
std::cout
<< "alignof(st32) = " << alignof(st32) << '\n'
<< "a... |
why &st64 b: 0x7ffc59fc9684 is not 0x7ffc59fc9688
Aligning a structure does not affect the alignment of the sub objects of the structure. The address of the enclosing structure is 64 byte aligned, and b is the second member after a 4 byte sized a, so it's reasonable to expect b to not be 64 byte aligned.
if alignas ... |
72,151,184 | 72,151,416 | Moving the function templates definition to different translation unit resolves the ambiguity error | I was using function templates when I noticed that moving the definition of one of the function template to a different translation unit resolves the ambiguous error. Below are the two examples that I tried. The first example produces ambiguous error as expected but when I move the definition of one of the function te... |
how does the C++ standard resolves this ambiguity.
From temp.over.link#1:
1. It is possible to overload function templates so that two different function template specializations have the same type.
2. Such specializations are distinct functions and do not violate the one-definition rule.
(emphasis mine)
Now, in th... |
72,151,450 | 72,151,535 | On the conversion from std::string type to template T type in C++ | I've found on this forum the following snippet witten by user Ben Voigt:
//forward declaration
template<typename T>
T getline_as(std::istream& s);
template<>
std::string getline_as<std::string>(std::istream& s)
{
std::string str;
std::getline(s,str);
return str;
}
template<typename T>
T getline_as(std::i... | std::stringstream convert(...); is a constructor call, but trying to do convert(...); after the stream is created is illegal (it would require the stream to overload operator(), which it doesn't do). convert = std::stringstream(...) would work, but I'd just completely recreate the stream.
You also should use a read-onl... |
72,151,546 | 72,151,690 | Too many copies of the function to use std::move in C++ | I have 2 classes: A and B. I need to pass instances of them to a function that will push them into a vector. I want to have good efficiency in my program, so I try to use move semantics. So in that function I need const A& and A&& type for A as well as for B.
It forces me to create 2^N number of functions where N is th... | You can create a template function and use std::forward to pass on the value with the correct reference type:
template<class T, class U>
void Function(T&& a, U&& b) // note: universal references are used here, not rvalue references
{
elements.emplace_back(std::forward<T>(a), std::forward<U>(b));
}
|
72,151,600 | 72,151,685 | value of set::find() if not found in container | I am trying to understand std::find(). Below is my code.
std::set::find searches the container for an element equivalent to
val and returns an iterator to it if found, otherwise it returns an
iterator to set::end.
But when I gave find(100) I am getting 7 rather than 20.
#include <iostream>
#include <set>
using names... |
auto a2 = s1.find(100);
cout << "find(100) : " << *a2 << endl;
Here you dereference (*a2) the end iterator. That is undefined behaviour - remember that s1.end() points to one past the last element and must not be dereferenced.
You're unlucky that you got a value from that dereference - it would be more convenient i... |
72,152,281 | 72,152,718 | *char conversion to/from bool in call to strstr | I have code that is supposed to remove all characters in one C-string from another.
The problem arises when I try to use the function strstr: both an array and a char* get converted to bool. Obviously it doesn't work because strstr needs to receive 2 char* arguments.
#include <iostream>
#include <ctype.h>
#include <str... | You have two errors in one line of your code. The first is not addressing the issue that the != operator has higher priority than =. Thus, in the following line:
while( p=strstr(str_temp,del)!=NULL) {
the comparison is actually:
while( p = ( strstr(str_temp,del)!=NULL ) ){
So, you are attempting to assign the result ... |
72,153,026 | 72,154,762 | c++ Cannot create magnifier window | Im trying to make a magnification program, but I cannot create the child window without the error 1407, The child window also makes the host windows gui disappear.
hwnd = CreateWindowEx(WS_EX_TOPMOST | WS_EX_TRANSPARENT | WS_EX_LAYERED, wc.lpszClassName, skCrypt(_T("magnifier")), WS_POPUP | WS_CLIPCHILDREN, rect.left, ... | Thank you to the people that helped me fix this.
I fixed this by changing the classname in wc2 to "Magnifier"
|
72,153,033 | 72,153,249 | Problem passing a method of a class as a std::function parameter | I am trying to write this function:
void CChristianLifeMinistryEditorDlg::PerformAutoAssignForAssignment(
const MSAToolsLibrary::AssignmentType eAssignType,
const CString strStartingName,
std::function<void(CString)> funcSetAssignName)
{
CString strName = L"abc";
CChristianLifeMinistryEntry *pEntr... | In order make a method of a class callable, you must supply a this object.
Wrapping such a method in a std::function can be done in 2 ways. Both of them associate a specific class instance with a method, making it callable:
Use std::bind - see the documentation: std::bind, and a specific stackoverflow post regarding t... |
72,153,420 | 72,153,563 | Is `auto(expr)` treated as cast at the beginning of the expression statement? | I have a simple code snippet shown below (https://godbolt.org/z/cPT3PhYdj):
int main() {
int x = 1;
auto(1); // ok in GCC, error in Clang
auto{1}; // ok in GCC, error in Clang
static_cast<void>(auto(x)); // ok
auto{x}; // ok in GCC, error in Clang
auto(x); // both error in GCC an Clang
}
Where both GCC and... | From Explicit cast conversion:
auto ( expression ) (8) (since C++23)
auto { expression } (9) (since C++23)
8,9) The auto specifier is replaced with the deduced type of the invented variable x declared with auto x(expression); (which is never interpreted as a function declaration) or auto x{expression}; r... |
72,153,514 | 72,154,577 | Estimation of time required for calculation in Eratosthene's sieve algorithm | I am using Qt and cpp to calculate some time consuming calculation like prime number calculation using Eratosthene's sieve algorithm as shown below.
QElapsedTimer timer;
timer.start();
int p;
for ( p = 2ull; p * p <= n; p++)
{
// If prime[p] is not changed,
// ... | Lets ignore if a number is prime or not. Estimating that is a big math problem involving the density of primes and such. Lets just assume every number is prime. That gives:
The code marks all even numbers, so that is N/2 operations. Then all numbers divisible by 3, so N/3 operations. Then N/4, N/5, N/6, N/7, ...
So ove... |
72,153,701 | 72,153,870 | unpack variadic arguments and pass it's elements accordingly | suppose I got a struct i.e. Coord that contains two static member variables, then pass it as an argument of variadic template function variadic_print_coord(), how do I unpack the variadic expressions, to call the print_pair() function that shown below.
template<class T1, class T2>
void print_pair(T1 t1, T2 t2)
{
std:... | You can use the following construct involving a fold expression
template<class... COORDs>
void variadic_print_coord()
{
(print_pair(COORDs::X, COORDs::Y), ...);
}
In this case you won't need the variadic version of print_pair, as the calls basically decouple.
#include <iostream>
template<class T1, class T2>
void p... |
72,153,819 | 72,153,956 | assigning new array to reference variable | void byReference(int (&p)[3]){
int q[3] = {8, 9, 10};
p = q;
}
I want to write function where i can reassign the p with new array. I am not sure if we can do that.
My goal :
i want to change the original array, like we do swapping of two number by call-by reference.
Edit:
my working solution :
void byReferenc... | In c++ it is recomended to use std::array for fixed size arrays, and std::vector for a dynamic size arrays.
Both of them can be passed by refernce, to be modified by a function.
This requires the function to declare that the argument is passed by refernce using the & symbol.
See the example below:
#include <array>
#inc... |
72,153,836 | 72,154,029 | Issue running c++ code from 2013 using Clion | [I have very little experience with c++, and this is the first time I use it after more than 10 years].
I need to run some c++ code from 2013, and I am having issues doing so. I am using Clion on OSX Monterey (M1 Silicon chip). If I run a very simple script (main.cc below), I get the error
Undefined symbols for archite... | The problem has nothing to do with architecture or the version of C++. The definition of Hair::read couldn't be found because your CMakeLists.txt wasn't compiling the file that contained it. You need to tell it to compile Hair.cpp in addition to main.cpp, like this:
add_executable( OpenCVTest main.cpp Hair.cpp )
|
72,153,965 | 72,154,433 | C++ method for non class or struct | Is there any way in C++ to have a method for variable which is not a class or struct? Suppose I have a defined type dogs for convenience.
using dogs = std::unordered_map<std::string, dog>;
dogs d;
Now, what I want to achieve is to have a method, e.g. print() which operated on the dogs type variable d.
d.print();
| Your d.print() means invocation of the method print that std::unordered_map<std::string, dog> actually hasn't. You can't add new methods to an existing class in C++ in contrast to e.g. Python because C++ is a statically typed language. The only way to add new method to a class is creating a new class that inherits to t... |
72,153,990 | 72,154,236 | C++20: Unable to properly use concepts to enforce that a constructor template parameter is a base of one of two types | I am a bit of a noob to C++20, and I only recently have been able to use C++11/14 so I am trying to update my knowledge and I'm having a bit of trouble trying to use concept requirements. My goal is to ensure that a class of type SocketAddress only takes a type of IpV4Address or IpV6Address in its constructor, while us... | This is dumb but a clean and rebuild literally fixed my problem.
Additionally given @PatrickRoberts suggestion, my concept is now defined as:
template <typename T>
concept IpAddress = std::is_base_of<IpV4Address, std::remove_cvref_t<T>>::value ||
std::is_base_of<IpV6Address, std::remove_cvref_t<T>>... |
72,154,006 | 72,154,042 | "error: break statement not within loop or switch" in arduino one | i don´t have any idea of coding but i´m doing a school exersice and it gives me the error of the title
while (distancia<200 && distancia>100);
{
lcd.print("ALTO");
delay(1000);
lcd.clear();
delay(1000);
if(distancia<100)
{
break;
}
}
if(distancia<100);
{
lcd.print("INTRUSO EN");
lcd.setC... | Here
while (distancia<200 && distancia>100);
--------------------------------------^
remove that semicolon, it terminates the while right there
while (distancia<200 && distancia>100)
|
72,154,506 | 72,154,778 | Is auto(x); considered a declaration of a variable named x or an explicit type cast in C++23 | I came across this which states:
Not a bug, auto(x); is interpreted as auto x;. Use +auto(x); if you want that to be an expression.
The above seems to imply that since auto(x); is a declaration(equivalent to auto x;) it should be rejected since we're using auto and don't have an initializer.
While this states:
Yes ... | Note the code referenced by the GCC bug in question:
int main() {
int x = 0;
float t;
t = auto(x);
}
auto(x) here is not a statement; it is unequivocally an expression. If auto(x) is used as an expression, it will behave as an expression. If it however is used in a way that makes it a statement, then it will beh... |
72,154,546 | 72,154,572 | Can someone point out the problem in my linked list implementation? | When I compile the following code, I get compile error that " head does not name a type".
Can someone explain what goes wrong ?
#include <iostream>
using namespace std;
/* Link list node */
struct node {
int val;
struct node* next;
node(int x)
{
this->val = x;
next = NULL;
}
};
... | Only declarations are allowed outside of functions. Expressions such as head->next = node(4) need to be inside a function. You should move that code into main().
|
72,154,655 | 72,154,795 | How to pass the Image pointer to Image_dos_header in windows | How to properly construct the NtHeader when calling PIMAGE_NT_HEADERS64 Microsoft docs does not seem to have much remarks on this function, the problem is that casting from void* to DWORD fails
int runPE64(void* Image)
{
/*
non relevant code
*/
char CurrentFilePath[1024];
DOSHeader = PIMAGE_DOS_HEA... | DWORD is 32 bits (4 bytes) in size, in both 32-bit and 64-bit systems.
The compiler is warning you that the size of DWORD is different than the size of a void* pointer in your compilation, so you will lose bits. This means you must be compiling a 64-bit executable, where pointers are 64 bits (8 bytes) in size.
You need... |
72,154,684 | 72,156,665 | Printing decimal precision upto desiired number in cpp | I have an application I want to print the precision of the calculated prime number up to the desired number. But the number is omitted on the terminal as shown below.
The code I used for this is as
int main ()
{
cout << "Enter the precision for calculation" << endl;
long num_steps ;
cin >> num_steps ;
... | use iomanip. first add #include <iomanip> and then std::setprecision(num_steps) like this program:
This code was written based on Calculate Pi from Geeks For Geeks.
#include <cstdio>
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
// Initialize denominator
double k = 1;
// Initialize su... |
72,154,759 | 72,154,847 | The "break statement" is just not working like it should | This is the code but for some reason, when (distancia<100) the ("ALTO") still appears, and the same with the other while loop
while (distancia<200 && distancia>100)
{
lcd.print("ALTO");
delay(1000);
lcd.clear();
delay(1000);
if(distancia<100)
{
break;
}
}
while(distancia<100)
{
lcd.prin... | this is your while loop:
while (distancia<200 && distancia>100)
and this is your if:
if(distancia<100);
{
break;
}
a variable can't be greater and smaller than 100 at the same time so that if is basically useless
|
72,155,084 | 72,155,259 | Is there a way to turn input string to input stream in c++? | What I want to do is get user input from the terminal and use this input in other functions in my program. Since my functions only take input streams as arguments I want to convert the input string into an input stream.
int main(int argc, char** argv)
{
std::vector<std::string> args(argv, argv + argc);
if... | The std::istringstream class has a constructor that takes a std::string as an argument, which uses a copy of the string passed as the initial content of the stream.
So, rather than use a std::vector to store all your input lines from the console, just keep adding those to a single (different) std::string object, rememb... |
72,155,568 | 72,155,624 | Circular main in makefile | when i run "make" with the Makefile I wrote, it says "Circular main <- main dependency dropped." how to solve it?
main: main main.cpp pair.cpp
g++ -o main main.cpp pair.cpp
generate:
g++ -shared -fPIC -o libpair.so pair.cpp
clean:
rm main.exe
| main: main main.cpp pair.cpp
g++ -o main main.cpp pair.cpp
There are too many mains in your makefile, make sure that you know the first main is the target name, and the second one is an executable that generated by "something else".
tar_main: main_exec main.cpp pair.cpp
g++ -o main_exec main.cpp pair.cpp
Assu... |
72,155,603 | 72,155,738 | how to evaluate concept to false upon expression compilation error | I was trying to change the following example concept code that, under certain inputs, caused an error instead of evaluating false:
template <typename T>
constexpr bool inner = T::prop;
template <typename T>
concept outer = inner<T>;
struct pass {static constexpr bool prop = true;};
struct fail {static constexpr bool ... | You can use requires-clause to initialize inner, which first requires that the return type of T::prop must be const bool&, then use nested requires with T::prop as its value
#include <concepts>
template <typename T>
constexpr bool inner = requires {
{T::prop} -> std::same_as<const bool&>;
requires T::prop;
};
te... |
72,155,848 | 72,156,635 | Loading C++ dll in python doesn't work with C++ libs | So I am trying to make a C/C++ dll for a project but any C++ library I include in my header, ends up causing loading problems when I try to load it using ctypes in python. I'm guessing maybe ctypes doesn't have c++ libs paths included? I made a simple demonstration to my problem.
init2.h: Generic Header file for dll an... | The problem was as I expected due to cdll not able to find the C++ library. The file name for my case was libstdc++-6.dll. Which is located in the bin folder in my compiler's directory. To make cdll search for the dependencies in that folder I did the following:
import os
# add dependency directory
os.add_dll_director... |
72,156,800 | 72,157,004 | Replace every occurrence with double in string | I'm trying to write a function whose first parameter is a string and the second parameter is vector of real numbers. The function should return as a result a new string in which each occurrence replaces the sequences "%d" or "%f" with one number each from the vector, in the order in which they appear. In doing so, if t... | You could use:
regular expressions to search for the pattern (%d|%f), i.e., %d or %f, and
a string stream to create the string to return.
Going into some more detail:
The code is basically a while (std::regex_search).
std::regex_search will return whatever was in the input string before the matched pattern (what you... |
72,156,970 | 72,161,464 | xt::random::binomial returns different results based on output size | I am writing code to generate an NxN matrix of 0s and 1s in XTensor where the probability of an entry being 1 is 1/N. Additionally, I want to discard all values on the diagonal and above. Finally, I want to find the indices of all 1s. Hence, I am using the following code:
auto binomial = xt::tril(
x... | It appears that you have to worry about types here. Internally, you should be able to resolve indices up the N * N. For you N = 1e5 that means 1e10. The maximum size of uint32_t is about 4e9, so that means that you overflow.
What does seem to work is
size_t N = 100000;
auto binomial = xt::tril(
xt::rand... |
72,157,313 | 72,158,973 | How to retrieve a previously declared variable with __COUNTER__ pasted inside its name in C++? | I have the following problem:
#define CONCAT_(A,B) A ## B
#define CONCAT(A,B) CONCAT_(A,B)
#define CREATE_NAME(N) CONCAT(N, __COUNTER__)
If I wanted to retrieve a specific variable##__COUNTER__ later in the code how can I achieve this? I only need to get the previous one, something like:
#define CONCAT_(A,B) A ## B
#d... | BOOST_PP_SUB macro from boost library can be evaluated and expanded to an identifier.
#include <boost/preprocessor/arithmetic/sub.hpp>
#define CONCAT_(A,B) A ## B
#define CONCAT(A,B) CONCAT_(A,B)
#define CREATE_NAME(N) CONCAT(N, __COUNTER__)
#define GET_NAME_PREV(N) CONCAT(N, BOOST_PP_SUB(__COUNTER__, 1))
auto CREATE... |
72,157,397 | 72,157,403 | clang++ library not found even when providing library path | I was trying to create a new OpenGL project with glfw and glad using vs code on an m1 Mac, and setup the files such that I have the include folder and lib folder which contains the necessary headers and library (libglfw3.a) files and the src folder that contains the glad.c and main.cpp, all in my workspace folder.
I ha... | Normally when you give libraries to link with the -l flag, you omit the lib prefix. For example: "-lglfw3" links the file "libglfw3.a". It looks like you should change your -llibglfw3 option.
|
72,157,815 | 72,157,918 | Ctrl still pressed with keyb_event() | i'm trying to help a friend with a macro for his mouse, but i've been strugling with an error.
But when i use :
if(GetAsyncKeyState(VK_XBUTTON2)){
keybd_event(VK_LCONTROL, 0xA2, 0x0001, 0);
Sleep(50);
keybd_event(VK_LCONTROL, 0xA2, 0x0002, 0);
Sleep(50); }
My ctrl still holded unless i click in my console a... | Don't use magic numbers in your code, it makes it harder to read and understand. Use named constants instead. In this case, KEYEVENTF_EXTENDEDKEY and KEYEVENTF_KEYUP. Then you will notice that you are not specifying the KEYEVENTF_EXTENDEDKEY flag when releasing the key. Use the | (bitwise OR) operator to combine flags.... |
72,157,936 | 72,157,962 | This is a question from GFG. I am trying to analyse and understand this code | This is a code I have taken from GeeksForGeeks. I am trying to understand the code.
In the line in the function deleteEle which says if(i==n) return n, how could i become n if it is running for < n times in the for loop just above it?
#include <iostream >
#include <cmath>
using namespace std;
int delet... |
how could I become n if it is running for < n times in the for loop just above it?
Because it may happen that the if condition arr[i] == x inside the preceding for loop is never satisfied which in turn means that the break is never executed in which case the last iteration will increment i so that i becomes equal to ... |
72,157,975 | 72,158,307 | C++ Set: thread 1 is inserting, is the inserting result visible to iterator in thread 2? | I have following code
#include <thread>
#include <mutex>
#include <condition_variable>
#include <iostream>
#include <set>
#include <string>
#include <chrono>
#include <atomic>
using namespace std;
set<string> messages_;
mutex mu;
void thread1() {
for(int i=0; i<20; ++i) {
{
lock_guard<mutex> lock(mu);
... | Since the set contains std::string, the elements are sorted in lexicographic order.
Suppose Thread 1 gets to insert strings "9", "10" and "11" while Thread 2 is waiting on condvar. In this case, "10" will be the smallest string and thus it will be printed first followed by "11" and "9".
|
72,158,223 | 72,162,165 | Variadic template template wrapper: weird compilers errors, possibly bugs | Over years of template metaprogramming practice, I have encountered all sorts of weird compiler bugs and errors. But with this one, I must say that I am somewhat puzzled. I have no idea which compiler is correct: gcc, clang, msvc, and intel all give different results (and as surprising as it may sound, only intel compi... | All compilers are right, the two failing tests are ill-formed NDR ("No Diagnostic Required").
The > 3 arguments case is ill-formed NDR because of [temp.res.general]/6.1:
The program is ill-formed, no diagnostic required, if:
— no valid specialization can be generated for a template ... and the template is not instanti... |
72,158,300 | 72,158,465 | Is there a way to use (std::cin).get() to accept newlines when asking for input? | (std::cin).get()
I want to use std::cin to collect a string with spaces, like "1/2 oz of flower". When I add a space and then press enter it exits the program instead of collecting the rest of the input.
Found this stdcin-and-why-a-newline-remains and I saw a comment that says you can use .get(), but its not working f... | I think you should use https://en.cppreference.com/w/cpp/string/basic_string/getline to parse the whole input and then split it on space according to your needs.
|
72,158,325 | 72,158,472 | Why undeclared identifier error occurres while I'm using objet in class's function? | I've been self teaching CPP OOP and this error occurred:
Error C2065 'carObj1': undeclared identifier
And since I'm self teaching I tried to search on Internet but nothing found!
Can anyone help me with this?
#include <iostream>
#include <string>
using namespace std;
class car {
public:
string brand;
... | The problem is that you're trying to access the fields brand, model and year on an object named carObj1 which isn't there in the context of the member function car::enterObj.
To solve this you can either remove the name carObj1 so that the implicit this pointer can be used or you can explicitly use the this pointer as... |
72,158,419 | 72,412,705 | Generate preprocesed file ( .i ) in code blocks | I am following The Cherno C++ series and in this video he is talking about generating .i files. I am an Ubuntu [20.04] user and am making my projects on Code::Blocks. Does any one know how to generate .i files in Code::Blocks?
| actually you can't directly genrate a preprocessor file in Code::Blocks
as far as my knowledge go. Because I am also following the same series and I also had this problem { i am also using C::b }, so what you can do is in ubuntu terminal go to that file location by using cd command and then use
gcc -E FileName.c -o Fil... |
72,159,100 | 72,164,050 | how is std::is_function implemented | Per CPP reference, std::is_function can be implemented as follows. Can someone explain why this works as it seemingly does not directly address callables?
template<class T>
struct is_function : std::integral_constant<
bool,
!std::is_const<const T>::value && !std::is_reference<T>::value
> {};
| It exploits this sentence from https://eel.is/c++draft/basic.type.qualifier#1
A function or reference type is always cv-unqualified.
So, given a type T, it tries to make a const T. If the result is not a const-qualified type, then T must be a function or reference type. Then it eliminates reference types, and done.
... |
72,159,106 | 72,161,238 | Undo-Redo functionality using Command-Pattern in Qt for FitInView feature | I have QGraphicsView which contains some QGraphicsItem. This view has some feature like zoom-in, zoom-out, fitIn, Undo-Redo.
My fitIn feature is not working in Undo-Redo functionality.
( To implement Undo-Redo I have used Command-Pattern in Qt. )
myCommand.h
class myCommand: public QUndoCommand
{
public:
myCommand(... | Based on the many question you posted on the Qt's Undo Framework, it seems to me you are missing an essential part of the Command pattern:
The Command pattern is based on the idea that all editing in an
application is done by creating instances of command objects. Command
objects apply changes to the document and are ... |
72,159,168 | 72,161,798 | Pass and Return 'Reference to a Pointer' for Binary Search Tree Insertion in C++ | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), l... | If you change find to TreeNode*& find(TreeNode* root, int& val) then look at the first line of the function:
if (root == nullptr) return root;
This would return a reference to a local variable. Changing it in insertIntoBST is undefined behavior and will not change the root variable inside insertIntoBST.
Go through... |
72,159,175 | 72,159,259 | Proper syntax for defining a unique_ptr array of class objects with a constructor | I want an array of class objects with unique_ptr:
std::unique_ptr<MyClass[]> arr(new MyClass[n]);
MyClass has no default constructor (and in my case is not supposed to have), so I have to put it explicitly here. I cannot find out how to do it so it is syntactically correct. What is the correct way to write a unique_pt... | The answer below is based on a previous version of the question, in which the array size appeared to be a compile-time constant. If the size of the created array is not a compile-time constant, then it is impossible to pass arguments to the constructors of the elements. In that case std::vector is probably a better cho... |
72,159,216 | 72,162,717 | Embed Python in C++ (using CMake) | I'm trying to run a python script in c++. For example:
// main.cpp
#include <python3.10/Python.h>
int main(int argc, char* argv[])
{
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print('Today is',ctime(time()))\n");
Py_Finalize();
return 0;
}
And I have suc... | Prefer imported targets (https://cmake.org/cmake/help/latest/module/FindPython.html#imported-targets):
cmake_minimum_required(VERSION 3.18)
project(task_01)
find_package(Python REQUIRED Development)
add_executable(task_01 main.cpp Utility.cpp Sort.cpp)
target_link_libraries(task_01 PRIVATE Python::Python)
|
72,159,583 | 72,159,652 | Iterate through vector<uchar> and count occurrence of values | How to iterate through a std::vector<uchar> and count the occurrence of each value?
I'm still fairly new to C++ and don't really know the best approaches
My guess would be to iterate through the vector and register each occurrence in a new multidimensional vector
std::vector<uchar<int>> unique;
for(const auto& sample :... | We use an unordered_map as a counter by key.
#include <algorithm>
#include <cstdio>
#include <iterator>
#include <unordered_map>
#include <vector>
int main(int argc, char const *argv[]) {
auto samples = // or from user input
std::vector<int>{1, 1, 1, 4, 5, 6, 7, 8, 9, 10,
4, 5, 6, 1, 1... |
72,159,909 | 72,160,084 | How to make python faster? | I'm working on a python project which is required to do a lot of tasks in the shortest amount of time.
Done some tests, and a print("Hello World!") takes about 0.7 seconds to run with python.
In c++, cout<<"Hello World!"; takes about 0.003 seconds, a huge difference compared to python.
What approach should I take to mi... | This doesn't really answer the question but shows (proves?) that there must be something wrong with OP's Python runtime setup / environment
import time
start = time.perf_counter()
print('Hello world!')
end = time.perf_counter()
print(f'Duration={end-start:6f}s')
Output:
Duration=0.000018s
|
72,160,076 | 72,160,258 | decouple member variables of a struct in variadic function accordingly | I have posted a question before, unpack variadic arguments and pass it's elements accordingly. However, it didn't quite address my problem as I am not asking it precisely. Hence I would like to rephrase and explain my problem in detail. Thanks in advance!
suppose I got a struct Outcome that take a two parameter functio... | template<class... COORDs>
Outcome get_out_from_coords() {
return std::apply(
[](int x, int y, auto... args){ return cal_out(cal_out(x, y), args...); },
std::tuple_cat(std::make_tuple(COORDs::valueX, COORDs::valueY)...)
);
}
This just concatenates all of the valueX/valueY pairs and calls cal_out with these ... |
72,160,310 | 72,160,438 | How to generate an string iterating each character from array list c++ | i want to generate an string of 64 characters from my char list but after each string generated it will iterate the first digit of the string to the next one and so on, after that will check wish is the result of the sha256 function for each string, for example i have the following char list char hex_numbers[16] = {'0'... | This problem is similar to finding the k-th number in X-ary
#include <algorithm>
#include <cstdio>
#include <iterator>
#include <unordered_map>
#include <vector>
int main(int argc, char const *argv[]) {
const char alphabet[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b'... |
72,160,446 | 72,160,620 | What is the signature of a function that returns another function of the same type? | With a something like this:
bool exit = false;
int main() {
auto & fun = init_function;
while(!exit) {
fun = fun();
}
}
I know I can make it work by casting void* into the right function pointer, but it would be better to know the actual function type.
I'm searching for the declaration syntax of i... | There is no such signature. But the premise of such a state machine is not an impossible one, if we apply the fundamental theorem of software engineering: everything can be solved with a layer of indirection.
For instance, we can declare functions returning incomplete types. And so can declare a function type for a fun... |
72,160,663 | 72,161,488 | Minesweeper algorithm in C++[KOI 2020] | I'm preparing KOI 2022, so, I'm solving KOI 2021, 2020 problems. KOI 2020 contest 1 1st period problem 5(See problem 5 in here)
I want to make <vector<vector<int>> minesweeper(vector<vector<int>> &v) function that works on 5*5 minesweeper.
argument
vector<vector<int>> &v
Numbers in minesweeper that converted to vector.... | There two some simple rules to solving Minesweeper:
If a field sees all it's mines then all blank fields don't have mines and can be uncovered.
If a field has as many blank fields as it is missing mines then they all contain mines.
Keep applying those rules over and over till nothing changes.
Now it gets complex be... |
72,160,678 | 72,160,751 | How to pass member function as a parameter | I'm trying to create a dynamic spell system for a game I'm developing: spells should consist of an archetype, e.g. area of effect and an effect, e.g. heal.
I have following (simplified) code:
class SpellEffect {
public:
virtual void heal(int magnitude);
}
class SpellArchetype {
public:
virtual void applyToArea... | The correct syntax would be as shown below. Note that you can also use std::function.
class SpellEffect {
public:
virtual void heal(int magnitude);
};
class SpellArchetype {
public:
//-------------------------------------------vvvvvvvvvvvvvvvvvvvvvvvvvvvvvv---->func is a pointer to a member function of class Spell... |
72,160,747 | 72,161,017 | How to get the second last element of a list in C++ | i just started programing in C++, and have a little bit of experience in C, but in this program was trying to use the C++ libraries that i am not familiar to at all.
The objective of the program is simple, i have a linked list and i need to get the second to last element of the list. What i did was reversing the list, ... |
i was trying to get the new second element of the list, using std::next.
You are not getting the new second element of the list, what you are trying to get is the next new address of the list, since what you are passing is the pointer, the address of the list, not the iterator:
list *getNextXValue(list *Head, int x)
... |
72,160,831 | 72,161,270 | Convert size in bytes to unsigned integral type | I am developing a library that needs to auto deduce the type of size (in bytes).
How to convert size (in bytes) to unsigned integral type?
The type deduced must be big enough to store data in the size, but that does not mean to use uint64_t in every case.
C++20 or below can be used.
To be clearer, I want to deduce a ty... | Immediately invoked lambda might help. You can also use std::conditional_t.
template<std::size_t N>
using magic = decltype([] {
if constexpr (N <= 1)
return std::uint8_t{};
else if constexpr (N <= 2)
return std::uint16_t{};
else if constexpr (N <= 4)
return std::uint32_t{};
else {
static_asser... |
72,160,937 | 72,161,276 | How can I place multiple QToolButton one after the other, instead of being one below the other | I am working on a QT project that makes it possible to view and edit table views from a given file.
For the buttons in the GUI I'm using QToolButton, but when more than one button is created, they are placed one below the other, whereas I would like them all to be shown one after the other on the same row. Here is the ... | Put them in a horizontal layout or a widget with horizontal layout. You can also use a grid layout for your window and make the table span all columns.
There is also the QButtonBox that has a number of default buttons with default icons that might mesh better with the users theme.
|
72,161,009 | 72,176,190 | spdlog: not configuring the logger correctly using same sink | The following code :
#include "spdlog/spdlog.h"
#include "spdlog/sinks/stdout_color_sinks.h"
int main() {
auto stdout_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
auto a = std::make_shared<spdlog::logger>("a", stdout_sink);
auto b = std::make_shared<spdlog::logger>("b", stdout_sink);
a->set... |
That would work yes. Problem is when you want to extend this to log files. Then, you end up having two log files
The answer is you can't, directly.
set_formatter is just a wrapper of set_formatter(pattern_formatter{}). In spdlog, a formatter is stored in a sink rather than a logger.
Just thought of a workaround if y... |
72,161,048 | 72,167,870 | MFC Draw Stuff Outside OnPaint in a Dialog-based App | I'm currently trying to draw something outside OnPaint function. I know there are many duplicate questions on the internet, however, I failed to get any of them to work. This is entirely because of my lack of understanding of MFC.
What works inside OnPaint:
CDC* pDC = GetDC();
HDC hDC = pDC->GetSafeHdc();
CRect lDispla... | For example:
void CMFCApplicationDlg::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
HDC hdc = ::GetDC(m_hWnd);
Ellipse(hdc, point.x - 10, point.y - 10, point.x + 10, point.y + 10);
::ReleaseDC(m_hWnd, hdc);
CDialogEx::OnLButtonDown(nFlags,... |
72,161,247 | 72,161,714 | shared memory c++ cross platform | I'm coding in C++ a program that works as a socket between other programs in different languages (C#, Python till now). This socket reads data from the USB-port, do some stuff and stream it to the other programs.
My Idea: each program asks over a port-massage to be part of the stream. As response this program gets a po... |
Is this possible? shared memory over different programing-languages?
Yes. Memory is memory, so a shared-memory region created by language A can be accessed by a program written in language B.
and can I just passe the pointer to the shared memory to the other program?
It's not quite that simple; the other program ... |
72,161,324 | 72,161,370 | replacing new with smart pointers in this example | In the following I would like to replace usage of "new" with smart pointers. However, so far my attempts were not successfully. The commented lines are what I tried to change for smart pointers.
int main(){
int n, val;
cin>>n;
Person* per[n];
// shared_ptr<Person> per[n];
f... | You're not allocating the actual object, so use std::make_shared :
per[i] = std::make_shared<Student>();
Although make_shared is preferred, you can write:
per[i] = shared_ptr<Professor>(new Professor);
|
72,161,498 | 72,170,323 | time complexity of (A[i]^x)>(A[i]&x) | 'Is it possible to further optimize the time complexity this piece of calculation "(y^x)>(y&x)" in c++?(you are allowed to change the Boolean operation into other forms, for example this can also be written as log2(y)!=log2(x) and this gives the same Boolean output but this has a higher time complexity with c++ compile... | (y^x)>(y&x) is equivalent to nlz(y) != nlz(x) where nlz is a function that returns the number of leading zeroes of its input.
Therefore in order to count how often (A[i]^x)>(A[i]&x) is true for items in the array A, we could make a small array N where N[j] is the number of elements with nlz(A[i]) == j in array A. Then ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.