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 |
|---|---|---|---|---|
73,791,394 | 73,791,549 | Cannot initialize a std::vector of objects when class contains std::thread | I'm running into an error with a more complicated class structure which I have boiled down to the below simple test case. The actual intent is to use a ctor with parameters, but the error occurs even when explicitly calling the empty ctor.
class TestFun{
public:
explicit TestFun(const std::function<void()>& fun) :... | As stated in documentation on std::vector constructor on this line:
std::vector<Test> tests(10); // This compiles
you use
Constructs the container with count default-inserted instances of T. No copies are made.
on another side on this line:
std::vector<Test> tests(10, Test()); // This gives an error
y... |
73,791,436 | 73,829,034 | Are concepts able to check private non-static data members? | I made a concept that checks the type of a data member:
#include <concepts>
#include <iostream>
template < typename DataType >
struct StaticA
{
private:
static DataType value;
};
template < typename DataType >
struct NonStaticA
{
private:
DataType value;
};
template < typename DataType >
struct B
{
DataT... | It seems that this issue was indeed a bug: https://developercommunity.visualstudio.com/t/C-concepts-are-able-to-access-private-/10155281
The fix shall be released in the future.
|
73,791,478 | 73,793,388 | Cast pointer to union to known base class of unknown active member | Suppose I have a union and I know the active member derives from some (non-standard layout) base class, but I don't know which specific member is active. Is it legal to cast a pointer to that union, via void *, to a pointer to the base class, then use that base pointer?
For example, is this (which does compile with g++... | The union object that this points to is pointer-interconvertible with the active derived_1 or derived_2, but it is not pointer-interconvertible with the base class subobject of either. Pointer-interconvertibility between base and derived classes applies only to standard layout classes.
Therefore the cast will not resul... |
73,791,559 | 73,817,231 | window fails to initiate when specifying a custom class name registered with RegisterClass to CreateWindowEx but only the second time I do it | I'm creating a window that's supposed to contain buttons.
When I create the first window (the container) I use a WNDCLASS to specify a WindowProc callback function to lpfnWndProc and it works as intended. When I do it the second time with a window, specifying a callback used to detect when the button is clicked, it doe... | The solution to the problem in the title was solved by the comment by Igor Tandetnik:
ButtonWindowProc returns 0 for all messages it doesn't handle, and doesn't pass them to DefWindowProc. In particular, it returns 0 in response to WM_NCCREATE, which is a signal that the window creation has failed. You probably didn'... |
73,791,938 | 73,792,107 | Why can I not push_back a element into a vector pointer? | My code is the following:
#include <vector>
int main() {
std::vector<int> *vec;
vec->push_back(1);
return 0;
}
This program segfaults, no matter which compiler I try it with. I also tried using a smart pointer, but it also segfaults. I now have two questions:
Why and how can I solve this?
Does having a p... | Pointers are trivial objects, so the result of default-initializing one is that its value is indeterminant. Since that's what you did, your pointer doesn't point to anything. That means trying to access the thing it points to results in undefined behavior.
You need to create an object for your pointer to point to. F... |
73,793,368 | 73,793,398 | What happens to the old one after swapping with an unnamed object in C++ | Consider the statement decltype(s){}.swap(s), where s is a STL class entity. If s is not ::std::array, this gets a nice complexity ( O(constant) ).
But I wonder, where the old one goes? Is it automatically deleted?
I think so, for the old one will never be used again. But I'm not sure about that (if the compiler will t... | The content of s is swapped with the content of the temporary object created by decltype(s){}. Effectively, s will simply become re-initialized with its default content, and the temporary object will destroy the old content when itself is destroyed when it goes out of scope.
And FYI, swap() works with std::array, too.... |
73,793,723 | 73,793,808 | c++11 expanding parameter pack inside of a lambda | I'm trying to assign a lambda to my std::function that contains 1 call to Test for each type specified in the parameter pack, does anyone know how to do this?
template<typename T>
void Test() {
}
template<typename ... Ts>
void Expand() {
std::function<void(void)> func = [Ts] {
for (const auto& p : { T... | template<typename ... Ts>
Ts here represents types. Template parameters are types.
[Ts] {
// ...
}
A lambda's capture captures values, and discrete objects rather than types. There's no such thing as a capture of types.
for (const auto& p : { Ts... })
Range iteration iterates over values in some container. A braced ... |
73,793,851 | 73,794,731 | Why does " error: no match for 'operator<<' " occur when searching for the iterator? | I am looking for the positions of an element using find(); method, but for some reason it conflicts whit the cout<< and I don't understand why.
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, busquedas, num,
vas=0, pet=0;
vector <int> arreglo;
cin>>n;
for(int i = 0; i < n; i++){... | This error means that the << operator is not supported for the iterator type with std::cout. Try doing this if you want to see the distance of the iterator from the beginning of the vector.
std::cout << std::distance(arreglo.begin(), it) << std::endl;
Or this if you want the value in the array the iterator points to (... |
73,795,409 | 73,796,269 | Is C++Builder (10.4 and above) a C++17 compliant compiler | I've been using previous version of C++ Builder and I decided to upgrade to 10.4 before 11.2 as I need C++17 compatibility. I'm already facing an issue with "scoped_lock" (C++ Builder 10.4 community edition => scoped_lock are missing (at least seems to be a path mess)) but now even that example from ccp_reference does ... | std::variant is broken in C++ Builder for some types. However, the compiler is intended to support C++17, and many C++17 features work. You could use boost::variant instead.
There is a workaround in comments:
Issue: The assignment and constructor of Dinkumware std::variant checks that the value is assignable to exactl... |
73,796,007 | 73,796,584 | Use of overloaded oeprator[] is ambiguous | Simplified code as below:
#include <string>
#include <string_view>
struct object{
operator std::string(){return "";}
}
struct foo{
foo operator[](std::string_view s){
return foo{};
}
template <typename T>
operator T(){
return object{};
}
};
int main(){
foo f;
std::string s = f["a"];
}
cla... |
template <typename T>
operator T(){
return object{};
}
I think clang is correct here, since this snippet makes the foo class convertible to any type, and viable template functions are supposed to be instantiated before overload resolution comes into play:
Before overload resolution begins, the functions selecte... |
73,796,018 | 73,797,216 | Capturing shared_ptr in lambda using std::move | In following code std::move in lambda capture list felt unnecessary to me, but compiler does seem to need it.
As there is extra code for copying shared_ptr is generated if I don't use std::move.
Question is, why compiler can't optimise this on its own.
template<typename T>
std::function<void(void)> prepLambdaImpl(std::... | Automatic move only happens in return statement in some specific circumstances, which are not met here.
Last usage doesn't trigger a move instead of a copy.
The as-if rule allows optimization as long than observable behaviour is unchanged. Whereas we know the 2 forms are equivalent, it is not easy to know. Especially m... |
73,796,216 | 73,796,250 | C++ - Class implicitly convertible to size_t | I have created a simple class and I would like it to be convertible to size_t. But I don't understand how to do it.
class MyClass {
private:
std::size_t size;
public:
MyClass();
~Myclass();
};
I tried this got some errors :
Error: namespace std has no member class size_t
Thanks for your help in advance.
| std::size_t can be found in multiple headers, for example <cstddef>
To enable the conversion, you can provide a operator std::size_t member function :
#include <cstddef>
class MyClass {
private:
std::size_t size;
public:
operator std::size_t() const {
return this->size;
}
//...
};
the compiler... |
73,797,112 | 73,797,672 | Need help understanding why this invalid C++ code compiles successfully | The following code compile correctly for me in some environments (e.g. on compiler explorer with GCC 9.3.0) and complains in others (CentOS 7.9.2009 (Core), GCC 9.3.1).
#include <iostream>
#include <string>
using namespace std;
int main() {
std::string name="aakash";
name.erase(name.begin()+2, name.cend());
... | Since C++11, both arguments to the two-iterator overload of std::string::erase() are const_iterator. See form #3 on this cppreference page (the one you linked in your question).
Further, the C++11 Standard requires that a conatiner's iterator types are convertible to the equivalent const_iterator.
From this Draft C++11... |
73,797,480 | 73,811,522 | How do I avoid LNK2005 and LNK1169 errors while compiling TetGen in my project? | I am trying to compile TetGen and use the code below to tetrahedralize a .ply file although I am getting these two linker errors:
LNK2005 main already defined in tetgen.obj
LNK1169 one or more multiply defined symbols found
The files that are includes in my project solution are "tetgen.h", "predicates.cxx", and "tetgen... | For anyone who may have this issue in the future with TetGen: The problem was that the TETGEN_LIBRARY flag needed to be defined in tetgen.h. I knew this, but every time I defined the flag, it would cause memory errors without fail. So, I kept TETGEN_LIBRARY undefined to avoid the memory error. Turns out, with TETGEN_LI... |
73,797,579 | 73,797,841 | Question about brace-initialization of data member array in constructor? | In the following class:
struct S {
S() : B{} {}
const uint8_t B[32];
};
Are all 32 bytes of the B array guaranteed to be initialized to zero by the default constructor?
Is there any way to create an object of type S such that any element of the B array is not zero? (without const casting or reinterpretting m... |
Are all 32 bytes of the B array guaranteed to be initialized to zero by the default constructor?
Yes, B is value-initialized which for an array means each member is value-initialized - primitive types are value-initialized to 0.
Is there any way to create an object of type S such that any element of the B array is n... |
73,797,710 | 73,797,732 | C++ string::rfind time complexicity | What is time complexity of string::rfind method in c++?
From what I understood, rfind is reversing the string and then doing string::find. Am I correct? Then it should be O(n)
| No, you are not correct. rfind searches from the back of the string without reversing the string. The complexity is the same as for a forward find.
I haven't found anything in the standard requiring this, but any search algorithm that you can use for find (like a naive search or a Boyer-Moore / Boyer-Moore-Horspool sea... |
73,797,874 | 73,798,063 | "typedef iterator<const value_type> const_iterator;" results in: "error: expected member name or ';' after declaration specifiers" | I want to create a vector from Zero and this requires creating an iterator class as well, but I have this problem when I want to set a const iterator
That's my vector
template < class T, class Alloc = std::allocator<T> > class vector {
public:
typedef T ... | You're trying to redefine the template to a concrete type:
typedef iterator<value_type> iterator;
I suggest renaming the class template to something else, like iterator_impl:
template <class T> class iterator_impl {
protected:
T* m_ptr;
public:
typedef T ... |
73,798,236 | 73,801,399 | Explicit template instantiation vs concept constraints | Let's suppose that I've either a function or a class template that should work only for certains types, e.g. std::wstring and std::string.
I know that concepts can be used to put a constraint on a template so I would use something like this:
template <typename T>
concept StringLike = std::convertible_to<T, std::wstring... | You have two things here and they are not interchangeable.
Concepts are used to constrain template arguments. This is what you should use if you want to restrict the type arguments your A class should be instantiated with.
Explicit template instantiation, that you show in the second example, is something different. Rem... |
73,798,572 | 73,798,684 | How to pass a virtual function as an argument in C++? | I am trying to write this code below:
// Type your code here, or load an example.
#include <iostream>
class A
{
public:
virtual void virFunc1(int a) = 0;
virtual void virFunc2(int a) = 0;
void func1(int a)
{
onTempFunc(this->virFunc1, a);
}
void func2(int a)
{
onTempFunc(thi... | The correct syntax for passing virFunc1 and virFunc2 as arguments would be to write &A::virFunc1 and &A::virFunc2 respectively as shown below.
Additionally, for calling/using the passed member function pointer we can use ->* as shown below:
class A
{
public:
virtual void virFunc1(int a) = 0;
virtual void virFun... |
73,799,194 | 73,799,298 | Why the parent's method should be called explicitly with the parent's prefix from the child object? | see please the code:
#include <iostream>
using namespace std;
class A{
public:
A() = default;
virtual void foo() = 0;
bool foo(int x)
{
cout<<"A::foo(int x)\n";
return true;
}
bool func(int x)
{
cout<<"A::func(int x)\n";
return true;
}
... | It is called 'name hiding'.
You have a function called foo without parameters in your subclass. The compiler will hide any other function with the same name from the superclass, unless you declare it with the using A::foo; directive in the child class.
To my knowledge, this is done to avoid confusion of the function ca... |
73,799,750 | 73,800,505 | How create a JSON-file from my data? (with С++, boost json) | I wanted to create a Json-file that will be created from the data received earlier. I don't understand how to work with Json files at all. I want to use the Boost library, because I am using it in another part of this program. I need to create a Json-file with a specific structure which I have attached below.
I need to... | Despite comments suggesting to use a different library, which they could, I think @Nindzzya wanted to specifically use the boost library.
Using the boost library from How to use boost::property_tree to load and write JSON:
#include "boost/property_tree/ptree.hpp"
#include "boost/property_tree/json_parser.hpp"
#include ... |
73,800,644 | 73,861,012 | Algorithm intuition: transform but with possibly more output items than input items? | I want to escape a string. That is, I want to copy characters, but where the input has " or \, I want to prepend \ on the output. I can write that easily enough, even very generically:
//! Given a range of code units (e.g., bytes in utf-8), transform them to an output range.
//! If a code unit needs escaping (per the g... | After asking on Twitter, I got some very satisfying answers, although it involves the M-word (monad).
First, @atorstling
suggests that this is flatMap in JavaScript: https://twitter.com/atorstling/status/1574097704098988033?s=20&t=jzS503R6fMOqCajReygzJg https://dmitripavlutin.com/javascript-array-flatmap/
So translatin... |
73,800,949 | 73,801,133 | Why does this string concatenation loop not work? | I want to use the formatting capabilites of the cstring library together with std::string's ability to dynamically allocate. Consider the following debug-log (I wouldn't do it in production code this way but for debugs cstring is convenient):
Demo
#include <cstdio>
#include <string>
#include <array>
#include <cstdint>
... | Basically you have resized start more then it is needed. std::string is exception and actual buffer size is one item more then size() returns to contain terminating zero.
So start contains "array (size=3);\0" just before entering loop.
Now after each update (loop iteration) content is added after this extra \0.
So when... |
73,801,029 | 73,801,077 | fstream std::ios::binary printing in ASCII ? is it working correctly? | i was trying to write some data to a file in binary, the following is the minimal reproducible example of the problem, i am trying to print two unsigned 64 bit integers to a binary file and read one of them again ... problem is that the data is not printed or read in binary.
#inclue <fstream>
#include <iostream>
#inclu... | The stream input and output operators >> and << are text-based. They will write the output as text, and read the input as text. Even for binary files.
To write raw binary data use the write function. And to read the raw binary data use read:
s.write(reinterpret_cast<char const*>(&a), sizeof a);
s.write(reinterpret_cast... |
73,801,349 | 73,801,585 | Is there any way to make this CRTP work with inheritance? | Pardon the very vague question but I am struggling with even finding the proper words to describe what I'm trying to do. Basically, when I write a class I like having:
class A
{
public:
using uptr = std::unique_ptr<A>;
using sptr = std::shared_ptr<A>;
using wptr = std::weak_ptr<A>;
};
So I can use A::uptr... | When you derive B from both Ptrs<B> and A you're introducing two sets of identical type aliases. Therefore, the compiler is not able to figure out which one you want.
The use of the CRTP cannot help you here. However, it's opposite pattern, mixins, may help you. Mixins are small classes that are intended to add common ... |
73,801,509 | 73,802,053 | How to properly delete QWidget from layout QT? | I know, that I can delete QWidget from QLayout so:
QLayoutItem*item = wlay->takeAt(0);
wlay->removeItem(item);
delete item;
delete w;
However, without deleting QWidget(delete w), the widget will be on the screen. However, I cant delete the widget, so the widget will be on the screen. H... | It seems the function you're looking for is QWidget::hide().
Moreover, once you've called QLayout::takeAt(), you don't have to call QLayout::removeItem() afterwards since the former already removes the item as mentioned in the documentation.
You can see QLayout::takeAt() as a shorthand for QLayout::itemAt() + QLayout:... |
73,801,523 | 73,803,399 | boost asio, yield an awaitable function | I have several time-consuming computation jobs, which shall not block the executing thread while executing.
I also want to use c++20 coroutines + asio::awaitable's to accomplish this.
The asio::io_context's thread for example should still be responsive.
Therefore, I want my Job to suspend/yield after some time, and the... | You can use timers, they are lightweight.
E.g.
struct CoroEvent {
using C = asio::steady_timer::clock_type;
using T = C::time_point;
void send() { _timer.expires_at(T::min()); }
auto async_wait(auto&& token) {
return _timer.async_wait(std::forward<decltype(token)>(token));
}
asio::stea... |
73,801,767 | 73,802,198 | std::any object cast to reference type, change its value, but original object is not changed | I was trying to see if std::any object can cast to reference type, and see whether changing the casted reference means to change original object. As below:
struct My {
int m_i;
My() : m_i(1) {}
My(const My& _) : m_i(2) {}
My(My&& m) : m_i(3) {};
My& operator = (const My& _) { m_i = 4; return *this; ... | Look at your example without any any:
#include <any>
#include <iostream>
using std::cout;
using std::endl;
using std::any;
using std::any_cast;
struct My {
int m_i;
My() : m_i(1) {}
My(const My& _) : m_i(2) {}
My(My&& m) : m_i(3) {};
My& operator = (const My& _) { m_i = 4; return *this; }
My& o... |
73,802,126 | 73,802,777 | Solving an uncomplete nonlinear system of equations with Z3 | I am trying to make a solver for nonlinear system of equations using the Z3 library in c++.
It will exists with multiple equations and variables. Depending on previous steps in my software, it could be that some variables are unknown.
When too many variables are unknown and the system does not have a single solution, I... | (/ 78.0 23.0) simply means 78/23, i.e., approx. 3.39. Z3 prints real-values in this format since they are infinitely precise; as the fraction might require an unbounded number of digits in general.
Your question regarding "proper way to detect is an implicit function" is a bit ambiguous. I assume what you mean is if th... |
73,802,668 | 73,803,127 | How to check if a `std::vector<bool>` is true at multiple indexes simultaneously? | I have a std::vector<bool> of size N and a std::vector<std::size_t> of variable size containing indexes in [0, N). What is an idiomatic way to check if the first vector is true at all indexes given by the second vector?
My possibly naive solution is:
auto all_true(
std::vector<bool> const& bools, std::vector<std::s... | An idiomatic (though not necessarily efficient) way to do this would be to use the std::all_of STL function, using a predicate that simply returns the value of the Boolean vector at the index specified by each value in the size_t vector.
Here's an outline/demo:
#include <iostream>
#include <vector>
#include <algorithm>... |
73,802,728 | 73,805,361 | basic mathematics c++ code for moving left or moving right for same if condition (k*x<b*k); k =1 or -1 | Below is a simple program.
int main()
{
int x, b = 3; //size_t x; size_t b = 3;
char const *c = "moving_left"; // "moving_right"
int k, border;
if (!strcmp(c,"moving_left"))
{
k = 1; // moving left
border = 0;
x = 5;
}
else
{
k=-1; ... | It is not completely clear why you want to use unsigneds and why you want so much to keep the condition (k*x<b*k) rather than something along the line of if ( (moving_left && x<b) || (!moving_left && b<x).
Anyhow if you want to use unsignds and you want to use a single condition for both cases, then you can add a level... |
73,802,743 | 73,803,043 | How can I use dynamic_cast to get objects with a user-specified type? | If there is a method, which aims to put objects with specific type into another list, how can I use a user-defined parameter in the dynamic_cast? I know, that I can not use the std::string parameter directly in dynamic_cast, but is there a better solution?
std::list<Car*> GetCarsOfType(std::string type)
{
s... | You could keep a central repository of the mapping between the named car type and the actual type if you wish. It could then be used to do the dynamic_cast test for you.
Example:
#include <algorithm>
#include <unordered_map>
std::list<Car*> GetCarsOfType(std::string type) {
// map between the named type and the dy... |
73,803,277 | 73,803,561 | Is it better for performance to use boost::reversed than accessing back to front? | Is it better for performance to use boost::adaptors::reverse to access elements in a vector in reversed order instead of the usual v[i-1]?
I.E.:
std::vector<int> v {1,2,3,4};
for (const auto& el : boost::adaptors::reverse(v))
print(el);
vs
std::vector<int> v {1,2,3,4};
for (size_t i = v.size(); i > 0; --i)
print(v... |
reverse has to reverse the vector
No, it's only an adaptor, it doesn't do anything to the vector. What it does is provide begin as the vector's rbegin, and end as the vector's rend. So these two pieces of code are more or less equivalent.
|
73,803,363 | 73,803,852 | C++ - Modify member function if argument (function) is given | I am creating a class which takes as input arguments either 1 or 2 functions.
My goal is that if only one function func is given then the member function dfunc is calculated using num_dfunc (which is the numerical derivative of func and is hardcoded inside the class). If two functions are given func and analytical_dfun... | I would make num_dfunc either a static member function, or probably even better a free function, that has nothing to do with MyClass. I would modify it, such that it also takes the zeroth-order function as well as the dimension as an input.
If your constructor is called with just one argument, you can create the second... |
73,803,533 | 73,805,024 | printf all characters in a string using HEX i.e. printf("%X", string.c_str()) | I'm on an embedded Linux platform which uses C++ but also printf for logging.
I receive data in string type - "\241\242" - but they're unprintable characters.
On the sender side, I type in a hex number in string format i.e. "A1A2" but the sender encodes it as the number 0xA1A2 so on the receiver, I cannot use printf("... |
Is there a way to use ONE printf("%X") to print all the characters in the string as hex?
No.
Is there a way
You can write your own printf with your own specifier that will do whatever you want. You might be interested in printk used in linux kernel for inspiration, I think that would be %*pEn or %*ph or %*phN.
On g... |
73,803,717 | 73,820,786 | How do I determine which GStreamer plugin decodebin3 selected? | I need to determine which decoder plugin decodebin3 has selected.
I've found that I can't always link it to certain downstream elements after it spawns the source pad. But if I "disable" (change the rank) of a given unusable plugin, I can make my pipeline linkable/functional. I want to dynamically switch the selectio... | I figured it out myself. Basically, the element created by this plugin is a "bin" (which is why it's called decodeBIN3!), and therefore one can use gst_bin_iterate_elements to iterate through the child elements within it. Then, it's possible to get the factory an element was produced by, and from there check the type... |
73,803,967 | 73,805,733 | zmq::message_t assign a string | I am trying to familiarize myself with ZeroMQ by creating a simple socket communication betwenn a publisher and a subscriber to send a test message. However, I can't find the information I want on how to put a string inside a zmq::message_t type message. Indications pointed to the use of "std::memcpy(message.data(), ms... | There is a constructor for zmq::message_t that has the signature (docs)
message_t(const void *data_, size_t size)
so you could use this like
zmq::message_t message(static_cast<void*>(ms.data()), ms.size());
|
73,804,080 | 73,804,283 | C++ partial template function specialization | I have a primary template function:
template <typename T, int U>
void print() {
std::cout << "int is " << U << std::endl;
}
How to make a partial specialization for function print, so that U is inferred based on a type of T?
For example:
template <typename T>
void print<T, 1>(); // If T is float
template <typena... | You can't partially-specialize functions, and specializations are selected after all of the template's arguments are known, so you can't do this with partial specialization.
What you can do is have a separate function template that has a single argument that simply calls through to the underlying function template:
tem... |
73,804,659 | 73,804,744 | How to retrieve an enum index value based on char array? in C++ (cpp) | Disclaimer: New to programming, learning on the fly. This is my first post and apologize if the question is not written clearly.
I am trying to go through a tutorial on building a chess engine, but it is written in C and I am attempting to convert it to C++ code. The idea of the code is to enter a char and retrieve the... | You can write a function to return specific enum for you char input .
enum Piece {P, N, B, R, Q, K, p, n, b, r, q, k};
Piece charToPiece(char ch)
{
switch (ch) {
case 'P':
return P;
case 'N':
return N;
case 'B':
return B;
case 'R':
ret... |
73,804,726 | 73,810,117 | Getting the PowerShell::Create.AddScript.Invoke return value in c++ | With reference to Would like to run PowerShell code from inside a C++ program, I have created a program to execute the PowerShell script in C++ using System.Management.Automation.dll. But, I wasn't able to retrieve the return data from the Invoke() function. I can create individual PSObject, but I couldn't create the c... | You need to either import the proper namespaces, like this:
#include <Windows.h>
#include <vcclr.h>
#include <iostream>
#include <vector>
#using <mscorlib.dll>
#using <System.dll>
#using <System.Management.Automation.dll>
using namespace std;
using namespace System;
using namespace System::Collections::ObjectModel; /... |
73,804,774 | 73,949,897 | boost::asio async operations handler not called | i would like to use a very similar pattern to the boost::asio example here, so i first ran the example on windows 10 running boost 1.71.0, and it executed properly. Dropped the unchanged client code in my project with main() replaced by:
[EDIT]
boost::asio::io_context io_context;
auto c = std::make_unique<test_async::t... | Yep, pilot error. The code worked, but it was called from a member function in a templated class. Put the code in the header file and it works. Feeling a bit silly right about now.
Thanks @sehe for a good answer
|
73,804,801 | 73,805,487 | Implement a PID control in C++ for a motor with absolute encoder | Sorry if my question is too stupid, but I can't figure out how to solve my problem.
I have a motor with a gearbox and I also have an absolute encoder mounted on the gearbox shaft. I need to make the output shaft rotate in a range from -90 to +90 and it is centered in 0°.
Now, when the shaft is in 0°, then the encoder o... | Here you go:
unsigned angle2pid(double angle_in_degrees)
{
return 1010 - angle_in_degrees * 55 / 45;
}
void move_motor_to_angle(int motor_id, double angle)
{
static const int CLOSE_ENOUGH = 10;
int currentPosition = get_enc(motor_id);
int desiredPosition = angle2pid(angle);
// IF WE ARE CLOSE ENO... |
73,805,510 | 73,805,591 | Does new int[] return the address of the first element in the array or the address of the entire array? | int *a = new int[16];
How do I access the array afterwards?
Does a hold the address of the entire array or just the first element in the array?
Basically, I have this code,
struct student {
string name;
int age;
};
int num_students = get_number_of_students();
struct student *students = new student[num_students]... | a is simply a pointer to an int. It points to the beginning of the block of memory you have allocated. It does not carry any information about the size of the array.
As advised in comments, best practice in C++ is to use a std::vector for this, letting it handle the memory allocation (and importantly de-allocation) and... |
73,805,807 | 73,807,557 | How to use the QGraphicsItem::setPos() function | I can't figure out how the setPos() function of the QGraphicsItem class works.
My Rect class has no parent, so its origin is relative to the scene.
I try to put the rectangle back at (0, 0) after it is moved with the mouse but it is placed in a different place depending on where I had moved it.
I suppose that means tha... | When you create a QGraphicsView you initially accept the default settings. A standard setting is, for example, that it is horizontally centered.
Another factor is that the default area size is probably up to the maximum size.
what you can do set a custom size for the scene. You do that with graphicsView->setSceneRect(... |
73,805,831 | 73,807,099 | Does DirectX11 Have Native Support for Rendering to a Video File? | I'm working on a project that needs to write several minutes of DX11 swapchain output to a video file (of any format). I've found lots of resources for writing a completed frame to a texture file with DX11, but the only thing I found relating to a video render output is using FFMPEG to stream the rendered frame, which ... | Found the answer thanks to a friend offline and Simon Mourier's reply! Check out this guide for a nice tutorial on using the Media Foundation API and the Media Sink to encode a data buffer to a video file:
https://learn.microsoft.com/en-us/windows/win32/medfound/tutorial--using-the-sink-writer-to-encode-video
Other doc... |
73,805,926 | 73,806,053 | How to change textout() when it's already drawn? | I'm trying to move static TCHAR greeting[] = _T("123"); by using arrows, but it doesn't move at all. MessageBox is used as a confirmation of getting keyboard input.
void move(HWND hWnd, WPARAM wParam, LPARAM lParam, unsigned int *x, unsigned int * y) {
RECT rt;
if (wParam == VK_LEFT) {
GetClientRect(hWn... | The x and y variables you are using to draw the text with are local to WndProc and are always reset to the initial values whenever a new message is received. You need to move their declarations outside of WndProc() (or at least make them static) so that their values can persist between messages. You can then update t... |
73,806,073 | 73,806,120 | Using "CreateProcess()" gives error C2664 | I am trying to open an application from my .cpp file. I did some research and found that using CreateProcess() would be the best option. Doing this resulted in the following code:
//Below has the purpose of starting up the server: -----------------------------------------------
LPWSTR command = (LPWSTR)"C:\\Users\... |
cannot convert argument 9 from 'LPSTARTUPINFOA *' to 'LPSTARTUPINFOW'
You are giving the function a pointer to a STARTUPINFOA pointer but the function expects a STARTUPINFOW pointer (which is what LPSTARTUPINFOW is typedefined as).
The correct way is therefore to define si like so:
STARTUPINFOW si{sizeof(STARTUPINFO... |
73,806,642 | 73,806,732 | Converting cv::Mat to Eigen::Matrix gives compilation error from opencv2/core/eigen.hpp file (OpenCV + Eigen) | In my code, I have to convert cv::Mat to Eigen::Matrix so that I can use some of the functionalities of the Eigen library. I believe a straightforward option would be to manually copy+paste each element of cv::Mat into Eigen::Matrix. However, I stumbled upon this question on SO and found out about the cv::cv2eigen func... | Actually, I found the root cause:
As per line 78 & 79 of opencv/modules/core/include/opencv2/core/eigen.hpp on 4.x branch:
@note Using these functions requires the Eigen/Dense or similar header to be included before this header.
So, surprisingly enough, all I had to do was change the #include order
from
#include <ope... |
73,806,740 | 73,806,776 | Parsing a text file with a tab delimiter | I need to parse this text file that has essentially four strings separated by a tab. I've been researching and trying different methods and I can't quite figure out how to do it.
For example, I would need to parse this data:
Sandwiches (tab) Ham sandwich (tab) Classic ham sandwich (tab) Available (newline)
Sandwiches ... | Simple way is
getline(in, a, '\t');
getline(in, b, '\t');
getline(in, c, '\t');
getline(in, d, '\n');
where a, b, c, and d are std::string variables and in is your input stream.
Better would be a little rudimentary error handling
if (getline(in, a, '\t') && getline(in, b, '\t') && getline(in, c, '\t') &&
getline(... |
73,807,728 | 73,807,762 | Get quotient and residue from a division executing just one operation | I need to know how can i get quotient and residue from a division executing just one operation, using python or c++.
| quotient, reminder = divmod(10, 3)
print(quotient, reminder) # 3 1
https://docs.python.org/3/library/functions.html#divmod
|
73,808,479 | 73,834,333 | Can I use C++20 `std::atomic<T>::wait()` or `std::atomic_flag::wait()` in shared memory? | My project involves a plugin, and a GUI for said plugin which is isolated into a separate process. The data I'm sharing may be updated by the GUI, and when it is, it should be processed by the plugin.
To do this, I'm considering putting this in my shared-memory block:
std::atomic_bool event_flag;
// insert mutex...
som... | The C++ standard never specified how C++ code interacts with shared memory and processes, so much of this is implementation-defined.
However, it seems that implementations are not cross-process:
libstdc++ seems to use futexes and/or condition variables with tables. Condition variables are likely not shared across proc... |
73,808,816 | 73,808,848 | Thread-safe stack implementation | "C++ Concurrency in Action second edition" has an example of thread-safe stack implementation, and the following is the code for pop:
template <typename T>
std::shared_ptr<T> threadsafe_stack<T>::pop()
{
std::lock_guard<std::mutex> lock(m);
// `data` is a data member of type `std::stack<T>`
if(data.empty()) thro... | It is assumed that the if the move constructor of T throws an exception it will make sure that the original object remains in its original state.
That is a general exception guarantee that move operations should satisfy, otherwise it is trivially impossible to make any guarantees about exception safety when the move op... |
73,809,029 | 73,809,214 | C++ Major syntax error? (12 Duplicate Symbols for architecture x86_64) | Apologies for my ignorance. I'm relatively new to C++ from another language. I'm making a program to rank poker hands for an assignment and I'm hitting an error that I don't understand but I'm assuming is a major syntax error. Please be nice, I'm trying to learn. This will not build in Xcode. When I try, I get the foll... | There are/were two problems. When you include a file the include directive is effectively replaced with the contents of the named file during the preprocessing phase. This makes one big file containing the contents of the source file and all of the included headers and all of the headers included by other headers that ... |
73,810,105 | 73,818,662 | npm config set msvs_version does not work? (node-gyp) | npm config set msvs_version does not work and I still get msvs_version not set from command line or npm config.
I have all the necessary paths set and I have Visual Studio 2017, 2019 and 2022 installed with the necessary C++ thingys.
Full error:
gyp info using node-gyp@6.1.0
gyp info using node@16.17.0 | win32 | x64
gy... | Fixed
I found the dependency that was causing this error
uninstalled it using npm uninstall <dependency-name>
I redownloaded it as a devDependency with the npm install <dependency-name> -save-dev.
This fixed my issue for now but I do not know if this is a long term solution, I'll probably update this answer when I g... |
73,810,381 | 73,810,443 | Visual Studio - Create exe inclusive of ssh.dll | I have built a simple program in Visual Studio, as per the below.
#define LIBSSH_STATIC 1
#include <libssh/libssh.h>
#include <iostream>
#include <stdlib.h>
int main()
{
std::cout << "Hello World!\n";
ssh_session my_ssh_session;
int verbosity = SSH_LOG_PROTOCOL;
int port = 22;
my_ssh_session ... | A .dll is a Dynamic Link Library; it's not meant to be included in an .exe. There are ways, but they are ugly and difficult.
The "proper" and easier way is to build libssh as a static library instead; this will give you a .lib file that you can add to your .exe easily.
It looks like the downloads you used already conta... |
73,810,611 | 73,814,980 | Modification of objects in constant expression contexts | Consider the following code:
struct S
{
constexpr S(){};
constexpr S(const S &r) { *this = r; };
constexpr S &operator=(const S &) { return *this; };
};
int main()
{
S s1{};
constexpr S s2 = s1; // OK
}
The above program is well-formed but I'm expecting it to be ill-formed, because [expr.const]/(5.16) says:... | As Language Lawyer points out, there are no modifications in your program, however even if the constructor did modify s2, this wouldn't necessarily make the program ill-formed, because:
In any constexpr variable declaration, the full-expression of the initialization shall be a constant expression ([expr.const]).
-- [... |
73,812,404 | 73,813,524 | Confused on which variables should be shared or private in nested OpenMP loop | I have a nested loop and im confused on which variables should be shared or private. I believe that i and j should be private but im confused on whether other variables also need to be shared or privated in my code:
y = p->yMax;
#pragma omp parallel for private(i,j)
for (i = 0; i < p->height; i++) {
... |
Assuming that you do not need the values of i and j after the loops and observing that you reset i and j to zero at the beginning of the loops, I would simply define the i and j within the loop. If so, you don't have to state the behaviour of i and j when entering and exiting the loop (because it is automatically priv... |
73,812,999 | 73,813,564 | There is no byte type in c. But I found byte type in programming | I am trying to learn I2C from this website https://forum.dronebotworkshop.com/arduino/i2c-part-one-tutorial-and-slave-demo-sketch-for-platformio/. In the website section "Slave Demo Sketch" (Arduino), there is one line code that I don't understand.
What is type of Byte? What does the byte inside the brackets mean?
for ... | First of all, type naming is somewhat subjective, though wide consensus exists.
Various sketchy, home-brewed types tend to exist in some libraries. byte, BYTE, U8 and other such non-standard types. These are almost always just some flavour of typedef unsigned char slop;, which is a completely useless typedef.
Some of t... |
73,813,011 | 73,813,110 | train_test_split function in C++ | I would like to create a train_test_split function that splits a matrix (vector of vectors) of data into two other matrices, similar to what sklearn's function does. This is my attempt in doing so:
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <time.h>
#include <vector>
#include <string>
usin... | A function can only return one value. Though look at your function declaration: It is declared to return a vector<vector<float>>, and thats a container of many vector<float>s. Containers can contain many elements (of same type) and custom types can contain many members:
struct train_test_split_result {
vector<ve... |
73,813,309 | 73,813,405 | C++ Only accept a set of types for template parameter pack | To limit a template parameter pack to a certain type, this can be done in the following way:
std::enable_if_t<std::conjunction_v<std::is_same<int32_t, Ts>...>>
send(bool condition, Ts...);
I would actually allow int32_t and std::string and any order.
How can this be expressed?
I had a workaround using a varian... | You are using std::conjunction as a replacement for && on the std::bool_constant level correctly, but then you should in the same way replace || with std::disjunction:
std::enable_if_t<std::conjunction_v<std::disjunction<std::is_same<int32_t, Ts>, std::is_same<std::string, Ts>>...>>
or with C++17 you can use fold expr... |
73,813,349 | 73,813,908 | C++ 2d array using vectors returns a consistent incorrect result on the second query | I'm doing a coding challenge where the aim is to take x arrays and query it y times. Each array is given a size (N) and a list of values and each query wants a specific value (b) from a specific array (a).
The input is given as follows:
X Y
N n n n ...
N n n n ...
a b
a b
Here is all of my code:
#include <vector>
#inc... | The problem has been already described in comments by others: You are storing a pointer to an array on the stack that will be undefined outside the for loop. Just use vectors for both array dimensions and let them handle pointers and memory allocations for you:
#include <iostream>
#include <utility>
#include <vector>
... |
73,813,446 | 73,983,335 | apt.llvm.org clang-15 is not able to compile with C++17 feature std::execution::par | for cross-reference: i asked also at llvm-bug-tracker: https://github.com/llvm/llvm-project/issues/57898
Steps to reproduce:
Ubuntu with clang from apt.llvm.org and with potential pstl backends installed via libtbb2-dev and clang-15-openmp is not able to compile with C++17 feature std::execution::par.
Dockerfile:
FROM ... | The problem is not related to compilers, but to implementations of the C++ standard library.
According to the compiler suppor table as well as libc++ documentation, libc++ is still missing the support for C++17 parallel algorithms and execution policies.
On Godbolt, Clang uses libstdc++ by default. That's why it compil... |
73,813,667 | 73,931,350 | Valgrind detects memory leaks in MKL/LAPACK STEVR function for eigenvalue problems with matrix sizes above a threshold | I am working on software that uses the Intel MKL implementation of LAPACK functions for eigenvalue problems. When I ran Valgrind to check the code for memory leaks it reported errors only when using the function 'STEVR', or more precisely the C-funtion LAPACKE_dstevr. In order to find out if my interface is the problem... | Here is the solution for anyone else with a similar issue.
Try using the latest oneMKL version 2022.2.0 which is now available for download and here is the command with Intel oneAPI compilers
icpx -ggdb3 -I"${MKLROOT}/include" test_dstevr.cpp -L${MKLROOT}/lib/intel64 -lmkl_intel_lp64 -lmkl_intel_thread -lmkl_core -liom... |
73,813,823 | 73,814,440 | Postgres: How to use variables in create functions constructions? | I want to load functions from my shared library. To do this, I specify the path to the library after AS and I want to do it using a variable. But the value is not substituted in this way. How can this be done ?
DO $$
DECLARE
pathToLib text := '/path/to/lib/myPostgresFunctionsLib.so';
BEGIN
C... | You need dynamic SQL:
DO
$$DECLARE
pathToLib text := '/path/to/lib/myPostgresFunctionsLib.so';
BEGIN
EXECUTE format(
$_$CREATE OR REPLACE FUNCTION someFunction() RETURNS text
AS %L, 'someFunction'
LANGUAGE C$_$,
pathToLib
);
END;$... |
73,813,836 | 73,814,409 | return a reference to an array with templated size | I am trying a function's return value to be to a reference to an array whose size is variable (i.e. templated). The code I have is:
const char *strarr[] = { "one", "two", "three" };
template <std::size_t T>
const char* (&GetArr())[T]
{
return strarr;
}
The reason I want to do it this way: it would be convenient i... | There is no template argument deduction from return statements and T cannot be deduced from any function parameter/argument pair.
So you will have to specify the size manually, but that is not a problem, since you need to specify the array that is returned anyway, so that the only possible choice is
const char* (&GetAr... |
73,813,868 | 73,814,104 | printing the bits of float | I know. I know. This question has been answered before, but I have a slightly different and a bit more specific question.
My goal is, as the title suggest, to cout the 32 bits sequence of a float.
And the solution provided in the previous questions is to use a union.
union ufloat{
float f;
uint32_t u;
};
This is... | The constructor of std::bitset you are calling is:
constexpr bitset( unsigned long long val ) noexcept;
When you do bitset<32>(uf.f), you are converting a float to an unsigned long long value. For numeric_limits<float>::max(), that's undefined behavior because it's outside the range of the destination type, and in your... |
73,814,012 | 73,814,508 | Override a base class member in derived class C++ | I can't seem to overwrite the base class member (Painting) value for the derived class FamousPainting.
Things I have tried:
virtual function
creating new setter function in derived class
change derived class constructor signature
I am at a loss of what to do now
#include <iostream>
#include <string>
#include <vector>... | Several issues:
class FamousPainting: public Painting // <- Inherits from Painting
{
private:
Painting painting; // <- Contains a Painting called "painting"
You should pick one of the two. Either FamousPainting IS a Painting and should inherit, or it CONTAINS a Painting and should not inherit. I suspect you... |
73,814,832 | 73,892,602 | Could not initialize my i2c_config_t structure | According to the i2C.h as follows:
/**
* @brief I2C initialization parameters
*/
typedef struct{
i2c_mode_t mode; /*!< I2C mode */
gpio_num_t sda_io_num; /*!< GPIO number for I2C sda signal */
gpio_pullup_t sda_pullup_en; /*!< Internal GPIO pull mode for I2C sda signal*/
gpio_num_t scl_... | @hcheung gave the right answer about the order of the members.
But regarding the anonymous union, his solution does not work.
I finally came up with the solution:
i2c_config_t conf = {
.mode = I2C_MODE_MASTER,
.sda_io_num = I2C_MASTER_SDA_IO,
.sda_pullup_en = GPIO_PULLUP_ENABLE,
.scl_io_... |
73,815,195 | 73,815,313 | Create class based on variadic templates | Lets imagine that we have several data flows and we need unite them to one. Capacity of flows (and type) is known at application level. So we need class that incapsulates all other classes that relates to each data flow and produces common frame based on return type of data flows. Each data flow class have next interfa... | You can expand Args... to be std::tuple<Args...> and declare a member of that type. Now your Main class has a tuple of all Flow types:
template <typename... Args>
struct Main {
using tuple_type = std::tuple<Args...>;
tuple_type members;
the next step is to make a get() function that returns the .get() of all m... |
73,815,252 | 73,815,894 | How do I solve this Array question of Sorting Positive and negative digits in C++? | An array of length L is given. Elements are '–ve' and +ve integers. Make a function that figure out all positive numbers in the array that have their opposites in it as well.
Input : 4,5,8,3,2,-5,-8,-4,-2,-3,-5,8,-8
Output : 2,-2,3,-3,4,-4,5,-5,8,-8
I copied this code from the web but couldn't understand it, is there ... | Using standard algorithms does not always immediately make code easier, but standard algorithms are well documented. If you do not understand application of a standard algorithm you can find plenty of documentation. That isnt the case for self-written algorithms.
Know your algorithms! I will use a simpler example: 2,1... |
73,815,697 | 73,816,403 | Is there a way to expect global exception in GTest? | I have a scenario where a call SendFeedback() sends a message and returns successfully. The message is received by another thread which throws. EXPECT_THROW doesn't work because SendFeedback() does not throw itself. Is there a way to expect this kind of exceptions?
pseudo-code:
auto listener = Listener();
auto sender =... | It is not exactly what you asked for, but GTest have for mechanism for death tests, where you can assert that given invocation would crash the program.
Uncaught exception invokes std::terminate, which by default invokes std::abort, thus will pass the assertion.
I've made small proof of concept to verify it works:
void ... |
73,816,170 | 73,816,569 | Why implement specific functions to retrieve data rather than retrieving directly when overloading a * operator for a iterator class nested in a ADT | C++ newbie here.
I'm reading the book Data Structures and Algorithm Analysis in C++(M. A. Weiss), where the implementation of const_iterator and iterator class nested in a user-defined List class of <typename Object> was given.
Here's a snippet of it.
class const_iterator
{
public:
const Object& operator* () const
... | I think the usage of intermediary function may just be due to the preference of the author. Usually such style is used in order to perform some validation in the intermediary function(for example, checking if data_ is nullptr, or if data_ satisfies some condition which is imposed by the problem the code tries to solve)... |
73,816,266 | 73,816,442 | consume element from std::set | I try to directly consume elements from a set, which i cannot get to work from the outside getting an error
binding reference of type ‘int&&’ to ‘std::remove_reference<const int&>::type’ {aka ‘const int’} discards qualifiers
Consuming from a vector works perfectly fine.
I really do not understand where syntactic the di... | The point is: You are not allowed to change the objects within a set, as this would require to move their location within the set. This is why the iterator only returns a const reference even for non-const std::set!
Now r-value references are intended to be used to modify the object (moving the contents away – which wo... |
73,816,371 | 73,816,468 | error C2312 is thrown for ifstream::failure and ofstream::failure exceptions | I am writing a small application that modifies a text file. It first creates a copy of the file in case something goes wrong.
The following function creates this copy in the same directory. It takes the file's name as an argument and returns true if the copy is successfully created, and false if it fails.
#include <ios... | ifstream::failure and ofstream::failure are both the same type defined in the std::ios_base base class std::ios_base::failure, you can't catch the same type in two separate catch clauses.
Note that neither of your streams will actually throw any exceptions, by default std::fstream doesn't throw any exceptions. You have... |
73,816,562 | 73,816,629 | Can't use vector::assign with 1 parameter on vs code mac | At first I thought there was something wrong with my code, but even this gets compiler errors and says that I need to provide 2 arguments:
#include<iostream>
#include<vector>
std::vector<int>v;
int main()
{
int m;
std::cin>>m;
v.assign(m);
}
If I use v.assign(m,-1); instead of v.assign(m);, it compiles... | See the documentation for std::vector.assign(). assign(n, e) will fill the vector with n copies of e. There is no 1 argument call to assign.
|
73,816,713 | 73,852,577 | cppyy OPENMP error: nullptr result where temporary expected | I've been trying to run some parallelised code in C++ from Python through cppyy but am facing an error.
The executable (compilted through GCC with -fopenmp -O2) runs without errors and shows the expected drop in runtime from parallelisation.
When the #pragma omp parallel for is commented out of the C++ code, cppyy does... | The problem was linking the OpenMP library file to the Cling compiler that runs cppyy.
I encountered the same problem in Linux Mint and Windows 11 too - which made me realise it is not an OS-specific problem. What ended up working was the following:
Add the -fopenmp flag to your EXTRA_CLING_ARGS environmental variable... |
73,816,992 | 73,817,023 | Is it safe to use c_str() as a parameter in std::exception? | Is it safe to pass c_str() as a parameter when constructing std::exception? Please let me know if handling exceptions like this is a bad idea. In my project all error messages are returned from a function as std::string and then thrown as a std::exception.
#include <iostream>
int main()
{
try {
std::stri... | std::exception does not have a contructor that takes a const char* or a std::string.
std::runtime_error (and its descendants) does have constructors for both. And yes, it is perfectly safe (well, provided that memory is not low) to pass the message.c_str() pointer to this constructor. std::runtime_error will copy the c... |
73,817,020 | 73,817,757 | Why is there no built-in way to get a pointer from an std::optional? | Things like the following happen all to often when using std::optional:
void bar(const Foo*);
void baz(const std::optional<Foo>& foo) {
// This is clunky to do every time.
bar(foo.has_value() ? &foo.value() : nullptr);
// Why can't I do this instead?
bar(foo.as_ptr());
}
This is the sort of thing... | To be pedantically correct, you need to use one of these instead:
// `Foo` might have an overloaded `operator&`
foo.has_value() ? std::addressof(foo.value()) : nullptr
// You can shorten it to
foo ? std::addressof(*foo) : nullptr
// Or you can use `operator->()`
foo ? foo.operator->() : nullptr
// Which in C++20 can be... |
73,817,544 | 73,817,779 | C++ constexpr function parameters | With this nice simplified compile time string class.
There are no constexpr/consteval function parameters in C++
but the point of this question is:
Can I get a function call style for passing of non-type template parameters ?
With the suffix I can get pretty close.
But can it be done better ?
I do not want to use this ... | Preprocessor macro trickery aside, it is impossible to do it with the exact syntax you want, because a usual string literal (not a user-defined literal) does never encode its value in its type (only its length).
A value passed to a function via a function parameter can never be used by the function in a constant expres... |
73,819,293 | 73,828,023 | Finding current connected network interface/adaptor Windows | I'm thinking there must be a way to ask windows for information about the network adaptor of the current connected network (available unicast/multicast, is it Wi-Fi, the name, etc)
When I say connected, I mean like the current Wi-Fi connection like windows shows you in the Wi-Fi options - the definition of connected is... | The GetAdaptersAddresses will give you the list of network interfaces on the system and will tell you what type of interface each of them is.
In the returned IP_ADAPTER_ADDRESSES list, the IfType field tells you the type of the interface, which for wireless will be IF_TYPE_IEEE80211. Then when you find an interface of... |
73,820,256 | 73,821,701 | Vector of queues of different types | I have a type, let's call it T. It can be of different types, and I do not know them in advance:
int, double, bitmap pointer...
Now, I have a class, let's call it C. It should maintain a vector of queues of T.
Each queue has its unique type of elements, but it is possible that C has a vector (or whatever other way of m... | It's actually not that complicated. You don't even need recursion. Just std::tuple
#include <tuple>
#include <queue>
template <class... Args>
struct C
{
std::tuple<std::queue<Args>...> queues_;
template <std::size_t I>
auto& queue_at()
{
return std::get<I>(queues_);
}
};
auto test()
{
... |
73,820,417 | 73,820,534 | Lazy Evaluation on condition variables | In the following code snippet, would compiler do lazy evaluation on condition variables and also do short circuit evaluation?
const bool condition1 = calcCondition1(...);
const bool condition2 = calcCondition2(...);
const bool condition3 = calcCondition3(...);
if (condition1 && condition2 && condition3)
return true;... | Yes, if compiler is sure that such a optimization does not change any visible semantic of the program (see __attribute__((pure)) example below).
No in other cases. Note that function bodies from different compilation units (different .cpp file) are unknown: they are linked into binary after compilation process.
The com... |
73,820,519 | 73,821,900 | Why does gcc 12.2 not optimise divisions into shifts in this constexpr function | I have been playing around with the Godbolt Compiler and typed this code:
constexpr int func(int x)
{
return x > 3 ? x * 2 : (x < -4 ? x - 4 : x / 2);
}
int main(int argc)
{
return func(argc);
}
The code is somewhat straight forward. The important part here is the final division by 2 inside func(int x). Since... | GCC treats main specially: implicit __attribute__((cold))
So main gets optimized less, as it's usually only called once in most programs. __attribute__((cold)) isn't quite the same as -Os (optimize for size), but it's a step in that direction which sometimes gets the cost heuristics to pick a naive division instructio... |
73,820,660 | 73,820,856 | Why doesn't ISO c++17 permit a structured binding declaration in a condition? | Clang emits a warning if I use a structured binding declaration as a condition:
$ cat hello.cc
int main() {
struct A { int i; operator bool() { return true; } };
if (auto [i] = A{0}) {
return i;
}
return -1;
}
$ clang++-10 -std=c++17 hello.cc
hello.cc:3:12: warning: ISO C++17 does not permit structured bin... | The grammar for the if statement is
if constexpr(opt) ( init-statement(opt) condition) statement
and as you can see condition is required while the init-statement is optional. That means in if (auto [i] = A{0}) that auto [i] = A{0} is the condition, not the init-statment. condition is defined as
condition:
expre... |
73,820,693 | 73,822,378 | Choose std::queue or std::priority_queue, depending on whether "<" is defined | Inspired by SFINAE to check if std::less will work, I come to this:
template <typename F, typename S, typename = void>
struct QueueImpl {
using type = std::queue<std::pair<F, S>>;
};
template <typename F, typename S>
struct QueueImpl<F, S, decltype(std::declval<F>() < std::declval<F>())> {
using type = std::pr... | Your first attempt fails for the following reason. When you use the template, you don't specify the third argument. Hence, it is supplied from the default type in the primary template, namely void. Then, the specialization can only match the argument types if the decltype results in void, whereas when F is int, the typ... |
73,820,707 | 73,820,798 | Are preprocessor directives allowed in a function-like macro's argument? | This question regards the legality of using a preprocessor directive within a function-like macro's argument.
Consider the following code. #ifdef is used inside MY_MACRO's argument :
#include <iostream>
// Macro to print a message along with the line number the macro appears at
#define MY_MACRO( msg ) { std::cerr << "... | Short answer: No
[cpp.replace.general]:
The sequence of preprocessing tokens bounded by the outside-most matching parentheses forms the list of arguments for the function-like macro. The individual arguments within the list are separated by comma preprocessing tokens, but comma preprocessing tokens between matching in... |
73,820,932 | 73,821,087 | Observer Design pattern - Getting a segfault | I am writing an Observer design pattern where Subject knows what Observer it has (same as the original design) and Observer also knows what Subject it's attached to, mainly to tackle scenarios like Observer going out of scope and Subject has a reference to a destroyed object.
So if an Observer watches a Subject, both k... | There may be more problems in your code but I can see at last this one:
When Observer is being destroyed in destructor, it iterates over _subjects collection. You call Subject::detach() on each subject. Subject::detach() in turn calls Observer::removeSubject() on the very same observer and Observer::removeSubject() rem... |
73,820,966 | 73,821,028 | `std::is_same_v<size_t, uint64_t>` evaluates to `false` when both types are 8 bytes long | Code:
#include <iostream>
#include <type_traits>
int main() {
std::cout << "sizeof(size_t): " << sizeof(size_t) << std::endl;
std::cout << "sizeof(uint64_t): " << sizeof(uint64_t) << std::endl;
if constexpr (std::is_same_v<size_t, uint64_t>) {
std::cout << "size_t == uint64_t" << std::endl;
} else {
st... | Usually the type size_t is an alias for the type unsigned long.
From the C Standard (7.19 Common definitions <stddef.h>)
4 The types used for size_t and ptrdiff_t should not have an integer
conversion rank greater than that of signed long int unless the
implementation supports objects large enough to make this necessa... |
73,821,149 | 73,964,096 | CPU inference in libtorch causes OOM with repeated calls to forward | I have some libtorch code that is doing inference on the cpu using a model trained in pytorch that is then exported to torchscript. The code below is a simplified version of a method that is being repeatedly called.
void Backend::perform(std::vector<float *> in_buffer,
std::vector<float *> out_buf... | This ended up being a bug in the windows implementation of libtorch. Memory leaks can happen when calling forward on a separate thread from the main thread (https://github.com/pytorch/pytorch/issues/24237), and moving the forward call to the main thread fixed the issue.
Even though the issue is marked closed the bug is... |
73,821,535 | 73,821,607 | program to verify a number by two requirements | I'm trying to make a program that verifies if a number meets two requirements:
the number has 4 digits
not all the digits are the same
I've been made it, and it looks good, but the code fails in a specific case.
When the user enters a number with all of the digits equal, like 1111, the first time the program will s... | To check if your number is 4 digits you can simply compare it:
if( n < 1000 or n > 9999 ) // not 4 digits number
To check if all digits are the same, just check if it is divisible by 1111 (thanks to @SamVarshavchik )
if( n % 1111 == 0 ) // all digits are the same
|
73,821,619 | 73,821,669 | Using Variadic Function to pass args into a vector | I am trying to make a function that adds an unknown amount of objects to a vector. I am trying to accomplish it here by just passing ints, but I cannot get it to work. Does any one know how this can be done?
Code
#include <iostream>
#include <vector>
class Entity
{
public:
std::vector<int> Ints;
template ... | In C++11 and C++14, You can use something like this:
private:
void Internal_AddToVector()
{
}
template <typename T, typename ... pack>
void Internal_AddToVector(T first, pack... argPack)
{
Ints.push_back(first);
Internal_AddToVector(argPack...);
}
public:
template <type... |
73,822,721 | 73,822,873 | Reverse right angle triangle pattern with numbers and asterisks using for-loops in C++ | first time posting here, I'd like help with getting the output of the code upside down while still using the for commands, below is the best I can put in a clarification.
Desired Output: Actual Output:
123456 1*****
12345* 12****
1234** ... | first time answering here :).
change num <= row to num <= integ - row + 1
|
73,822,766 | 73,823,829 | How to extract rotation and translation from Eigen::Affine | Since each Eigen::Affine3d object indicates a special linear transformation, I want extract the rotation part and translation part separately. And I want to save the rotation part into an Eigne::Quaterniond and the translation part into an Eigen::Vector3d. How to realize that?
| Use the rotation() and translation() methods, like this.
Eigen::Affine3d a;
...
Eigen::Quaterniond q(a.rotation());
Eigen::Vector3d t(a.translation());
|
73,823,025 | 73,865,813 | Libssh - Can't connect to Windows host | I have some code that initiates a simple SSH client session using Libssh, but its failing at ssh_connect
int main()
{
ssh_session my_ssh_session;
int rc;
int port = 22;
const char* password;
int verbosity = SSH_LOG_FUNCTIONS;
// Open session and set options
my_ssh_session = ssh_new();
if (my_ssh_session == NULL)
e... | If you build libssh statically, you must call ssh_init() early, and in a "main" context.
From the manual:
If libssh is statically linked, threading must be initialized by
calling ssh_init() before using any of libssh provided functions. This
initialization must be done outside of any threading context. Don't
forget to... |
73,823,210 | 73,823,465 | template parameter incompatible with declaration | I have a function that should generate a random integer or a random floating point value.
For that I want to use concepts.
Since integers and floating points need different distributions, namely std::uniform_int_distribution and std::uniform_real_distribution respectively, I use a separate struct to select the correct... | Use the concepts in the specialization but not in the declaration of the primary template.
Also, distribution is not a template, its type is determined at its context.
template <typename T>
struct distribution_selector;
template<std::integral I>
struct distribution_selector<I> {
using type = std::uniform_int_distr... |
73,823,283 | 73,823,386 | Why i am getting No associated state error in below example. Could anyone tell any reason? |
In below program i am getting error std::future_error: No associated
state error.could anyone help why i am facing this error
#include <iostream>
#include <thread>
#include <future>
#include <chrono>
#include <functional>
void task(int& var, std::future<int>& refFuture)
{
std::packaged_task<int()> mytask{ [&](){... | You are not waiting for the thread to actually execute refFuture = std::move(future); before you wait on future in the main thread, so the future in main does not have any associated state to wait on at that point.
I am not sure what you are intending to do here, but you are supposed to prepare the std::packaged_task i... |
73,824,767 | 73,825,922 | stbi_write_png external symbol not solved | I can use stbi_load correctly and have the next code in a .cpp file:
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
When trying to use stbi_write_png I got a compiling error saying thats unsolved symbol.
This is the code where I call the function.
void FeatherGUI::saveImage() {
//save the current image us... | Adding
#define STBI_MSC_SECURE_CRT
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
Fixed the problem also has to change the sprintf call inside the stb_image_write to sprintf_s.
|
73,824,975 | 73,825,071 | Does declaring a constexpr object marks the constructor as constexpr | I just a have a problem in understanding when the compiler marks the constructor as constexpr.
If I write the following program:
struct S{ S() {}; }
constexpr S s{ };
Does this mean that the default constructor is marked as constexpr?
| An implicitly-defined constructor is a constructor defined by the compiler implicitly when some contexts are encountered (see below). But, an explicitly-defined constructor is a constructor defined by the user, not by the compiler.
Now per [class.default.ctor]/4:
A default constructor that is defaulted and not defined... |
73,825,006 | 73,825,180 | iterate char by char through vector of strings | I want to iterate char by char in a vector of strings. In my code I created a nested loop to iterate over the string, but somehow I get an out of range vector.
void splitVowFromCons(std::vector<std::string>& userData, std::vector<std::string>& allCons, std::vector<std::string>& allVows){
for ( int q = 0; q < userDa... | The error here is in these lines:
allVows.push_back(userData.at(r));
allCons.push_back(userData.at(r));
the r variable is your index into the current string, but here you're using it to index into the vector, which looks like a typo to me. You can make this less error prone using range-for loops:
for (const std::strin... |
73,825,663 | 73,825,870 | why can I not use break? | I have written the following code for the problem:
Alice has an array of NN integers — A_1, A_2, ..., A_N. She wants the product of all the elements of the array to be a non-negative integer. That is, it can be either 00 or positive. But she doesn't want it to be negative.
To do this, she is willing to remove some ele... | You need to read all input even if you do know the answer already:
for(int i=0;i<n;i++){
int f;cin>>f;
// ^^ ----------- !!!
If you break from that loop then the numbers for the current test case are still in the stream, waiting to be read. And you do read them for the next test case.
Consider this... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.