question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
71,059,958 | 71,060,020 | How to connect to and access information on a NoSQL database using C++ | I want my code to be able to connect to a wide-column store database like Cassandra or DynamoDB and read/write information to it.
I have been working on a project primarily written in C++ and was able to use a MySQL database simply by including mysql.h header file and using some functions defined in this file to connec... | You can use Datastax C/C++ driver for connecting your application with Cassandra database.
|
71,060,196 | 71,060,456 | Is it valid to delete a lambda while executing it? | Is it allowed to delete a lambda object while executing the associated lambda function, as long as precautions are taken not to access any of the captured state after the deletion?
Consider the following example:
int main() {
int x = 1;
std::function<void()> d;
auto l = new auto([x, &d]() {
fmt::... | There might not be an explicit specification for this in the standard.
Although not specified to be so, lambda types are "essentially" like special classes. Staying with this analogy, the question would be same as "Is it well defined to delete this;". The typical answer to that question is:
As long as you’re careful, ... |
71,060,202 | 71,060,722 | When is a class template depending on a incomplete type as a template argument instantiated? | class I;
template<class T>
struct P
{
T t;
};
template<class T>
struct F
{
operator bool() {return false;}
};
int main()
{
int a = F<P<I>>();
int b = !F<P<I>>();
int c = int(F<P<I>>());
int d = !int(F<P<I>>());
}
Are the evaluations in the initializers above well-formed? Why or why not? Whi... | Specializations are instantiated only if a complete type is required or affects the semantics in the given context. [temp.inst]/2
So the default behavior is not to do any implicit instantiation if not necessary.
In all the cases you have shown, the specializations of F need to be instantiated because T() requires T to ... |
71,060,511 | 71,060,555 | c program Warning the control reaches the end of non-void function | so this is a simple c programming using recursion which returns the power of the input value, but for some reason it showing error
#include <iostream>
//int sum = 1;
int powerOfNumber(int n, int p) {
if (n != 0) {
p--;
return powerOfNumber(n , p) * n;
}
if (n == 0) {
return 1;
... | #include <iostream>
using namespace std;
int powerOfNumber(int n, int p) {
if(p==0)
return 1;
else
return (n*powerOfNumber(n,p-1));
}
int main()
{
std::cout <<powerOfNumber(5, 2);
return 0;
}
Your powerOfNumber function never terminates because n is always 5.
|
71,061,070 | 71,061,801 | std::ranges::take_while_view cannot pipe | auto int_v10 = std::vector{8,7,3};
//fail auto rng2 = int_v10 | std::ranges::take_while_view([](int x) {return x> 5;} ) | std::ranges::views::common;
auto rng2 = int_v10 | std::ranges::views::take_while([](int x) {return x> 5;} ) | std::ranges::views::common;
auto result4 = std::accumulate(rng2.begin(), rng2.end(),0... | take_while_view has only two constructors:
take_while_view() = default;
constexpr take_while_view(V base, Pred pred);
The second constructor needs to accept two parameters, one is base and the other is pred, so you need to struct it like this:
auto rng2 = std::ranges::take_while_view(int_v10, [](int x) {return x > 5;}... |
71,061,241 | 71,061,428 | How to "map" a variadic macro with boost preprocessor? | Say I have a macro F:
#define F(x) /*...*/
and a macro G that takes one or more arguments:
#define G(...) /*...*/
and I want to write a macro H that takes one or more arguments that expands to G with F applied to each argument:
#define H(...) /* G(F(arg1),F(arg2),...,F(argn)) */
How can H be implemented with boost.p... | You can use BOOST_PP_SEQ_FOR_EACH_I to do this "mapping" operation:
#define VARIADIC_MAP(r, macro, i, elem) BOOST_PP_COMMA_IF(i) macro(elem)
#define H(...) G(BOOST_PP_SEQ_FOR_EACH_I(VARIADIC_MAP, F, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)))
The BOOST_PP_COMMA_IF(i) prepends a , before every value except the first so thi... |
71,061,638 | 71,080,885 | Handle PostgreSQL transaction errors in GDALVectorTranslate | In c++ I'm using the GDAL library for importing geo-spatial files into Postgres/PostGIS.
The GDAL library will create a table in the Postgres database and insert the data. But I can't figure out how to handle errors during the inserting of data.
I'm using GDALVectorTranslate https://gdal.org/api/gdal_utils.html#gdal__u... | You can register your own error handler to log and count the underlying errors:
struct {/*members for handling errors*/} ctx;
static void myErrorHandler(CPLErr e, CPLErrorNum n, const char* msg) {
ctx *myctx = (ctx*)CPLGetErrorHandlerUserData();
/* do something with ctx to log and increment error count */
}
int ... |
71,061,748 | 71,061,988 | Swapping between subclasses of an Abstract Class | I want to make an abstract class, A that will be subclassed by Class B and Class C such that they will all use the same methods in the defined abstract class (B and C are A-able classes).
I have another class, Z, that will contain an array of A-able classes. I would like for it to have a function that allows it to swap... | Like other comments, if you store a vector of superclass by value, say vector<A>, as the vector allocates the memory, in addition to other information that vector stores, it will allocate sizeof(A)*NumOfElement(vector<A>) for storage. As subclasses, say B need more space than A, object slicing will occur. My suggestion... |
71,061,771 | 71,064,494 | Is it possible to draw 3d segments with CGAL? | I want to draw 3d segments, and the camera can rotate, so that I can observe the segments from various perspectives. I wonder if there is a way to draw them with CGAL? I know that CGAL is not specific for visualization, so the question itself may be some kind of silly. But it will be really helpful for me if it has thi... | CGAL::Basic_viewer_qt allows to draw points, segments and faces in 2D/3D.
You can define your own viewer inheriting from this class.
As suggested by Marc, have a look at the different draw_XXX.h files to see how this is achieved for several viewers in CGAL.
|
71,061,842 | 71,062,195 | Can a custom allocator improve cache locality for lists? | This is a rather hypothetical question.
I only have limited knowledge about how the cpu cache works.
I know a cpu loads subsequent bytes into the cache.
Since a list uses pointers/indirection into random locations in memory, it has relatively bad locality compared to lets say vector or an array.
My question is: If I wr... | Yes and no, but leaning mostly toward no, at least if you use the list in a way that lets you get anything out of it.
The advantage of a linked list is the ability to insert and delete elements in the middle of the list in constant time (provided you already know the point where you're going to insert/delete).
If you a... |
71,062,018 | 71,062,244 | Evaluating a postfix expression | This is a program to evaluate a post-fix expression using stack. Why in the 8th line we have pushed question[i]-'0' rather than just question[i]. I did not understand the role of 0.
stack<int> s;
int main(){
string question;
cin>>question;
for(int i = 0 ; i < question.length() ; i++){
if(isdigit(question[i])... | '0' is a character literal.
So when you wrote:
s.push(question[i] - '0');
The fundamental reason why/how question[i] - '0' works is through promotion.
In particular,
both question[i] and '0' will be promoted to int. And the final result that is pushed onto the stack named s will be the result of subtraction of those ... |
71,062,312 | 71,069,429 | How to ensure that the messages will be enqueued in chronological order on multithreaded Asio io_service? | Following Michael Caisse's cppcon talk I created a connection handler MyUserConnection which has a sendMessage method. sendMessage method adds a message to the queue similarly to the send() in the cppcon talk. My sendMessage method is called from multiple threads outside of the connection handler in high intervals. The... | If you use a strand, the order is guaranteed to be the order in which you post the operations to the strand.
Of course, if there is some kind of "correct ordering" between threads that post then you have to synchronize the posting between them, that's your application domain.
Here's a modernized, simplified take on you... |
71,062,376 | 71,062,829 | Problems with using accumulate in c++ | I'm using OpenCV to access the color data of the pixels within a specified area and currently I'm trying to use the accumulate method in c++ to sum up all the data numbers obtained in that specified area. But right now it has only given me the sum of only a single pixel within the specified area and not the whole area.... |
Is there something that I have missed and have not written?
you've missed the fact that you are still in the middle of your loop. You need to define v, w and x before the loop, and add each element, then accumulate after the loop.
std::vector<int> v;
std::vector<int> w;
std::vector<int> x;
//the rows of the image
for... |
71,062,558 | 71,063,204 | boost:math:factorial2 throws an error while computing double factorial of -1? | The official documentation of boost library in C++ confirms that -1!! is defined. However, when I try to compute the double factorial of -1, it throws the following error
"Error in function boost::math::tgamma result of gamma is too large to represent". I can implement a code based on iteration to compute the same (if ... | This is how boost::math::double_factorial is declared:
namespace boost{ namespace math{
template <class T>
T double_factorial(unsigned i);
template <class T, class Policy>
T double_factorial(unsigned i, const Policy&);
}} // namespaces
According to the documentation for boost::math::double_factorial
The argument t... |
71,062,930 | 71,063,103 | How does std::find works with std::set | To find an element from a std::set, ofc, we should use std::set::find. However, the function std::find/std::find would work too.
std::set<int> st;
for (int i = 0; i < 999999; i++) {
st.insert(i);
}
// method 1
if (st.find(999990) != st.end()) {
std::cout << "111" << std::endl;
}
// method 2
auto itor = std::f... | The reason for the time complexity difference is that std::find operates with iterators, and it, indeed, does treat std::set as a sequence container, while std::set::find uses container properties.
As for why st.begin() is faster than std::begin(st), they are actually identical. The reason why second is faster is that ... |
71,063,108 | 71,063,172 | converting a string to lowercase/uppercase depending upon the count of upper/lower case characters in it | i have to output a string in all uppercase if count of uppercase characters in it is more otherwise lowercase string will be shown if lowercase characters are more in the string,in case both characters are equal i will print the string in lowercase only
this the code i have written , but , it's not giving desired outpu... | After your first loop, do this:
string result = (uc>lc) ? toupper(s) : tolower(s);
|
71,063,295 | 71,063,296 | Program segfaulting in release version only | I have an executable that is segfaulting in release but not in debug. I assume it's a wrong call to a printf-family function.
When running i get this:
*** buffer overflow detected ***: ./mybin terminated
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x777f5)[0x7f3a8914d7f5]
/lib/x86_64-linux-gnu/libc.so... | Well, as it turns out, the original text (not "Some text") took 19 chars plus the %d, which is "always" one digit. Even so, that's 20 chars in a char aCharArr[20], producing a char array that is not \0-terminated.
Increasing the size of aCharArr (to the next multiple of 8 but that's just me) fixed it and using snprintf... |
71,063,649 | 71,064,211 | Pass template function to std::bind? | I want to use std::bind with template function. Is it somehow possible?
P.S. It is IMPORTANT to use std::bind, because I know at least one solution through lambdas and want to find out if there is std::bind solution.
#include <iostream>
#include <functional>
#include <memory>
using namespace std;
struct foo : std::en... | handle is not a template function. There are no "template functions". handle is a function template, ie it is a template, it is not a function. You cannot std::bind to a template. You can only std::bind to a callable.
The trick is to defer instantiation of the template and deduction of the template parameters to when t... |
71,064,243 | 71,064,350 | Inject default template argument type from user code | Is there a way to "inject" a default type for a template member function of a template class "after" the definition of said template member function?
Basically similar to this (which does not compile), so that I can specify NS::Default (the default type for Z) outside of the library in which template class S and its me... | You can create a traits that customer should define/specialize:
// In library
template <typename> struct DefaultType; // declaration without definition.
template<typename T>
struct S {
template<typename X, typename Z = typename DefaultType<X>::type>
void foo(X x, Z z = Z{}) {}
};
// In user code
template <typena... |
71,064,756 | 71,070,626 | How to install websockets for Qt 6? | Already referred below old posts, but its solution of installing websockets didn't work in my Ubuntu 21.10.
Project ERROR: Unknown module(s) in QT: websockets
Project ERROR: Unknown module(s) in QT: webkitwidgets
This could be probably due to my Qt is 6.2, while the available library is from Qt5, viz. libqt5websocket... | When installing Qt via Qt Maintenance Tool, just go to Additional Libraries and check QtWebSockets. It is available in Qt 6.2.x versions.
|
71,065,244 | 71,065,931 | SSBO CPU mapping returning correct data, but data is 'different' to the SSBO on GPU | I've run into an issue while attempting to use SSBOs as follows:
GLuint lightSSBO;
glGenBuffers(1, &lightSSBO);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, lightSSBO);
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(int) + sizeof(LightData) * 10, NULL, GL_DYNAMIC_DRAW);
glBufferSubData(GL_SHADER_ST... | GLSL structs and C++ structs have different rules on alignment. For structs, the spec states:
If the member is a structure, the base alignment of the structure is N, where
N is the largest base alignment value of any of its members, and rounded
up to the base alignment of a vec4. The individual members of this substru... |
71,065,497 | 71,126,504 | How to add an action to the default context menu of a QSpinBox? | I am using Qt 5.7 (C++) and want to add custom functionality like a reset option to a QSpinBox (as well as QDoubleSpinBox and maybe some other input widgets). This functionality should be accessible via the context menu. However I do not want to replace the default context menu. Instead I want to add my custom actions ... | https://code.qt.io/cgit/qt/qtbase.git/tree/src/widgets/widgets/qabstractspinbox.cpp#n1315
Yeah it doesn't look like we have any easy "hook" for customizing it (and you can make a feature request if you like); OTOH it's not that much code to copy, since most of the menu entries are added by QLineEdit::createStandardCont... |
71,065,560 | 71,065,804 | Why do you use a Scope Resolution Operator when defining a class' method? | My question about the Scope Resolution Operator (::) is why do we use it in a CPP file to define the methods of a class? I'm more so asking about the SRO itself, rather than the relationship between CPP and Header files.
| When you define a class:
struct foo {
void bar() {}
};
Then the full name of bar is ::foo::bar. The leading :: to refer to the global namespace can often be omitted. There is no bar in the global namespace, hence bar alone (or ::bar) does not name an entity and when you define the method out of line you need to te... |
71,065,852 | 71,066,035 | Should I #include .cpp files to header of TestSuite to make cxxtest work? | Situation is as follows: I've got a simple project consisting of two files - Calc.h and Calc.cpp.
Calc.h:
#pragma once
class Calc {
public:
int add(int,int);
static const int a = 42;
}
Calc.cpp:
#include "Calc.h"
class Calc {
public:
int add(int a,int b){
return a + b;
};
}
CalcTestSuite.h:
... | There are two problems:
You are violating One Definition Rule! You can't redefine Calc like this:
#include "Calc.h"
class Calc {
public:
int add(int a,int b){
return a + b;
};
}
It must be:
#include "Calc.h"
int Calc::add(int a,int b) {
return a + b;
};
const int Calc::a;
Now this problem do not s... |
71,065,942 | 71,066,026 | no warning for missing ctor initializer list? | This code is missing a constructor initializer list:
#include <cstdio>
struct s {
s() {} // should be s(): m() {}
int m;
};
int main() {
struct s *px = new s();
if (px->m) {
printf("true\n");
} else {
printf("false\n");
}
delete px;
return 0;
}
gcc compiles clean wit... | You could add -Weffc++ to catch it (inspired by Scott Meyers book "Effective C++"). Strangely enough it does not refer to any other -W option (and neither does clang++).
The option is however considered, by some, a bit outdated by now, but in this case, it's finding a real problem.
|
71,066,647 | 71,069,105 | OpenAL Soft 40964 in alcOpenDevice: AL_INVALID_OPERATION | When running my audio application, ported from Windows, on Ubuntu Virtualbox, it reports the following:
Devices found:
OpenAL Soft
OpenAL Soft 40964 in alcOpenDevice: AL_INVALID_OPERATION
The line it runs on:
ALCdevice device = alcOpenDevice( NULL ); // Also tried "OpenAL Soft"
Ubuntu audio is working properly. What... | Apparently, the alGetError() will return this error before a context is created. Starting from alcMakeContextCurrent() I can use this function to check for errors.
It now plays audio!
So for alcOpenDevice() and alcCreateContext() I had to comment out the alGetError() error checking. Though I could still check whether t... |
71,066,820 | 71,066,957 | Numeric UDL operator template | I'm trying to define what Pablo Halpern calls a numeric UDL operator template. I want it to return a lambda that would count how many characters at the beginning of a char array are from the given set.
Here's my test code:
template <char... c>
constexpr auto operator ""_cntany() {
return [](const char* s){
unsign... | cppreference says
If the literal operator is a template, it must have an empty parameter list and can have only one template parameter, which must be a non-type template parameter pack with element type char (in which case it is known as a numeric literal operator template)
template <char...> double operator "" _x();... |
71,067,493 | 71,067,530 | C++ equivalent of Java StringUtils.indexOfDifference | For C++20, is there a library equivalent of Java's StringUtils.indexOfDifference()?
What is the efficient way of comparing two large strings and determining where they differ?
| You can use std::mismatch from <algorithm>
Returns the first mismatching pair of elements from two ranges
For example
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
std::size_t IndexOfDifference(std::string const& lhs, std::string const& rhs) {
auto diff = std::mismatch(lhs.begin(... |
71,067,900 | 71,069,088 | How to set C++ version with Bazel in a cross platform way? | I would like my Bazel project to use c++17. There is a similar question (How to set C++ standard version when build with Bazel?) but the accepted answer does not port to MSCV.
MSCV needs --cxxopt='/std:c++17' while gcc needs --cxxopt='--std=c++17'.
Does anyone have a minimal example configuration that builds on the mos... | You can do something like this in your .bazelrc:
# GCC 9.3
build:gcc9 --cxxopt=-std=c++2a
build:gcc9 --cxxopt=-Wall
build:gcc9 --cxxopt=-Werror
##build:gcc9 --cxxopt=-Wextra
build:gcc9 --define compiler=gcc9_3_0
build:macos --cxxopt=-std=c++2a
build:macos --cxxopt=-Wall
#build:macos --cxxopt=-Werror
##build:macos --cx... |
71,068,221 | 71,068,425 | Why does std::condition_variable::wait_for() return with timeout if duration too large? | The following behavior was seen under g++ 11.2.1 . The std::condition_variable wait_for method returns immediately if the timeout variable is too large. In particular in the program below, if num_years==1, then the program hangs waiting as expected (presumably for 1 year), but if the variable num_years==1000 then the p... | This is an overflow bug under the hood of condition_variable::wait_for. Internally it is waiting using steady_clock which counts nanoseconds. This clock overflows at +/-292 years. So when 1000 years gets converted to nanoseconds, it is overflowing.
This looks like a standards bug as opposed to an implementation bug:... |
71,068,287 | 71,078,952 | Batch one line to call an executable using arguments from file | For convenience, I have renamed all the files to simple names for my example.
I'm trying to run an executable (test.exe), with a C++ entrypoint int main(int argc, char* argv[]) from a batch file (test.bat), and pass arguments from a text file (test.txt). The end goal is to run unit tests on an SDK using the testing sof... | Thanks to the comments under my question, I was pushed in the right direction.
The problem was my understanding of <. It literally means "Read file to STDIN" (as mentionned here). Many other documentation sites give vague definitions like (as mentionned here)
command < filename : Type a text file and pass the text to ... |
71,068,332 | 71,068,438 | Is there a reason to name parameters in forward declaration? | Say I have this:
// Forward Declaration of the sum()
void sum(int, int);
// Usage of the sum
void sum(int a, int b)
{
// Body
}
It could also be done like this:
// Forward Declaration of the sum()
void sum(int a, int b);
// Usage of the sum
void sum(int a, int b)
{
// Body
}
Is the latter version just a was... | No you don't need to.
You could even rename your function to
void _(int, int);
(in both places of course). But then it's harder to follow still. In other words the parameter and function names are important for readability. Given most program documentation appears in header files, and most forward declarations are in ... |
71,068,538 | 71,069,401 | Insertion sort using vectors, not working | Im trying to create an insertion sort algorithm using vectors, but instead of parsing the elements from the start of the array (vector here), i tried doing it from the end. The code does nothing but sort the element for the first time, and delete the first element of my vector. I want to know what correction to my code... | This is my implementation of Insertion reverse algo.
template <class T>
void isort(vector <T> &ar){
if(ar.size() < 2)
return;
//start from second last element upto first element
for(auto i = ar.end()-2; i >= ar.begin(); i--){
auto j = i;
//swap values until condition met
whi... |
71,068,840 | 71,069,414 | How to assign the shared_ptr object to the function of type raw pointer using C++ | I am creating the shared_ptr in a function and returning raw pointer from that function.
To get the underlying raw pointer from the shared_ptr I am using .get()
If i am using the raw pointer in a function and assigning to the function of type raw pointer it is working without any issue.
But if i create the shared_ptr a... | Yes, what @user17732522 said.
In the code as written, l_MyClassInterface is going out of scope when your first version of CreateClassInstance returns, taking your newly created object with it. When you return a shared_ptr, as opposed to the pointer returned by get(), the mechanism that it uses to keep track of the ref... |
71,068,960 | 71,073,967 | How to call destructor of C++ class safely from a Python wrapper class using ctypes? | I built a C++ shared library, that exports functions for constructing, destructing and interacting with an implemented class. I want to write a wrapper class in Python, which loads the compiled .dll and wraps all the functions as a class using ctypes .
How do I wrap the destructor function of the C++ class safely so it... | As per Python's data model doc:
Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether...
...
Some objects contain references to “external” resources such as open files or windows. It... |
71,069,539 | 71,069,608 | How can this warning of InteropServices.SEHException be real? | I prevent unmanaged C++ exceptions from escaping from my C++/CLI code by wrapping unmanaged calls with exception frames where I catch const std::exception&. But I've got a code-path in which the unmanaged C++ throw immediately triggers a warning of SEHException, even though there is clearly a catch clause higher up th... | Interesting.
It's not at all obvious from the documentation exactly what's going on here, but there's an interesting article over at Code Project which explains how (unmanaged) C++ exceptions are handled by the Microsoft compiler. Basically, when you call throw an SEH exception is generated (via RaiseException) which ... |
71,070,080 | 71,070,137 | Building opencv from source in Mac m1 | I'm using the following Make to build OpenCV from source,
cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D OPENCV_EXTRA_MODULES_PATH=/Users/Tools/opencv_contrib/modules \
-D PYTHON3_EXECUTABLE=/miniforge/base/envs/envname/bin/python3 \
-D BUILD_opencv_python2=OFF \
-D BUILD_o... | I think that you've installed ffmpeg 5 and OpenCV is not yet compatible with it. Please try the following:
brew install ffmpeg@4
brew unlink ffmpeg
brew link ffmpeg@4
and then recompile OpenCV again.
|
71,070,100 | 71,070,921 | Function declaration conditioned on a used library version? | I have the following problem: say I'm using library Foo and there's a function bar that I use in my personal library. However, in an upcoming release, the function definition of bar is going to change. For example,
bar(int first, int second, int third)
will become
bar(int first, int newSecond, int second, int third)
It... | There are a few ways to go about this.
The first that comes to mind would be to use preprocessor directives:
#define OLD_VERSION // Can be set in code or when you compile the code
int myFoo(int first, int second, int third){
#ifdef OLD_VERSION
auto something = bar(first, second, third);
#else
a... |
71,070,150 | 71,070,204 | Returning an std::pair<std::shared_ptr<A>, std::unique_ptr<B>&> from a function results in weirdness | I'm having trouble understanding the (to me intricate) mechanisms executed behind the scenes in the following code example:
#include <utility>
#include <memory>
#include <iostream>
struct A {int a;};
struct B {int b;};
std::pair<std::shared_ptr<A>, std::unique_ptr<B>&> FuncA() {
std::shared_ptr<A> a = std::make_s... | std::pair<std::shared_ptr<A>, std::unique_ptr<B>&> FuncA() {
// ...
std::unique_ptr<B> b = std::make_unique<B>();
// ...
return {a,b};
}
A local std::unique_ptr<B> is created and a reference to it is returned as the second element in the pair. This is a dangling reference and is later accessed, giving ... |
71,070,239 | 71,070,421 | C++ Move constructor not called with the compound operator += when written in one line | I followed the amazing tutorials from stackoverflow for Move and Operator overloading (e.g. What are the basic rules and idioms for operator overloading?), and the following situation is baffling me. Nothing fancy in the code, just printing when special member functions are called.
The main code:
class B {
public:
... | Returning a local variable of type T from a function with with the same1 return type T is a special case.
It at least automatically moves the variable, or, if the compiler is smart enough to perform so-called NRVO, eliminates the copy/move entirely and constructs the variable directly in the right location.
Function pa... |
71,070,299 | 71,070,522 | C++ vector member initialization | I am confused about the output in the following program about the vec in Test. Why it's a vector with size 100 instead of 1? I thought std::vector<T> var{a} is the same as std::vector<T> var = {a}.
#include <iostream>
#include <vector>
using namespace std;
struct Value {
int a;
int b;
};
class Test {
public:
... | std::vector has a constructor with a std::initializer_list<T> argument. When using an initializer list like {100} this constructor will always take priority, if it is applicable.
For a std::vector<int> the initializer {100} is compatible with std::initializer_list<int> so that constructor will be used. It will create a... |
71,070,880 | 71,071,122 | The texture of the player does not changing | In the code I wrote, the collision is detected correctly, but only 1 enemy changes players texture. What is the reason and how can I change players texture for every enemy? The problem is between lines 56 and 64 of the code.
Screenshots :
No collision
Collision but texture isn't change
Collision and players texture is ... | In your loop
for(int i=0;i<5;i++){
you are iterating through all 5 enemies.
If you detect collision with the LAST one, you change the texture and get out of the loop. But if the collision was with any other enemy, the next loop iteration will revert the texture back.
Solution: you might want to break; out of the l... |
71,071,231 | 71,072,106 | Binary to Decimal conversion not working properly: C++ | can anyone please help me with this code I wrote. I am multiplying the digit from the string that is either 0 or 1 by 2 to the power of "power" which is an integer incrementing every time we loop and I am adding the result to the return value...but for some reason it's not working.
So for example: "10" is returning 48 ... | There is another simpler implementation by strtoull() function for your problem.
More details can be found at C++: binary std::string to decimal
|
71,071,298 | 71,081,367 | Virtual paint() is not getting called while drawing Polyline | I am new to Qt, and wants to write code to change Qt's default selection behaviour. So I am trying to override virtual paint method. But paint method is not getting called.
Below code, just print the polyline and paint() tries to change its selection behaviour.
polyline.h
class Polyline : public QGraphicsPathItem
{
pub... | The problem is that you don't create any Polyline object and attach it to the window or a widget.
As such there's just no Polyline object to call the paint function on.
A simple solution it to have your drawPolyline function create a Polyline object instead of the QGraphicsPathItem object you create now:
QGraphicsPathI... |
71,073,069 | 71,073,706 | Some modulo hijinkery | I am solving a question on LeetCode:
You are given two positive integer arrays nums1 and nums2, both of length n.The absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed). You can replace at most one element of nums1 with any other element in n... | The problem is a common mistake with modular arithmetic, and surprisingly, has nothing to do with integer overflow (as is usually the case) but is solely the result of order properties not mixing well with modulus.
You said the distributive property, (a + b) % c = ((a % c) + (b % c)) % c, should let you take moduli ins... |
71,073,166 | 71,073,732 | How to embed an exe file into another exe file as a resource in C++? | I am trying to use a pre-build .exe file as a resource in my C++ project, after searching I done the following steps:
Step1
Create a new C++ project and place the following code in the Source.cpp file
#include<iostream>
#include<Windows.h>
#include<fstream>
#define IDB_EMBEDEXE 52
using namespace std;
int main() {
... | If your #define is already in resource.h, there is no need to duplicate it in your source code. Just use #include "resource.h" in your code instead.
In any case, you should be using the pre-defined RCDATA resource type, instead of creating a custom BINARY type.
That being said, your use of ofstream and system() are bot... |
71,073,222 | 71,073,961 | pcl::PointCloud in shared memory | I'm looking for a way to share a pcl::PointCloud between two processes without using files on the disk.
In particular, I'm interested in using boost shared memory libraries to achieve my scope.
I've just tried the following instruction for the sender:
void * pSharedMemory = ... ; // from wherever
pcl::PointCloud<pcl::P... | The problem is when pointers are used internally e.g. in the vector implementations:
using VectorType = std::vector< PointT, Eigen::aligned_allocator< PointT > >;
using CloudVectorType = std::vector< PointCloud< PointT >, Eigen::aligned_allocator< PointCloud< PointT > > >;
These pointers will only be valid in th... |
71,073,250 | 71,074,005 | Check if a flag is set on an enum field in Azure Cognitive Search using OData Query Syntax | I have to find a way to query (am using Azure search) whether or not a field has a set of flags set without using bitwise and. The reason for the limitation is that Azure Cognitive Search uses OData for querying, which does not support any bitwise operations.
Say we have an enum like so:
public enum PreferredColors
{
... | Azure Cognitive Search doesn't support OData enums, so you'll have to model this scenario with a different data type than Edm.Int32. Depending on how you want to model things in your application, you could use either Collection(Edm.Int32) or maybe Collection(Edm.String). Let's use a string collection for these examples... |
71,073,514 | 71,073,644 | C++ unordered_set insert accepts constructor parameters? | Given these two classes
class User {
string name;
string eMail;
pair<string, string> titleReading;
vector<pair<string, string> > titlesRead;
}
class UserRecord {
User* userPtr;
public:
UserRecord(User* user);
string getName() const;
string getEMail() const;
void setEMail(string eMail... | Your UserRecord::UserRecord(User*) constructor is a converting constructor, which means that it implicitly converts a User* value into a UserRecord object.
If you wish to prohibit this you can mark the constructor as explicit such that no automatic conversion is ever performed implicitly. You will always have to explic... |
71,073,671 | 71,073,829 | How can I print the empty spaces with " | | " until the line ends | I am working with vectors and I wanna know how I can print the empty spaces in between until the line ends.
void print_vector(const std::vector < int > & v, int print_cols, int col_width) {
//dash
cout << string(print_cols * (col_width + 2) + 1, '-');
cout << endl;
//printing the vector in formated output
cou... | void print_vector(const std::vector < int > & v, int print_cols, int col_width) {
//dash
cout << string(print_cols * (col_width + 2) + 1, '-');
cout << endl;
//printing the vector in formated output
cout << "|";
size_t x = 0;
for (x = 0; x < v.size(); x++) {
cout << right << setw(col_width) << v[x] <... |
71,073,872 | 71,073,925 | Unable to push an element of type child to a vector of type base using shared_ptr | Based on this answer, it appears the following code should work:
File Board.h:
std::vector<std::shared_ptr<Piece>> pawnRow;
for (int x = 0; x < 8; x++)
{
pawnRow.push_back(std::make_shared<Pawn>());
}
For reference Pawn.h:
#include "Piece.h"
class Pawn : Piece
{};
Instead I'm getting: error: no matching functio... | As per @Barry's comment, I had to inherit Piece publicly like so:
#include "Piece.h"
class Pawn : public Piece
{};
The code compiled just fine thereafter!
|
71,074,089 | 71,074,386 | How can I take output from the command line and input it into a file using write()? | I am trying to use the write() function from <unistd.h> to stream text from the command line into a file. I have tried multiple things along the lines of:
while(write(STDOUT_FILENO, argv[optind], strlen(STDIN_FILENO)) != 0)
{
write(STDOUT_FILENO, "\n", sizeof("\n"));
}
but continue to get segmentation faults or in... | You would need to read() from STDIN_FILENO into a local buffer, and then write() that buffer to STDOUT_FILENO. But you explicitly said that "I am required to do this without using read()", which means you are pretty much out of luck on this. You can't get input from STDIN without reading from it. If you can't use re... |
71,074,182 | 71,074,241 | Not all of my constructors are being imported? | I'm making a heap class to be importable with heap.h and my constructors including bool types do not work, yet every other constructor and function imported works.
Here is what's in heap.h:
#ifndef __HEAP_INCLUDED__
#define __HEAP_INCLUDED__
#include <iostream>
#include <vector>
using namespace std;
class heap{
int ... | What you are doing with the class in the .cpp file is wrong. You are not allowed to define the class twice. There must only be one class heap { /*...*/ }; in the program (but it may be included in multiple .cpp files). Otherwise the one-definition-rule (ODR) is violated and the program has undefined behavior.
So remove... |
71,074,412 | 71,074,629 | How does a function know what inputs to draw from when labeled under different names? | How can int length and int array[] be labeled differently than int TOTAL and int scores, yet they are recognized as being the same in the average() function? I assumed they had to be called the same thing in order to be recognized?
#include <cs50.h>
#include <stdio.h>
float average();
const int TOTAL = 3;
int main(v... | Variable names in most programming languages have a certain "scope" that they apply to. In C/C++, scopes are often determined by regions between a { and } character, e.g. a function scope or a loop scope within it.
In this specific example, TOTAL is defined in the "global" scope. Anything after that line can see and ac... |
71,075,139 | 71,075,179 | Find std::function by string key in unordered_map | This works:
std::unordered_map<std::string, int> m = {};
auto c = m.find(typeName);
if (c == m.end())
{
}
This works:
std::unordered_map<std::string, std::string> m = {};
auto c = m.find(typeName);
if (c == m.end())
{
}
This doesn't work:
std::unordered_map<std::string, std::function<void>> m = {};
auto c = m.find(... | std::function expects a function type as template argument, while void is not. For example if the function takes nothing and returns void then it should be
std::unordered_map<std::string, std::function<void()>> m = {};
|
71,075,307 | 71,075,422 | C++ compile time ternary conditional | Please, help me to figure out syntax of compile time ternary conditional in C++:
#include <iostream>
#include <type_traits>
int main(void)
{
//const auto y = constexpr(std::is_null_pointer_v<decltype(nullptr)>) ? 777 : 888.8;
const auto y = constexpr(std::is_null_pointer_v<decltype(nullptr)> ? 777 : 888.8);
std::cou... | Although one solution is provided while I program it, I suggest other solution:
making your consteval tenary function template, As it can handle different type in it.
template<bool T,auto A, auto B>
consteval auto tenary() {
if constexpr (T) {
return A;
}
else {
return B;
}
}
#include <... |
71,075,457 | 71,076,966 | Using variables in a function from another function | In function foo() there is a loop that iterates until it finds an optimum set of variables and determines that as the ideal set. The function only returns one variable, in order to pass a unit test.
In the next function bar(), I need to output all of the variables in function foo() as it iterates. First output the opti... | Unless you want to go really fancy (probably not within your reach, yet), foo() has to help bar() a little.
Since you want to show the end result first, then the intermediate data later, you will have to find some way of storing the intermediate states. You could do so, using arrays or lists and push the intermediate v... |
71,075,482 | 71,075,569 | C++ friend operator definition inside class body serves as function declaration? | I'm a newbie reading the C++ Primer book. It says:
A friend declaration only specifies access. It is not a general declaration of the function. If we want users of the class to be able to call a friend function, then we must also declare the function separately from the friend declaration. To make a friend visible to ... | Even if we define the function inside the class, we must still provide a declaration outside of the class itself to make that function visible. A declaration must exist even if we only call the friend from members of the friendship granting class. This means in your example, you should forward declare the function f as... |
71,076,055 | 71,076,736 | Why shared ptr in vector not delete with reserve | class A{
public:
A(){cout<<"constructor"<<endl;}
~A(){cout<<"destructor"<<endl;}
};
int main()
{
{
//case 1
vector<std::shared_ptr<A>> vec;
vec.reserve(1);
vec[0] = std::make_shared<A>();
}
// Not destructor
{
//case 2
vector<std::s... | TL;DR: I guess this is a typo and you meant to call resize(1) instead of reserve(1), but I'd like to explain a bit, because I see how one could easily confuse the two functions.
std::vector has a capactiy (the total slots that can be used) and a size (the number of slots actually used).
reserve() will increase the cap... |
71,076,119 | 71,076,165 | Deduce type from `static constexpr` to `using` | is it possible to "deduce" the type of a static constexpr to a using?
https://compiler-explorer.com/z/hKzqhv7Pa
#include <chrono>
// Bar.h
using Bar = std::chrono::milliseconds;
static constexpr std::chrono::milliseconds BAR{100};
// Foo.h
struct Foo {
// Is there a way to get ride of the `using Bar`... | decltype(BAR) does work. It just returnrs a const type, so the assignment in main fails. Use std::remove_const_t<decltype(BAR)>.
|
71,076,554 | 71,076,895 | How to roll the rows of a Eigen:Matrix? | I want to reindex a Eigen:Matrix by rolling N∈ℤ rows like this (here N=+1):
1 4 7 -> 3 6 9
2 5 8 1 4 7
3 6 9 2 5 8
Is there a simple way, or do I have to create a new matrix and copy over the data?
| I suggest setting up a new matrix and copying the data. Eigen's block operations allow doing this in an efficient way. Here is how a shift by n rows can be done for the example above.
MatrixXi A(3,3);
A << 1, 2, 3, 4, 5, 6, 7, 8, 9;
A.transposeInPlace();
int n = 1; // number of shifts
n = n % A.rows();
MatrixXi B(A.ro... |
71,076,981 | 71,077,215 | Reordering OpenGL Texture vertices to flip image rows | I am a complete OpenGL beginner and I inherited a codebase. I want OpenGL to flip a texture in vertical direction, meaning the top row goes to the bottom and so on. I am only doing 2D processing, if that is relevant.
My texture vertices are currently this:
const float texture_vertices[] = {
0.0, 1.0,
0.0, 0.0,
... | You need to flip the 2nd component of the texture coordinates (swap 0 and 1):
const float texture_vertices[] = {
0.0, 0.0,
0.0, 1.0,
1.0, 1.0,
0.0, 0.0,
1.0, 1.0,
1.0, 0.0,
};
|
71,077,172 | 71,077,413 | Ways to imply return values are not meant to be stored | We can use nodiscard attribute to imply that the return value of a function should not be discarded. Are there any attribute (or other ways) to imply some opposite semantics: the return value of the function should only be used temporarily (by "temporary" I mean, not to assign to any variable except local ones)?
As the... |
[...] is it bad practice to return resources by reference?
It depends. There are many examples of methods that return non-const references and they are all fine. For example consider standard container element accessors. However, they are not meant for encapsulation. std::vector::operator[] is not meant to hide the e... |
71,077,185 | 71,077,417 | Is there any valid method to duplicate sockaddr? | Lets assume that I have used getaddrinfo and resolved an address successfully:
//...
s = getaddrinfo(NULL, argv[1], &hints, &result);
if (s != 0)
return -1;
if (result != nullptr) {
// ....
}
freeaddrinfo(result);
in this case, result->ai_addr and result->ai_addrlen refer to a sockaddr structure and its size... | It seems valid to me. If you want to avoid dynamic allocations, you could also limit yourself to a union of all supported address families. Something like this:
union NetworkAddress
{
sockaddr addr;
sockaddr_in in4;
sockaddr_in6 in6;
static NetworkAddress from_addrinfo(const addrinfo* addr)
{
... |
71,077,289 | 71,080,896 | Microsoft.CppCommon.targets: The specified task executable "cmd.exe" could not be run. Because the file contains a virus | Suddenly my project has stopped to build. I don't even know where should I look to resolve the error?
What I've done I scanned my PC on viruses, added exception in Windows Defender for cmd.exe.
C:\Program Files (x86)\Microsoft Visual
Studio\2019\Enterprise\MSBuild\Microsoft\VC\v160\Microsoft.CppCommon.targets(241,5):
... | In event log I found a suspicious message from RAV antivirus. The problem was in RAV Antivirus. Somehow(?) it got installed on my machine and it was blocking cmd.exe from running.
|
71,077,435 | 71,078,649 | How do I link to a static library (libtiff) using CMake in my wxWidgets project? | For my wxWidgets project, I am trying to make the switch from my self-written Makefile to Cmake. I develop on macOS.
When I was writing that Makefile I ran into an issue with libtiff. I wanted to statically link my application so that I don't have to distribute any dylibs myself or rely on my users to install them. I b... | My search-and-replace idea turned out to be not so bad. I was able to achieve the same outcome with Cmake as with my Makefile.
My problem was not using double quotes in the appropriate place. So instead of this:
string(REPLACE "-ltiff" "/usr/local/opt/libtiff/lib/libtiff.a" wxWidgets_LIBRARIES ${wxWidgets_LIBRARIES})
... |
71,078,344 | 71,101,224 | Trying to use dynamic rendering extension, validation layers complain about missing renderpass | I want to use the dynamic rendering extension to finally be free of renderpasses.
However when i try to make a pipeline my validation layers yell:
required parameter pCreateInfos[0].renderPass specified as VK_NULL_HANDLE
For this createinfo.
vk::GraphicsPipelineCreateInfo pipelineInfo{};
pipelineInfo.stageCoun... | From changelog:
VK_KHR_dynamic_rendering (Note: Validation Layer support is incomplete, incorrect results are possible)
|
71,079,163 | 71,086,072 | Why IDXGIAdapter cannot cast to IDXGIFactory? | I understand that DirectX does not follow the COM standard. However, they look heck of a lot similar, hence my confusion.
For simplicity, I use the word 'COM' very loosely, and I omit all HRESULT handlings, so please bear with me.
Correct code:
Consider the following code.
ComPtr<IDXGIDevice3> g_pDXGIDevice ... | A good place to start is to read through Microsoft Docs: Programming DirectX with COM.
In many cases the DirectX COM components allow you to do just what you say: If the C++ interface class inherits from another one, you should be able to QueryInterface up or down the chain with the same object instance. IDXGIAdapter i... |
71,079,245 | 71,080,432 | Hashing raw bytes in C++? | I want to write a function that takes two types T, U such that sizeof(T)+sizeof(U)<=8 and gets a uint64_t by just reinterpreting their bytes one after the other. However this does not seem to work. I am certain there is a quicker and more elegant (and correct) way to do it but I have no clue. Any tips are greatly appre... | I cannot help with the problem in your code due to lack of details, but I can propose a perhaps simpler solution.
Firstly, I recommend adding a check that the argument objects have unique object representation. Unless that is satisfied, the hash would be meaningless.
Secondly, std::memcpy might make this simpler:
templ... |
71,079,570 | 71,079,690 | Conversion of Infix expression to Postfix | Below is the program i have written to convert a infix expression to postfix. It does give an output but its not always the right one. For example if we input the expression A+B*C-D/F+G , the expected output is ABC*+DF/G+- but rather the program outputs AB+C*D-F/G+. What is the problem in the program.
#include<iostream... | Here:
else if(oper == '*' || '/')
you are using || wrongly. If you consider operator precedence (https://en.cppreference.com/w/cpp/language/operator_precedence) you will see that == has higher rank than ||, hence it is parsed as
else if( (oper == '*') || '\')
The first part will evaluate to true or false but as \ is ... |
71,079,909 | 71,080,280 | Why can't I reuse an event even after explicit ResetEvent call? | I want to watch for changes done with a file (the event i'm waiting for is change contents event, i.e. last modified date is updated)
I have a code like this (minimalized example of actual code)
I expect that each iteration of the while loop the event gets reset and is available to be fired again but that doesn't happe... | Because that's just not how ReadDirectoryChanges works. It doesn't continuously send you changes. It sends you one batch of changes. You process them. You call the function again to tell the system that you want more changes.
I found a correct usage example of the function here: https://gist.github.com/nickav/a57009d4f... |
71,080,269 | 71,125,716 | Xlib how to answer to wrong target in XSelectionRequestEvent? | I'm working on program for sending clipboard contents between different computers.
Now I'm stuck on processing request for sending data from clipboard to requestor on Linux with Xorg.
For example my program is own image/bmp data, but other program send me request for image/png that I'm just ignore. After approximately ... | I just send XSelectionEvent with property field set to None.
// event is event that i responde
XEvent ev;
auto& sel_resp = ev.xselection;
sel_resp.type = SelectionNotify;
sel_resp.display = event.display;
sel_resp.requestor = event.requestor;
sel_resp.selection = event.selection;
sel_resp.target = event.target;
// Set... |
71,080,635 | 71,081,757 | Callback casting and set from another object | I just wanted to ask if my approach is wrong or one is the right way and it can be done.
In the project, I have one hal and several types of Dir based on Base.
When I create some dir I pass hal to it because each dir uses it in its own way.
Everyone also reacts in their own way to events in the hal. so I wanted to use ... | Member function pointers for one class are not convertible to member function pointers of another class, even if the functions look compatible. You can approximate this conversion using a layer of abstraction, for example using a std::function<void(Base*, int)> but it cannot be achieved using a cast.
However, member fu... |
71,080,735 | 71,081,152 | Wrong version number error on *some* websites during handshake with Asio and OpenSSL | I'm trying to send https web requests with Asio and OpenSSL. My code is working fine on most of the sites I tried it on, but on some others, I get an error during the handshake handshake: wrong version number (SSL routines, ssl3_get_record).
I've found some people having this issue because they were behind proxies or b... | You need to be more specific about the server you are trying to connect to:
Live On Coliru
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <iostream>
namespace ssl = boost::asio::ssl;
using boost::asio::ip::tcp;
int main() {
try {
boost::asio::io_context io_context;
tcp::resolver ... |
71,082,265 | 71,082,456 | How can I convert an int (which represents an decimal without its decimal places) to a double in c? | I need to convert integers (which represents decimals but without using decimal places) to doubles in C. I know how many decimal places the integer should have because this information is also there. This new double is handed over to a JSON-API which appends this to a JSON structure afterwards.
Example: I need to produ... | The addNumberToObject doesn't let you control how many significant digits you want to print.
You can get around this by using sprintf to format the number yourself and adding it as a string.
cJSON* addDecimalToJSON(cJSON* const object, const char * const name,
const int number, const int decima... |
71,082,517 | 72,939,704 | Integrate embedded python asyncio into boost::asio event loop | I have a C++ binary with an embedded python interpreter, done via pybind11::scoped_interpreter.
It also has a number of tcp connections using boost::asio which consume a proprietary messaging protocol and update some state based on the message contents.
On startup we import a python module, instantiate a specific class... | There are three possibilities to integrate the asio and asyncio event loops:
Run both event loops in the same thread, alternating between them
Run one event loop in the main thread and the other in a worker thread
Merge the two event loops together.
The first option is straightforward, but has the downside that you w... |
71,082,560 | 71,456,229 | C++ How to map USB Camera device names/paths to USB ports | Is there any way to get all connected USB Camera devices in accordance with the USB port order?
I use something like this to get device friendly names and their paths but it's not ordered(So, I don't know which one connected to which port):
int _GetUSBCameraDevicesList(std::vector<std::string>& list, std::vector<std::s... | Everything is okay, just use std::reverse for the array.
#include <algorithm>
std::reverse(devicePaths.begin(), devicePaths.end());
|
71,082,606 | 71,083,001 | C++ template function, how to handle case where a template types does not have a specific method | In C++, I have a template function which takes an operation type as the type.
The types are operations types in a neural network for example a convolution, depthwise or a MaxPool.
But the types have different methods that can be called on them.
For example. Only convolution or depthwise convolution have a method called... | You could create type traits that you check before calling the different functions.
Example:
#include <type_traits>
template<class T>
struct has_filter {
static std::false_type test(...);
template<class U>
static auto test(U) -> decltype(std::declval<U>().filter(), std::true_type{});
static constexpr... |
71,083,209 | 71,083,736 | How can I convert an array of characters to an integer (for 2 or more digits) | The array has to be entered by the user, and not specified in the app itself.
char coeff[20];
char expo[20];
for (int i = 0; i < Size; i++) {
cin >> coeff[i];
cin >> expo[i];
}
When i enter a number in the cin >> coeff[i] , it doesn't let me enter more than one digit, is there a way to enter more than 1 digit ... | I think your professor wants you to read in text, and then convert that text to a number. This is a silly requirement.
The sensible program would >> into ints directly
int coeff;
int expo;
std::cin >> coeff >> expo;
To read it into intermediate text safely you could
std::string coeff_s;
std::string expo_s;
std::cin >>... |
71,083,862 | 71,084,010 | What happens if you inline a function that calls it self in C++ | First I thought the compile time would take forever, or I take a weird error, but that didn't happen. The code runs for a while and then crashes.
This is my code:
#include <iostream>
inline void say_hello()
{
std::cout << "hello\n";
say_hello();
}
int main()
{
say_hello();
}
I thought the compiler will ... | In modern C++, the inline specifier is only a suggestion to the compiler that you might want to inline the function. The compiler is not required to comply.
For your specific compiler, please see Visual Studio Inline Functions (C++). You seem to "want" the __forceinline decorator combined with #pragma inline_recursion(... |
71,084,193 | 71,084,394 | c++ passing a pointer to a template function as template | I have this iter function that takes a pointer to value_type, a size_type, and a function pointer fun_type that is supposed to take a value_type& as parameter:
template <
class value_type,
class size_type,
class fun_type
> void iter(value_type *arr, size_type size, fun_type function)
{ while (size--) funct... | Your iter function template requires a function for its third template parameter; but print (on its own) is not a function – it's a function template, and the compiler simply cannot deduce what template parameter to use in order to actually create a function … so you need to tell it! Just add the type of the tab array/... |
71,084,462 | 71,086,012 | Is there any workaround for implicit user-defined conversion operator() to be considered when deducing function arguments? | Consider the following example, which tries to pass a std::array to a function. Naturally the "conversion" is not considered, but is there any work-around without having to be explicit? Especially if the class already provides the necessary properties (value_type etc.).
template <typename T, size_t N>
struct Array_t
{
... | Template deduction never considers (user-defined) conversion. Given your:
template <typename T, size_t N>
constexpr bool Test(std::array<T, N> Input);
If you see, in code, Test(x), then that is only ever valid if x is either specifically some kind of std::array or inherits (publicly and unambiguously) from that.
If yo... |
71,084,871 | 71,085,070 | CEF - without rendering | Please explain to me how you can use CEF without rendering pages?
That is, it is necessary that the memory buffer for rendering is not allocated at all.
It seems to write that there is a method CefBrowserHost::Was Hidden - which hides the browser window and the window rendering does not occur.
I use this method:
void O... | The error is pretty clear. When you create a new cef browser, make it using off-screen rendering.
windowInfo.SetAsWindowless(nullptr);
my_CefRefPtr = CefBrowserHost::CreateBrowser(windowInfo, /* whatever */);
|
71,085,267 | 71,085,832 | Must consteval constructor initialize all data members? | In the next program struct B has immediate consteval default constructor, which does not initialize i field. Then this constructor is used to make a temporary and its i field remains untouched:
struct B {
bool b = true;
int i;
consteval B() {}
};
static_assert( B{}.b );
Clang and MSVC are fine with it. Bu... | From cppreference's consteval specifier (since C++20):
The consteval specifier declares a function or function template to be
an immediate function,
...
An immediate function is a constexpr function, and must satisfy the
requirements applicable to constexpr functions or constexpr
constructors, as the case may be.
And... |
71,085,581 | 71,116,691 | QDialog::move() not considering taskbar on Ubuntu with multiple screens | Normally, moving a QDialog using QDialog::move() positions the dialog outside of taskbars.
However, on Ubuntu 20.04 with two monitors it is not the case with frameless Dialogs :
This does not happen if the dialog is not frameless :
This behaviour has been observed on Ubuntu 20.04. It also happens only under some conf... | I didn't find a proper solution or satisfying workaround for this issue, but found a partial solution that is half satisfying :
Before each move() on the dialog, set its flag to Qt::Window (no frameless) and hide it.
Override the moveEvent() handler, set the window flag to Qt::FramelessWindowHint and show it.
Here ar... |
71,085,609 | 71,086,510 | PlatformIO Unidentified reference error to defined attributes | I am creating a project using PlatformIO and a Nodemcuv2 micro-controller.
I have written a class for serial communication SerialCommunicationHandler. This class ICommunicationHandler implements a Interface. See the code below.
ICommunicationHandler.h
class ICommunicationHandler {
public:
virtual void sendTemperatu... | headerfile
#include "ICommunicationHandler.h"
class SerialCommunicationHandler : public ICommunicationHandler {
private:
//atributes needed for storing and modifying incoming data.
static char incomingData[6]; //char array to temporarily store incoming data.
static char receivedData[6]; //char array to copy incoming d... |
71,085,706 | 71,085,978 | Copying an object with a polymorphic member in C++ | I wish to express that each object of type V owns an object of type B. B is a polymorphic type, and is therefor accessed through a pointer or reference to prevent slicing (C.145). I find it natural to express this as following
class B {};
class V {
public:
unique_ptr<B> p;
};
I can now der... | You need to ask yourself a question : Why should B not be copyable?
The example you described, with a graph owning one (or probably multiple) vertexes shows the opposite : B should be copyable!
What you don't want is two graphs sharing the same vertex instance.
So you can create a copy constructor / clone method for V ... |
71,085,927 | 71,086,599 | How to extend ESP32 heap size? | I'm writing a code about play gif from SDCard on TFT Screen, so I create a array to put the gif file. (Using Nodemcu-32s 4MB)
#include<TFT_eSPI.h>
#include<SPI.h>
#include<AnimatedGIF.h>
TFT_eSPI tft;
AnimatedGIF gif;
uint8_t *gifArray;
int gifArrayLen;
void setup(){
tft.init();
tft.setRotation(2);
tft.fillScre... | The "4MB" in NodeMCU refers to the size of flash, the size of RAM on ESP32 is fixed at 512KB, roughly 200KB of which is used by IRAM cache/code sections, leaving around 320KB for program memory, half of which is available for dynamic allocation.
From documentation Heap Memory - Available Heap:
Due to a technical limit... |
71,086,157 | 71,086,310 | Why don't we use const char* const for constant strings? | The standard way to store a constant string in C++ is to use const char*.
In the interest of precision and correctness, why don't we write const char* const?
Is this just because people are too lazy to write the extra const, or because it really does have some disadvantage?
EDIT: I guess I should have been more clear, ... | A variable of type int can easily be modified by accident, by passing it to a function that takes int&. This is "invisible" at the call site, in the sense that calling a function that takes int& looks the same as calling a function that takes int or const int&. To guard against this, we make the variable const if possi... |
71,086,811 | 71,087,717 | Is it possible to achieve desired permutation of values for vertices with adjacent swaps? | Consider an arbitrary connected (acyclic/cyclic) undirected graph with N Vertices, with vertex numbered from 1 to N. Each vertex has some value assigned to it. Let the values be denoted by A1, A2, A3, ... AN, where A[i] denotes value of ith vertex. Let P be a permutation of A. Each operation, we can swap values of two ... | Indeed this is possible. Since we've got a connected graph, we can remove edges until you've got a tree. Removing an edge simply means we won't use it to do adjacent swaps in this case. "Removing a node" simply means we'll never swap the value of the node.
Now we can use the following algorithm to produce the permutati... |
71,086,883 | 71,087,021 | Equality of reference types in template parameters | The C++ standard says in [temp.type]#2.7, that
Two values are template-argument-equivalent if they are of the same type and
...
(2.7) they are of reference type and they refer to the same object or function
This is different, than how reference types are compared in non-template code. Say e.g.
template <auto& x1, aut... | For the purposes of template argument equivalence, the question we want to be asking is "are these two arguments identical?" rather than "are these two arguments equal?"
References to two different variables that have the same value might be equal to each other, but they aren't identical: one may not be substituted for... |
71,087,391 | 71,087,620 | C++ Lambda - Loop over integer array | I'm trying to loop over an integer array using a lambda template.
The code to invoke the lambda would look something like this (demo purposes, not functional code):
menu.option("Set Pedestrian Health to 0").allpeds(ped => {
SET_ENTITY_HEALTH(ped, 0);
});
The problem: how would I make the allpeds lambda template?
... | The example you have shown is more C# than C++, as far as the lambda syntax is concerned. But even then, the example is clearly passing the lambda as a parameter to allpeds(), and the lambda itself takes an input parameter, too. allpeds() is not returning an array that the lambda then iterates, allpeds() calls the lam... |
71,088,814 | 71,189,381 | Signal_delete_event doesn't change page in notebook with set_current_page | I'd like to change to a certain page in a notebook when deleting the window and do some work before effectively deleting the window.
The code below gives 1 for get_current_page, but the page isn't effectively changed to 1.
What should be the solution to this problem?
Form::Form()
{
add(box);
notebook.set_size_... | Sorry for the late answer, your question made my work more than I thought!
Working with the Glib::TimeoutSource class (which is ridiculously under documented...), I was able to hack my way around this limitation.
Basically, my strategy was, on a single click, to run the delete-event signal handler two times:
once to u... |
71,089,051 | 71,089,149 | Why is binary_search not working as expected? | The question is to find the index of first element in the array that repeats itself atleast once in the array.
Input:
7
1 3 4 5 3 7 2
#include <bits/stdc++.h>
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int n;
cin >> n;
int a[n], curr = -1;
int num = sizeof(a) / sizeof(a[0])... |
cin >> n;
int a[n]
This isn't allowed in C++. The size of an array variable must be compile time constant. n is not compile time constant. To create an array of runtime length, you must allocate it dynamically. Simplest solution is to use std::vector,
int num = sizeof(a) / sizeof(a[0]);
Use std::size(a) to get t... |
71,089,349 | 71,089,392 | Need help on SFINAE on class template T | I'm writing a template class Foo<T> which I only want to allow certain types of T. I have been playing around for quite a while and now the class compiles, but in the presence of a second template non-type parameter, I couldn't figure out how to instantiate it correctly. How can I give it a default value so that I can ... | std::enable_if_t<true> gives you a void type. Then you're trying to do something like
template<typename T, void = 0>
which doesn't work for an obvious reason. You can kind of fix the problem with std::enable_if_t<..., int>.
But note that you're not doing SFINAE here. Substitution will be a hard error in your example -... |
71,090,104 | 71,090,890 | Is there a way to create two Classes that needs each other in during their Initialization process? | I have a program where two classes need each other in their Initialization process, but so far all I get is Compilation Error and I have no idea how to make it work
in Class MainComponent
class MainComponent : {
private:
PlaylistComponent playlistComponent{formatManager, *this};
}
in Class PlaylistComponent
... | You need something like this(forward declaration: because you didn't show us how you used forward decleration I show that again here):
//in A.h file
class B;
class A{
B* b; // or anything else that dont need definition here and just need definition in cpp file.
}
//in B.h file
class A;
class B{
A* a; // or a... |
71,090,871 | 71,090,957 | C++ shared_ptr and mutex | I'm new to C++ and I have to following scenario:
main.cpp
#include "Foo.h"
#include "Bar.h"
int main() {
Bar bar{};
auto bar_ptr = std::make_shared<Bar>(bar);
for (int i = 0; i < 10; i++) {
Foo foo{bar_ptr};
}
return 0;
}
I want 10 Instances of Class Foo to share 1 Instance of Class Bar.... | std::mutex is a move-only type, so you can't copy it.
In your main function you are creating a Bar, and then trying to create a std::shared_ptr by copying that instance of Bar.
Instead, just use std::make_shared<Bar>() to create a shared_ptr to a bar with the default constructor.
#include "Foo.h"
#include "Bar.h"
int ... |
71,091,790 | 71,092,275 | How to traverse a trie to display all the words? | Here's my declaration of a trie in C++ using unordered_map
class trie{
public:
unordered_map<char,trie*>m;
bool isEnd;
};
Here's my insert function(part of another class)
trie *root=nullptr;
trie *getNode()
{
trie *tmp=new trie();
tmp->isEnd=false;
return tmp;
}
voi... | void iterate_(const trie* node, const std::string& prefix) {
if (node->isEnd) {
std::cout << prefix << std::endl;
}
for (const auto& [c, child] : node->m) {
iterate_(child, prefix + c);
}
}
void iterate() {
if (root) {
iterate_(root, "");
}
}
|
71,092,040 | 71,092,163 | Copy elision in initializer list? | Consider this class
class A {
public:
tracker tra;
A(tracker _t) : tra(_t) {}
};
And call it through
A a {tracker()};
The object created by tracker() is never used until being stored in a.tra
Why don't the compiler optimize all the copy constructions away?
.
The tracker is defined here:
class tracker {
public... | The compiler can't optimize out the copy construction of tracker in this case because the copy constructor and the destructor of tracker has observable side-effects. If the compiler optimizes out the copy construction ignoring that, it will change the observable behavior of the program thus violating the as-if rule.
Th... |
71,092,227 | 71,092,257 | Cannot change class objects within vector | I'm having difficulties with understanding how to change the value of a class object which is stored in a vector. From the example below, I thought the case would be that "ferrari" would be yellow after I change the color, however it is still black.
From what I understand this has to do with that I'm making a new copy ... | In for (Car car : cars), car is a copy of the corresponding vector element. Changing the copy doesn't affect the original.
Use for (Car &car : cars) if you want to modify the elements. Even if you only want to read (print) them, use for (const Car &car : cars) to avoid the unnecessary copy that you're currently making.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.