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 |
|---|---|---|---|---|
63,665,787 | 63,665,982 | How to delete a line of text in C++ using regex | I'm trying to define a method that deletes an entire line in a block of text containing a string passed to it.
#include <regex>
void removePlaceholder(std::string& element, const std::string& placeholder)
{
std::regex placeholderLine("\n.*" + placeholder);
std::regex_replace(element, placeholderLine, "");
}
T... | regex_replace returns the modified string, it doesn't modify the passed in string in place.
I presume you also want to add a newline at the end of your regex too so that it matches the whole line rather than stopping at the end of placeholder.
You should probably also make the * non greedy to prevent matching more than... |
63,666,217 | 63,666,384 | prevent 'delete[]' from source object's destructor from releasing our 'just stolen data' | From: https://stackoverflow.com/a/3109981/462608
string(string&& that) // string&& is an rvalue reference to a string
{
data = that.data;
that.data = nullptr;
}
What have we done here? Instead of deeply copying the heap data, we have just copied the pointer and then set the original pointer to null (to prev... | Take the snippet before the quote. You may know string would delete[] data when it destructs.
~string()
{
delete[] data;
}
Without that.data = nullptr, when that destructed, it would release that.data aka this->data because of data = that.data;.
"Source" in the link means that.
|
63,666,273 | 63,666,327 | Delete elements in a std::vector<std::string> which matches with the characters in another given std::string | How can I remove elements in the vector alphabets which matches with any of the characters in the string plaintext?
Here's my attempt:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
int main()
{
//init
std::vector<std::string> alphabets{ "a", "b", "c", "d", "e", "f", "g", "h", "i", ... | The *it has a type of char not std::string. This is what the compiler complaining about. Therefore you need to pass a std::string to the std::find as follows.
auto toErase = std::find(alphabets.begin(), alphabets.end(), std::string{ *it });
// ^^^^^^^^^^^^^^^^^^... |
63,666,660 | 63,674,006 | C++ stream becomes bad if called in multiple shared libs and libstdc++ static linking is enabled | I compiled 2 shared libs with --static-libstdc++ enabled.
The 2 shared libs have the same function f, which just outputs a string and an integer to stdout.
Main program will load the 2 shared libs using dlopen, and call the f in it using dlsym.
However, the second loaded shared lib failed to output the integer and the ... | Finally I found a way to resolve the issue in Linux (GNU Extensions).
Use dlmopen which provides better isolation btw objects.
auto dll = dlmopen(LM_ID_NEWLM, dll_path, RTLD_LAZY);
Great thanks for all commenters!
Still welcome to explain the details about what the conflict states are.
|
63,667,096 | 63,667,549 | Replacing a substring with a space character | I am given a string and I have to remove a substring from it. Namely WUB, and replace it with a space character.
There are 2 WUB's between ÁRE' and 'THE'. SO the first condition in if statement is for not printing two blank spaces but on executing the code two blank spaces are being printed.
Input: WUBWEWUBAREWUBWUBTH... | There are actually three bugs here, so it's probably worth to conclude them in one answer:
The first condition:
if (s[i] == 'W' && s[i+1] == 'U' && s[i+2] == 'B')
is out of bounds for the last two characters. One fix would be to check the length first:
if(i < s.length() - 2 && s[i] == 'W' && s[i+1] == 'U' && s[i+2] =... |
63,667,255 | 63,667,672 | Plotting graphs in C++ | I have made the following graph using matplotlib in python.I have also attached the code I used to make this.
The code for the arena
import matplotlib.pyplot as plt
import matplotlib.patches as patches
obs_boundary = [
[0, 0, 10, 600],
[0, 600, 900, 10],
[10, 0, 900, 10],
... | You could try https://github.com/lava/matplotlib-cpp, which looks like it is just a wrapper around matplotlib anyway, so you are still calling/using Python and matplotlib in the end. With this you probably can copy your code nearly verbatim to "C++".
|
63,667,542 | 63,667,612 | Is it legal to assign heap allocated class object to stack allocated object in C++? | In C++ we can assign heap allocated object of class to stack allocated object by dereferencing it. It looks like there is no problem and it works as expected even destructor works well, but is it good or bad to write code like this?
#include <iostream>
class cls {
public:
cls(int n) : pInt{new int{n}} {
st... | They copying is okay, but note that the compiler-generated copy-constructor will do a shallow copy.
That means, the pointer is copied, not what it points to. That leads you to have two objectd with the exact same pInt pointer, pointing to the exact same memory. And you can only delete that memory once.
This is the reas... |
63,668,081 | 63,668,240 | c++ thread worker failure under high load | I have been working on a idea for a system where I can have many workers that are triggered on a regular basis by a a central timer class. The part I'm concerned about here is a TriggeredWorker which, in a loop, uses the mutex & conditionVariable approach to wait to be told to do work. It has a method trigger that is c... | What happens when worker.trigger() is called twice before workLoop acquires the lock? You loose one of those "triggers". Smaller time gap means higher probability of test failure, because of higher probability of multiple consecutive worker.trigger() calls before workLoop wakes up. Note that there's nothing that guaran... |
63,668,328 | 63,668,552 | How can I make animated colormap plot of C++ arrays? Export to Python and use \matplotlib? | I have a C++ code which creates an array at each time. (C++ is needed because of the speed - if the code was built directly in Python, it would take 8 days to execute.) The structure of the code looks something like:
const int StopTime = 10000;
int main(void){
int Time = 0;
while(Time<StopTime){
//Crea... | The quick and dirty approach to such a problem is often to generate python code from your primary program. Here your C++ program. For example, the string [0, 3, 5, 1] is a valid python fragment defining an array of four values.
So, if you have your std::array<T,N> or your T[N] or std::vector<T> with your data, you can ... |
63,668,490 | 63,668,860 | Template functions' order invoke a compilation error for no reason | so this works fine:
template<class V>
void bar(V v1, V v2) {
}
template <class T>
void foo(T t1, T t2) {
bar(t1, t2);
}
int main() {
foo(5, 6);
}
but if i change the order of foo and bar like this:
template <class T>
void foo(T t1, T t2) {
bar(t1, t2);
}
template<class V>
void bar(V v1, V v2) {
}
int m... | You would get a compiler error from this code for the very same reason:
void foo(T t1, T t2) {
bar(t1, t2);
}
void bar(V v1, V v2) {
}
int main() {
foo(5, 6);
}
You cannot call bar before it is declared. Solutions: Either declare bar before you call it, or move the whole definition of bar before foo.
|
63,668,997 | 63,669,818 | What is the advantage of std::enable_if over static_assert for class templates? | I was wondering about the advantage of std::enable_if over static_asserts to prevent template instantiation. This answer suggests, that std::enable_if allows SFINAE, which is a convincing argument in the case of function templates.
However is this argument legitimate for class templates (and variable templates)? As far... | Handling a few distinct types can be done with specialising as you said:
template <class>
class foo;
template <>
class foo <int> { /* int implementation */ };
template <>
class foo <char> { /* char implementation */ };
Now consider that we want to specialise multiple types, and we want float and double to be in the ... |
63,669,700 | 63,669,757 | Code works completely fine in Hackerrank but when printed out in my command prompt, it gives complete different outputs | I am new to C++ and I've been learning how to use Vim recently as my text editor. I was doing a really basic task on Hackerrank which inputted an int, long, char, float, and double separated by a space between them and the program had to output all of the values accordingly with the float value going up to 3 decimal pl... | It looks like your code relies on long to occupy 64 bit. Which is often is not true. For example on 32 bit vc++ programs it occupies 32 bit. So you should use long long instead or (better) fixed size types from standard library, such as ::std::int64_t.
|
63,670,711 | 63,670,882 | C++ Memory violation error when trying to use function with variable of arguments | I want to create a function, that will log information to a file. This function needs to get some number of arguments and should iterate over them and print them to console. I have the following code:
void log(int argnum ...)
{
va_list arguments;
std::string argval;
va_start(arguments, argnum);
for (in... | Frankly, your code is a bit messy. You declared log to take parameters of type int:
void log(int argnum ...)
You then try to get them as std::strings:
argval = va_arg(arguments, std::string);
And you try to call the function with parameters of type int and const char[]. Moreover, you seem to have a misconeption a... |
63,670,784 | 63,678,038 | _CRTDBG_MAP_ALLOC not showing file name and line number | I use Visual Studio 2017. I work with a dynamic library which dumps memory leaks:_CrtDumpMemoryLeaks(); I have added an appropriate macro definition:
#define _CRTDBG_MAP_ALLOC
but an output still doesn't contain a file name and line number. When I debug that dll I can step into
the following malloc definition:
//
// m... | The technique described in the docs Find memory leaks with the CRT library.
The key point is in that you need to add the following 3 lines before any #include:
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
|
63,671,058 | 63,674,202 | STL list function that deletes N'th element from list and replaces it with M'th element from the same list C++. Must use re-linking | so I've come across a problem, i am able to delete the N'th element using the code below, but i have completely no idea how to re-link links in order to get my desired result.
An example with the result needed. So the list is {1,3,5,4} i need to be able to pass 2 parameters to function N and M. For example N is 2 which... | I think if you work a tad you'd be much better of with the solution that rcgldr offered.
That being said, if you're keen on using your homemade list and not using C++ much at all really, you can try something along these lines:
Caution, this solution is way less elegant than something using std::list (again, see rcgldr... |
63,671,349 | 63,685,867 | How to build an example cppkafka using qmake & mingw? | I need to get away from cmake, so I want to build a qmake project on mingw. Please help me understand what is missing. Build CPPKafka from https://github.com/mfontanini/cppkafka
main.cpp
#include <cppkafka/cppkafka.h>
using namespace std;
using namespace cppkafka;
int main() {
Configuration config = { // Create ... | You need to add dllexport to the struct HandleDeleter and rebuild.
before include\cppkafka\kafka_handle_base.h:
struct HandleDeleter {
explicit HandleDeleter(const KafkaHandleBase* handle_base_ptr) : handle_base_ptr_{handle_base_ptr} {}
void operator()(rd_kafka_t* handle);
private:
const Kaf... |
63,671,591 | 63,672,053 | Wait for Named Pipe to be read before Disconnecting | I have a program written in Python that I need to contact from a C++ Program. I'm creating the Pipe Server on the C++ program with the client being in Python. I can't wrap my head around how to properly read/write between the 2 programs as each time I try a different behavior occurs. Note that I want the pipe to remain... | I think there is a problem with Python f.read() and Windows pipes. Maybe I missed something but it looks like there is no EOF when you read a pipe like you do, and python read() will read past the end and error, even though it read everything correctly before.
To work around this, you can use a buffered pipe (open(r"pi... |
63,671,750 | 63,672,323 | Meaning of "Instances of types are called objects" | I am currently reading the book Modern C++ for Absolute Beginners by Slobodan Dmitrović
that has the following statement in the chapter types:
Every entity has a type. What is a type? A type is a set of possible values and operations.
Instances of types are called objects.
So bool, char, int, ... are all type's.
What... | In simple language when it says : Instances of types are called objects it means, when you have defined a prototype or a blueprint and you want to use that blueprint you need to declare an object of that type.
You have different types.
Primitive data type like int, long, char, short etc
User defined data types like ... |
63,672,002 | 63,672,995 | Why does MSVC 2019 fail when returning a statically-sized array in a ternary? | I am trying to compile some library code and ran into an error; I simplified the example and I have the following MVCE which fails to compile with MSVC 2019 with the error
error C2440: 'return': cannot convert from 'const char *' to 'const char (&)[20]'
static constexpr const char somethingWeird[] = "Well, that's odd... | A bit of googling shows this is know problem which is claimed to be fixed (but it is not).
C++ Overly aggressive decay of static array to pointer in ternary operator - Developer Community
Solution
by Leo Zhang [MSFT] Sep 07, 2017 at 02:35 AM
Thank you for your feedback! This issue has been fixed and it will be ava... |
63,672,176 | 63,672,976 | Efficient function selector once at runtime | I have an operation that I need to perform many times in parallel. For example interpolate an image at a cloud of points. For this operation I have a few variants. For example different interpolation functions (think linear, quadratic, cubic, etc.). The question is, how to efficiently select the operation once during r... | Probably both options should be roughly the same. If performance is really important, just measure your code. I did a benchmark and ifs were as fast as pointer.
Keep in mind that if you use a function pointer, you have an indirection, and with the "if" statement branching should not be a huge problem, as branch predict... |
63,672,254 | 63,701,747 | .mll file doesn't work on another user's computer - maya 2019 | I'm a newbie at maya c++ API making.
I made a byte of maya c++ api to my computer with Visual studio.
My .mll filetype worked well on my computer with devkit using mel(loadPlugin ~~).
But when the code is run on other computer, it doesn't work. I get the error:
//Error: line 2: Unable to dynamically load : C:/Users/use... | These types of error have two reasons in most cases: 1. Build in debug mode, not release mode. Debug mode will rely on debug libraries which are only available if the development environment is installed on the computer, e.g. VisualStudio. 2. The plugin needs an additional library, e.g. a alembic reader will need the a... |
63,672,515 | 63,678,465 | Timezone not recognized after SetTimeZoneInformation on Windows 10 | I am trying to change timezone on Windows 10 using Windows API and by following the documentation. I am passing timezone bias, standard name and daylight name that are for sure in the Registry as accepted timezones ("Central Europe Standard Time" and "Central Europe Daylight Time"). Clock is being set to correct time b... | A few things:
Don't use SetTimeZoneInformation, as it doesn't support the complete "dynamic" time zone information that is used in modern Windows. Use SetDynamicTimeZoneInformation instead. (The docs are slightly misleading in this regard, as this has been the case from Windows Vista and newer, not just Windows 7 an... |
63,672,599 | 63,672,779 | How is std::atomic<T>::operator= implemented for immutable types? | I've learned that one way to communicate between threads is to share some atomic data structure. For example:
struct Point {
int const x, y;
};
std::atomic<Point> some_point_in_shared_memory{Point{0, 0}};
Despite Point::operator=(Point const &) being deleted, there seems to be no problem calling the assignment op... | From cppreference:
The primary std::atomic template may be instantiated with any
TriviallyCopyable type T satisfying both CopyConstructible and
CopyAssignable. The program is ill-formed if any of following values
is false:
std::is_trivially_copyable<T>::value
std::is_copy_constructible<T>::value
std::is_move_construct... |
63,672,720 | 63,672,850 | Will compiler unroll "for" loop when iterating a const container? | In C++11, we can use a much simpler "for" loop when iterating a container like the following:
for (auto i : {1, 2, 3, 4})
...;
However, I don't know the efficiency of such code. Specifically:
What is the type of {1, 2, 3, 4}? It is an raw array, or converted to other containers such as std::vector?
Will compiler ... |
What is the type of {1, 2, 3, 4}?
std::initializer_list will be constructed from that initialiser. That is being iterated. You even need to include <initializer_list> for this to work.
Will compiler unroll the loop?
The language doesn't guarantee loop unrolling. You can find out whether a particular compiler unroll... |
63,672,998 | 63,673,252 | How is SFML so fast? | I need to draw some graphics in c++, pixel by pixel on a window. In order to do this I create a SFML window, sprite and texture. I draw my desired graphics to a uint8_t array and then update the texture and sprite with it. This process takes about 2500 us. Drawing two triangles which fill the entire window takes only 1... | Graphics drawing in modern devices using Graphic cards, and the speed of drawing depends on how many triangles in the data you sent to the Graphic memory. That's why just drawing two triangles is fast.
As you mentioned about multithreading, if you using OpenGL (I don't remember what SFML use, but should be the same), w... |
63,673,079 | 66,087,420 | CMake does not accept MinGW compilers | I just started using CMake so I tried to build a simple hello-world project and got an error.
There is a main.cpp file, which contains this:
int main()
{
return 0;
}
And a CMakeLists.txt, which contains this:
cmake_minimum_required(VERSION "3.18.0")
project("test")
add_executable("${PROJECT_NAME}" "main.cpp")
i... | Be sure not to use non-Latin characters in the absolute path to your working directory. In my case it was Cyrillic "C" as the name of folder.
|
63,673,138 | 63,673,199 | Problem in Finding Prime Numbers between Two numbers | I have to find all prime numbers between two given numbers(given in ascending order i.e small, large) I made logic such that my program starts from the given least number till the given most numbers and find factors for each number in between, if factors count are 2 i.e 1 and itself(which is a condition for a prime num... | Your program has several issues.
cin>>start,end; is not going to read in 2 numbers. You need cin >> start >> end;
You are not initializing count to anything, so you invoke undefined behavior when you do count++. You need to do int count = 0;
Also, when checking if n is prime, you don't need to check for divisibilit... |
63,673,655 | 63,674,483 | C++ template that differentiates static arrays, pointers and structs | Currently I have a template function that compiler can deduce TI for static arrays and pointers (of common types) as arguments:
template<typename TI, typename TO>
inline void foo(const TI a[4], TO b[][3]) { /* works for static arrays and pointers */ }
However, now I need to have the same function for a struct type wit... | What you can do is to use type traits available as from C++11
You can declare your function dedicated for structures as follows:
#include <type_traits>
template <class QT, typename TO, std::enable_if_t<std::is_class<QT>::value, int> = 0>
inline
void foo(const QT q, TO a[][3])
{
std::cout << "Method 2\n";
a[0][... |
63,673,846 | 63,674,063 | How do I make my program stop having build issues and make it stop using negative numbers? | My program needs to be able to calculate the monthly phone bill and there are 3 plans: Basic where 10 hours are free and it costs 9.95, Gold where 20 hours are free and it costs 14.95, and Platinum where you have unlimited hours and it costs 19.95. When my program is given hours less than the free hours it subtracts th... | The problem is in these lines:
basicHours = (hours - 10);
goldHours = (20 - hours);
extraBasic = (basicHours * 2);
basicCost = (9.95 + extraBasic);
goldCost = (14.95 + goldHours);
Think about what they are doing.
basicHours = (hours - 10);
If hours was 11, then basicHours is now 11 - 10 = 1. T... |
63,674,493 | 63,674,688 | Sending processor rank generated using C++ and Open MPI to Python script | I am a beginner C++ and MPI user. I am working in an HPC environment and need to do the following:
Use a C++ code to get the processor rank.
Pass rank to a bash script.
Feed a python script this rank value and run it (from the bash script).
This is the code I have written:
C++ (file name- cpp2bash_test.cpp):
#include... | Note that for most queue systems, there are system variables being set that indicate process rank. Once inside your script (that is started as MPI) you should be able to get it from the environment (you have to look into your queue system manual).
Another way is to produce some wrapped log and grep for the info, e.g.:
... |
63,674,861 | 63,675,791 | Can I have multiple users in SQLCipher? | I am using SQLCipher in a c++ project. It has multiple users and each one has to have their own database credentials. Can SQLCipher do this for me? If yes, please leave a sample code. If no, please share your opinions of how to do it.
| No, you cannot. It looks like SQLCipher uses a key derivation function to turn your password into a key that is applied per page of the SQLite database.
What you can do instead is the usual trick to enable multi-party encryption:
Encrypt the database with a completely random key k;
Store tuples of (user, encrypt(k, us... |
63,675,243 | 64,066,688 | what '-DLOCAL' flag does in C++ compilation | I want to know what -DLOCAL flag of C++ compilation does ?
which is used as :
g++ -std=c++17 -Wshadow -Wall -o "%e" "%f" -g -fsanitize=address -fsanitize=undefined -D_GLIBCXX_DEBUG -DLOCAL
thanks in advance.
| one use that I found is compiled with -DLOCAL flag allows us to run a statement like cerr, which is for testing
cerr << "some variable for testing";
if we remove -DLOCAL flag in the compilation, cerr will not be showing any output on the console.
this is helpful even we forget to remove all those testing statements it ... |
63,675,593 | 63,675,606 | I cant' seem to catch this exception in C++ | For some reason the program exits when executed while testing the handling of an exception. This is the class im using as the exception recipient
#ifndef _BADALLOC
#define _BADALLOC
#include <cstring>
using namespace std;
class badalloc{
private:
char* Message;
double Number;
public:
explicit badalloc(... | Very simple, you are copying to an uninitialised pointer Message in your badalloc class.
You'd get this error just by constructing a badalloc object. This has nothing to do with exceptions.
EDIT
Here's a possible solution, using std::string to avoid the pointer problems.
#ifndef _BADALLOC
#define _BADALLOC
#include <s... |
63,675,959 | 63,676,078 | How to pass runtime class to AfxBeginThread | Class A
{
method1()
{
m_GetDataThread = AfxBeginThread(B::method2, RUNTIME_CLASS, THREAD_PRIORITY_BELOW_NORMAL, 1 << 20, STACK_SIZE_PARAM_IS_A_RESERVATION);
}
}
Class B
{
method2()
{
----------
}
}
Here if RUNTIME_CLASS was Class A, I can just pass this in place of R... |
AfxBeginThread has two overloads, one takes function or static method, another takes runtime class, they are mutually exclusive. And none takes non-static method (and such function that would take it without this could hardly exist)
RUTNIME_CLASS macro takes class name as a parameter, so the problem you are asking of ... |
63,676,340 | 63,676,488 | C++: How to overcome memory issues using large int/double? | I am using CERN ROOT 6.22. I am reading ~1000000 rows of data from a file. Whenever the value in the first column >= 40000, I want to continue the loop without reading the values from that row into vectors. Here is a minimal version of my code:
# include <iostream>
# include <fstream>
# include <math.h>
# include <ioma... | The problem is here:
for(int i = 1; i < NumOfLines; i++){
inFile>>tempTime>>tempTimestamp;
if (tempTime < LimitForGood){
time.push_back(tempTime);
timestamp.push_back(tempTimestamp);
cout<<time[i]<<setw(20)<<timestamp[i]<<endl;
}
}
Before the loop you already pushed... |
63,676,573 | 63,677,076 | Remove adjacent Duplicates from a String which have count greater than or equal to burst Length | Given a string with repeating characters and a burst length, output the string such that the count of the same adjacent characters in the string is less than the burst length.
Input : abbccccdd, burstLen = 3
Correct Output : abbdd
My Output: abbd
Input : abbcccdeaffff, burstLen = 3
Correct Output: abbdea
My Output: ... | It would be better at least to use the container adapter std::queue instead of std::stack because there would not be a need to call the algorithm std::reverse.
Moreover if items of the stack contain the second data member that stores frequencies then you could just increase this data member for repeated characters ins... |
63,677,341 | 63,678,299 | Best way to find distance between beginning of string_view and its underlying string | Given an std::string s and std::string_view s_view. What is the "best" way to find the distance between the beginning of s_view and s? By "best" I mean what works safely for all of the main C++ compilers?
The two options I can think of are illustrated by the code example below. I am unsure if these two ways of doing it... | std::string_view has no concept of the std::string it is viewing. All it knows is the starting char* data pointer it was given.
It is undefined behavior to compare iterators from different containers, even if they refer to the same underlying data.
So, your only option is to compare raw pointers, like you do in your "... |
63,677,394 | 63,678,011 | Is Shared memory crash safe? | I want to share data between two or more processes in very efficient manner. I'm using C++ and boost.Interprocess. Here are the processes :
Process A : Creates shared memory and write to it afterwards.
Process B : Reader that reads from shared memory
Process C : same as process B
Constraints:
Size of the shared memor... | Request to the OS a segment to share and don't run any process until the program gets a valid one. Initialising the segment will allow process B to know if process A has written different values.
Unless you are absolutely sure that process B is not going to read the memory before process A has finished, synchronisation... |
63,677,426 | 63,677,494 | Accessing common struct members in std::variant | I have trouble understanding how to use std::variant in C++17. Given two struct A and B, and a std::vector<std::variant<A,B>> vs, I would like to:
Refer to a common struct member, e.g. n;
Call a common function, e.g. fun() or add().
#include <iostream>
#include <variant>
#include <vector>
struct A {
int n;
v... | Use std::visit with a lambda that has an auto&& parameter to access members that are common to all variant types. In your example:
for (auto&& v : vs) {
std::visit([&](auto&& x){
std::cout << x.n << x.add(1);
x.fun();
}, v);
}
|
63,677,531 | 63,695,601 | Determine type of template parameter in Visual Studio 2008 without overloading | I know this question was asked before, but I am trying to specifically find out if it could be resolved in Visual Studio 2008 SP1 (C++ version 9), without function overloading, and without boost or other 3rd party library.
template<typename T>T foo()
{
#if (T is char*) // return something
#elif (T is int) // re... | That's what I was looking for:
template <typename T,typename U>
struct is_same
{
static const bool value = false;
};
template <typename T>
struct is_same<T,T> {
static const bool value = true;
};
class INI
{
public:
. . .
template<typename T> T getValue(LPCTSTR path, T deflt);
template<bool> ... |
63,677,859 | 63,678,015 | Is there any way to make SendInput set the LLKHF_INJECTED flag? | I'm interested to know if there was a way to make SendInput set the LLKHF_INJECTED flag in a low level keyboard hook. I'm pretty sure macro apps have some way to do this, but I'm not sure how. Is there a C++ Windows alternative, or do I need to configure my INPUT differently?
| Calling SendInput will set the LLKHF_INJECTED flag, as observed by a low-level keyboard hook. You do not need to do anything special. After all, the sole purpose of SendInput is to inject input.
This is explicitly spelled out in the LowLevelKeyboardProc documentation:
If the input comes from a call to keybd_event, the... |
63,678,081 | 68,055,608 | Botan MC-Eliece implementation fails because of deprecated implementation example | I have problems with my c++ mc-eliece implementation from Botan crypto library. There seems to be virtually only one example of it in the whole internet, with a link to it.
https://www.cryptosource.de/docs/mceliece_in_botan.pdf
But this example is 6 years old, hence it is totally outdated and the Botan docs do not prov... | I have now updated the example code in https://www.cryptosource.de/docs/mceliece_in_botan.pdf to reflect these the changes to Botan's new KEM API.
Please note that it is unnecessary to provide a salt value for the KDF when used in the context of a KEM for a public key scheme such as McEliece. That the KDF can accept a ... |
63,678,681 | 63,678,753 | Close DLL file handle opened by LoadLibrary | How can I close the file handle opened by a LoadLibrary call on a .dll while keeping the library loaded? FreeLibrary will not work for example.
In my case there is a program I want to keep open that has the DLL open, but I don't want to close the program each time I recompile and replace the DLL. I don't care if the pr... | It's not possible because a "loaded" DLL is a memory mapped file. This means that "closing the handle" would remove it from memory because it's not copied to memory, only mapped.
This is why DLLs are so memory efficient as long as all programs use the exact same file - it (almost) doesn't cost any extra memory to load ... |
63,678,781 | 65,465,557 | Intersection detection with stencil buffer | In order to implement deferred lightning, I render light sources as a sphere with a radius of light.
I rendered only actual positions of light to screen. The result is below.
so I thought maybe if I can render the intersection of this spheres then I can get rid of for loop for each light in the deferred shader.
by usi... | I solved this problem.
After rendering geometry to buffer, instead of drawing quad to screen, I rendered spheres in the following.
First, render light spheres in the null pass with the following states.
glEnable(GL_STENCIL_TEST);
glEnable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glDepthFunc(GL_LESS);
... |
63,679,033 | 63,679,136 | Implementing small functions in a header file, including in two different files in the same project | A quote from learncpp.com about whether to ever implement functions in header files:
For classes used in only one file that aren’t generally reusable, define them directly in the single .cpp file they’re used in.
For classes used in multiple files, or intended for general reuse, define them in a .h file that has the ... |
I understand that some linkers are smart enough to tolerate this
All standard conforming linkers tolerate multiple identical definitions of inline functions.
linker can be relied upon to ignore the duplicate definition
Yes.
and will not waste too much time doing so?
I would not expect the time wasted by the linke... |
63,679,447 | 63,679,568 | Learning C++ and having a problem correclty separating class interface from implementation | I'm learning C++ using Xcode and have written several small programs including a hangman game but I'm having trouble every time I try to separate a class into definition and implementation. I made a simple case that shows my problem. Short version is it seems that I need to specify a type in the implementation file ev... | Remember that you are declaring a class. A class is an abstract concept. When you do this xlemem::atrb_count = 0;, you are having a concrete value on an abstract concept. Doesn't make sense, right? You don't think of a particular color when you think of the general concept of dog. Any initiliazations should be done ins... |
63,679,802 | 63,680,431 | Run-time linker issue: "error while loading shared libraries" | I am working on a C++ project consisting of multiple similar programs. Each use a variety of headers and binaries, around 80. I managed to compile each program, and successfully run each but one of them, one named VerifyServer. When I try to run this, I get the below error:
./VerifyServer: error while loading shared li... | This may be due to the linker unable to find transient dependencies. If you are directly linking against EG: libboost_thread, then the applications runtime linker will use the -rpath path that you defined when compiling.
HOWEVER, the libboost_thread may require ITS OWN library, libboost_system. The question is, should... |
63,679,827 | 63,681,085 | Variadic Template Expansion - expand all except the i-th entry | Is there a way to remove one of the types from type expansion?
Let's use tuple as an example,
void foo() {
tuple<int, double, string> t;
// some facility to expand except the i-th type:
expand_except_ith<0>(t); // returns tuple<double, string>
expand_except_ith<1>(t); // returns tuple<int, strin... | Here is a short c++14 version:
template<std::size_t...Is>
auto indexer( std::index_sequence<Is...> ) {
return [](auto && f) {
return f( std::integral_constant<std::size_t, Is>{}... );
};
}
template<std::size_t N>
auto indexer() {
return indexer( std::make_index_sequence<N>{} );
}
template<std::size_t N, clas... |
63,679,888 | 63,679,933 | CMake files to build main and tests separately | I have the following directory structure:
main.cpp
CMakeLists.txt
src/
some_function.h
some_function.cpp
some_class.h
some_class.cpp
CMakeLists.txt
test/
catch.hpp
tests.cpp
CMakeLists.txt
CmakeLists.txt in the project root:
cmake_minimum_required(VERSION 3.16)
set(CMAKE_CXX_STANDARD 1... | Just link the some_class library target to the tests target, like you did with the main executable target.
CmakeLists.txt in the project root:
cmake_minimum_required(VERSION 3.16)
set(CMAKE_CXX_STANDARD 11) # C++11
project(main)
add_subdirectory (src)
# Add the test sub-directory also.
add_subdirectory(test)
add_exe... |
63,680,358 | 63,680,422 | Implicit initialization by argument deduction for a templated class array | I have an item class, thats really a wrapper around an int.
I have a templated node class. I pass item class to it as template parameter.
I want to create an array of the templated node class, but compiler does not like it.
When I create a single object using the same syntax, it works.
Why cant it deduce the array elem... | In aggregate initialization of array, the elements are copy-initialized from the corresponding clause of the initializer list. That means the element with type bNode<bItem> needs to be copy-initialized from the int, which requires two user-defined implicit conversions, from int to bItem and from bItem to bNode, which i... |
63,680,537 | 63,698,976 | File dumping from Binary issue | I'm trying to code a dump tool and There is a file in memory at a pacific address that holds a file with 41mb's in file size.
I'm trying to write that file with the file size to the directory.
Any advice or opinions you can provide much appreciation.
I've tried this...
Here is my updated code:
#include <Windows.h>
#i... | Here is an example that writes 64k of memory from a running Notepad++ process. Perhaps you can adapt it to your needs.
#include <Windows.h>
#include <Psapi.h>
#include <iostream>
#include <fstream>
#include <vector>
void* GetBaseAddress(HANDLE processHandle)
{
HMODULE hMods[1024];
DWORD cbNeeded;
if (EnumP... |
63,680,706 | 63,680,770 | How do I read Files with similar names in c++ | total1_0831.txt
total2_0831.txt
total3_0831.txt
total1_0901.txt
total2_0901.txt
I want to load 3 0831 text files
my code is
fstream myTxT;
myTxT.open("total1_0831.txt");
fstream myTxT;
myTxT.open("total2_0831.txt");
fstream myTxT;
myTxT.open("total3_0831.txt");
It was ineffective, so I wrote the code in a new way.
v... | You should have a base string, to which you then append the number of the file to read as a string, and finally append the extension.
Once you have the path string constructed, you can load the file.
All this logic should go in a loop, and you're done!
Having said that, it probably is an overkill for just 3 files, but ... |
63,680,728 | 63,680,968 | Why does the below code give 'std::logic_error' what(): basic_string::_M_construct null not valid? | I am getting std::logic_error' what(): basic_string::_M_construct null not valid when i run the function sort_string with the for loop but not with simple relational operator to compare the two strings.
The program constructs the largest number from the vector of given numbers. For small input it works fine but not fo... | The problem is caused by
return true;
in sort_string. It needs to be
return false;
When you reach that line, xy is equal to yx. Hence yx < xy is false, not true.
The line
return xy >= yx;
works because that line is the same as
return yx < xy;
|
63,680,949 | 63,681,004 | How to resolve a C++ Error: Redefinition of 'class' | I am new to C++ programming and have a compiler error that I can't figure out. Any help would be appreciated.
Here is the build log:
C:\Dev\MemberTest\Entity.cpp|6|error: redefinition of 'class Entity::Entity'|
C:\Dev\MemberTest\Entity.h|6|error: previous definition of 'class Entity::Entity'|
||=== Build failed: 2 erro... | The implementation file (Entity.cpp) should not contain the class definition again. Instead, you write non-inline definitions ("out of class"):
#include <string>
#include "Entity.h"
namespace Entity
{
Entity::Entity(std::string y, bool x) : name(y), membership(x) {}
bool Entity::getMembership() { return membership; }... |
63,681,434 | 63,690,668 | GLSL + Scenekit: Function definition not allowed | I'm trying to create a vertex shader in Scenekit. The shader is successfully added to the geometry of the SCNNode, however it displays purple because I get an error. I added the shaders to the geometry using SCNShaderModifiers and know that they are successfully found and attached.
The exact error messages I recieved i... |
I added the shaders to the geometry using SCNShaderModifiers and know that they are successfully found and attached.
If you use SCNShaderModifiers, you also have to adhere to their documentation:
Custom global functions. If your shader modifier benefits from factoring common code into functions, place their definit... |
63,681,711 | 63,681,952 | Template Variadic argument deduction from sibling argument | I have this simple templated structure:
template<typename T, typename ...Args>
struct Packet {
void DoSmth(Args... args){}
};
//usage
struct Packet1Model{};
struct Packet1: Packet<Packet1Model, int,float ,int>{
};
Is there a way in c++ to have a function that takes as a template argument
an typename T and an oth... | You can do something along these lines with a wrapper class (and a trick to obtain the relevant base class for the template argument):
namespace detail {
template<class,class> struct Wrap;
template<class PacketType,class T,class ...TT>
struct Wrap<PacketType,Packet<T,TT...>> {
void Func(TT ...tt) {
Pack... |
63,681,939 | 63,682,411 | Reading/writing 32-bit data types on a 64-bit architecture | I have an unclear question that I need more clarification about it. when I store data type like integer 4 byte. then how the processor with the architecture of 64 bit reads or writes an integer with a size of 4byte as I know the processor reads/writes a word. is there any padding size here. I will be thankful for some ... |
as I know the processor reads/writes a word
Word-oriented CPUs can load/store in 64-bit chunks, but also narrower chunks. (Storing the low part of a register, or loading with zero-extension or sign-extension). Capability to do narrow stores is fairly essential for writing device drivers for most hardware, as well a... |
63,682,297 | 63,682,298 | What are IN, OUT and IN/OUT Parameters Modes in C++ |
What is an IN (Incoming Parameter)?
What is an OUT (Outgoing Parameter)?
... and more.
Was scrolling through Stack Overflow and found a question similar to
this. It was later deleted by the author. There is no searchable
information on the web about this. Found a small post read and tried
to understand. This Q&A i... | These terms are used to define what kind of operation the function performs on the passed variables. Read, Write or Read/Write. This notation is used in the documentation of libraries to ensure the caller provides appropriate variable type to the function for performing appropriately and not accidentally hinder the out... |
63,682,627 | 63,682,668 | How to bypass C++ inability to match function types in templates with lambdas | If you have the following template for filtering list:
template <typename T>
inline std::list<T> list_filter(std::list<T> const& a, bool (f)(T)) {
std::list<T> output;
std::copy_if(a.begin(), a.end(), std::back_inserter(output), f);
return output;
}
Then try to call it with the lambda inside like:
std::lis... | Implicit conversion (from lambda with no capture-list to function pointer) won't be considered in template argument deduction, which fails to deduce template argument T on the 2nd function argument.
Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for ove... |
63,682,820 | 63,682,844 | C2296: '|': illegal, left operand has type 'float' | I am trying to compare, in a clean and FAST way (by logic) if three variables are 0, they are all floating point numbers, IEEE 754.
float x;
float y;
float z;
if(((x | y | z) == 0.0f)) { ... }
But, I keep getting:
main.cpp(15): error C2296: '|': illegal, left operand has type 'float'
main.cpp(15): error C2297: '|': i... | The bitwise operators are only defined for integral types. A float is not an integral type.
Don't micro-optimise like this. Write your intention clearly, and leave the optimisation strategy to the compiler.
|
63,682,868 | 63,711,626 | pybind11 for C++14/C++17 | Does pybind11 work for C++14 and C++17 seamlessly ?
I'm planning to use Boost.python for my project which is currently in C++11. In future I may have to upgrade to C++14 or C++17. So I wanted to understand what will be the right choice here - boost.python ot pybind11.
From pybind11 doc, it says - "seamless operability ... | Yes, it works with C++11/14/17/20, see corresponding section in docs.
By default, pybind11 will compile modules with the compiler default or the minimum standard required by pybind11, whichever is higher.
|
63,683,240 | 63,741,862 | How the synchronized_pool_resource actually works? | I am studying about the polymorphic memory allocation in C++17.
I modified an example which uses monotonic_buffer_resource for vector allocations to use a synchronized_pool_resource.
I detected a strange behavior. Specifically , there are many memory allocations , just for two additions in the vector. I did not run ... | The answer is in the function description: https://en.cppreference.com/w/cpp/memory/synchronized_pool_resource
It consists of a collection of pools that serves request for different
block sizes. Each pool manages a collection of chunks that are then
divided into blocks of uniform size.
Calls to do_allocate are dispatc... |
63,683,286 | 63,683,386 | Difference between preprocessor macros and std::source_location | There are some predefined preprocessor macros (specified in C and C++ standard) like __line__ and __file__ which are replaced by line number and file name during preprocessing respectively. In C++20, a new class std::source_location is introduced which does more or less the same thing.
So, my questions are...
What are... | Preprocessor macros live outside the type system. Preprocessor macro substitution happens outside the rest of the language. See this answer and this answer for a comprehensive discussion of the disadvantages of using the preprocessor.
std::source_location on the other hand behaves like any other C++ struct. It has plai... |
63,683,345 | 63,684,793 | I just wanted add tutorial in my poor code and I wanted place help but i don't know how to do it, any idea? | I'm new to coding and I wanted to do it with an if statement but I don't know how.
I wanted to do so if user writes "help" the program shows him and if you enter "displaying information" the program will show you the result.
#include <iostream>
struct studen
{
char name[50];
int roll;
float marks;
std::... | I've an idea on how to implement the tutorial that you're asking for.
I'm going to attach the code here below:
#include <iostream>
#include <string>
#define NAME_LENGTH 50
#define SIZE_ARRAY 10
#define HELP_COMMAND "help"
struct student {
char name[NAME_LENGTH];
int roll;
float marks;
} students[SIZE_ARRAY... |
63,683,397 | 63,684,735 | C++ Error LNK2019 ai::FilePath unresolved error symbol | I'm actually stuck with this problem, I don't know why they said unresolved external symbol cause on Vstudio, ai::FilePath is recognized by the editor.
error LNK2019: unresolved external symbol : "public: __cdecl ai::FilePath::FilePath(void)" (??0FilePath@ai@@QEAA@XZ)"
Someone can help me please, thank you !
| Sounds like the library file is not being found. IAIFilePath.cpp will most likely be built into a .lib file and that is what the linker is not finding.
Make sure you #include the header file, not the .cpp file also. While it can be done, its not the right thing to do.
Couple of options for you:
Copy the .lib file into... |
63,683,597 | 63,683,885 | Move constructor vs Copy elision | Can someone please explain me one thing. From the one side the move constructor was designed to optimize the memory & processor usage by eliminating unnecessary copying an objects BUT from other side almost everywhere the move constructor is going to be used the compiler uses copy elision, disabling the usage of the mo... | There are plenty of cases where the move constructor will still get called and copy elision is not being used:
// inserting existing objects into a container
MyObject myobject;
std::vector<MyObject> myvector;
myvector.push_back(std::move(myobject));
// inserting temporary objects into a container
myvector.push_back(My... |
63,683,922 | 63,684,209 | Convert R, G, B arrays to RGB arrays | I've my R, G and B arrays which are uint8_t
uint8_t * R, * G, * B, * A;
int stride_r, stride_g, stride_b, stride_a;
getRGB(img, &R, &G, &B, &A, &stride_r, &stride_g, &stride_b, &stride_a);
// All the strides are equal and the img is img_width and img_height dimension
int RBG[stride_r * img_height];
SO my question is w... | You are on the right track. However, rather than adding the four component bytes into the four-byte integer, you need to combine them using bitwise or operations:
for(int i = 0; i < stride_r * img_height; ++i)
{
RGB[i] = (R[i] << 24) | (G[i] << 16) | (B[i] << 8) | A[i];
}
Also, bear in mind that, on many/most plat... |
63,684,249 | 63,684,399 | Print array effective in C++ | I want to print a int array in C++.
I know I can use a for loop to print it ,
But is there any utils for this? Like Arrays in Java .
| No, there is no Arrays.toString() nor Arrays.deepToString
the most similar to
Arrays.asList(strArray).stream().forEach(s -> System.out.println(s));
is the ostream_iterator
int x[] = { 0, 1, 2, 4, 256};
std::copy(std::begin(x), std::end(x), std::ostream_iterator<int>(std::cout, "\n"));
|
63,684,336 | 63,684,609 | Can I specialize forward declared template? | Can I specialize forward declared template? For example:
template <typename T> class A;
template <>
class A<char> {
char a[1000];
};
int main()
{
[[maybe_unused]] A<char> a;
return 0;
}
What do I want to achieve?
As we know, we have to specialize std::hash to use it with some hash-table-based types. Stan... | The general question about A is that yes, it's allowed. An explicit specialization is disjoint from the primary template. It can be defined as complete or incomplete, regardless of how the primary is defined.
As for your more specific question about std::hash, not it's not alright. You violate
[namespace.std]
1 Unless... |
63,684,485 | 63,685,953 | GStreamer + OpenCV video processing problem | I am planning on doing VideoCapture from OpenCV for video file stream/live rtsp stream. However, the VideoCapture has alot of latency when used in my program so i decided to use the gstreamer pipeline instead. For example, i used
VideoCapture capVideo("filesrc location=CarsDriving.mp4 ! qtdemux ! h264parse ! nvv4l2deco... | This is a bug which @alekhin mentioned here and here. Also mentioned how to fix. After changing you should rebuild opencv.
Also you said:
However, the VideoCapture has alot of latency when used in my program
so i decided to use the gstreamer pipeline instead.
rtsp cameras generaly streams as h264/h265 encoded data. I... |
63,684,741 | 63,685,060 | How to get the minimum and maxium number using pointers in C++ | I trying to find the minimum and maximum numbers using pointers in C++ but in this code that I get from the video-sharing site gives me the wrong value. when I type 1 2 3 4 5 6 its answer is the minimum is 2 and the maximum is 2.
Here is my code:
#include <iostream>
using namespace std;
int main()
{
int value[6], ... | Here you are the complete code:
#include <iostream>
#define N_VALUES 6
using namespace std;
int main()
{
int value[N_VALUES], *maximum, *minimum, i;
cout << "Enter six numbers with space: ";
for (i = 0; i < N_VALUES; i++) cin >> *(value + i);
maximum = value;
minimum = value;
for (i =... |
63,684,908 | 63,685,090 | Environment variables from a system() call another program | I'm currently building a daemon in C++ and the children processes are created by a fork() statement. The children are listening incoming events from an Amazon SQS queue, and everything is working fine in the lifetime loop of the processes.
When a new message is read from the queue, the process must execute an external ... | You need to run a single system() call which sets the environment variable and runs the program. Do it like this:
system("DYLD_LIBRARY_PATH=<path-to-my-dylib-folder> my_binary_path")
The same syntax works in a regular shell: the variable is set for the specified command (and not afterward).
|
63,685,159 | 63,685,393 | C++ I need to check if a two-digit number contains a 0 or not | I am making a program where I need to check if a two-digit number like 76 or 70 contains a 0 or not.
with 76 the outcome would be false
with 70 true
I can't seem to make something up and I am still stuck with nothing not knowing how to start.
| you can convert the number to string and check if first or second char is '0'
bool containsZero (int x) {
string tmp = to_string(x);
if (tmp[0] == '0' || tmp[1] == '0')
return true;
return false;
}
or divide the number on 10 twice and check if every digit is 0 or not
bool containsZero (int x) {
... |
63,685,243 | 63,685,643 | Convert temporary vector to list in C++ | I have a function get_stuff() that returns a vector.
I would like to do the following:
vector<int> get_stuff(); // a function returning a vector of ints
list<int> stuff = get_stuff();
stuff has to be a list because there will be a lot of insert/delete operations.
However you obviously can't assign a vector to a list... | You can use a lambda like this:
std::list<int> oList = [](std::vector<int>&& v){ return std::list<int>(v.begin(), v.end()); }(get_stuff());
The line can be written a little shorter:
auto oList = [](std::vector<int>&& v){ return std::list<int>(v.begin(), v.end()); }(get_stuff());
And with C++14 more shorter:
auto oLis... |
63,685,496 | 63,685,714 | How the answer is -0? | Please forget me if I my question is not right.I am a beginner in c++.
I just wrote a simple program in c++
My code is:
#include<iostream>
using namespace std;
int main()
{
float a,b,c;
a=0;
b=-5;
c=a/b;
cout<<c;
}
When I ran this code the output is -0.
How the answer could be -0 while -0 doesn't ... |
How the answer could be -0 while -0 doesn't exist?
Your assumption is wrong. -0 does exist in floating point number representations, and therefore the answer can be -0.
For reference, see the IEEE-754 standard and for "why", see Branch Cuts for Complex Elementary Functions or Much Ado About Nothing's Sign Bit.
|
63,685,561 | 63,686,384 | Getting all combinations inside an array, where the sum of all entries is equal to a given integer | I am trying to get all possible combinations inside an array with a given fixed size where the sum of all entries is equal to a given integer.
Example:
given integer n: 5 and given array size = 4
{0,0,0,5}
{0,0,5,0}
...
{0,0,1,4}
...
{1,1,1,2}
...
my goal is to get those combinations and save them inside a C++ vector.
... | Simple recursive approach:
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> v;
vector<int> parts;
void partitions(int sum, int k) {
if (k == 1) {
parts[k - 1] = sum;
v.push_back(parts);
return;
}
for (int i = 0; i <= sum; i++) {
parts[k-1] = i;... |
63,685,834 | 63,686,065 | How to take ownership of an object while looping over std::vector of std::unique_ptr using a range based for loop? | I have a std::vector<std::unique_ptr<Kind>> which I want to clean up while it is being iterated upon, without explicitly calling the destructor of its members (.reset()).
The Kind is a heavy struct and its size increases during the iteration. The next object doesn't need to know about previous objects so I'd like to cl... | Example of moving the element out of the vector.
int main() {
std::vector<std::unique_ptr<Kind>> store;
store.push_back(std::make_unique<Kind>('y'));
for(std::unique_ptr<Kind> &t : store){
auto tmp = std::move(t); // leaving a valid but empty entry in store
std::cout << tmp->a;
// cl... |
63,686,025 | 63,686,069 | How to create list and initialize only some of it's values in Python (in comparison to C++) | I need to create an List of size N and then initialize only N-1th and N-2th elements only. Which means if the size of the list is 5 then it should only contain elements in 3rd and 4th position.
i know how to do it in C++ but is there any way to implement it in Python?
for example: In C++
int *n = new int[5];
n[3] = ... | In python, list must be initialized with values.
Closest thing you can do:
N = 5
lst = [0] * (N-2) + [20, 10]
This:
Fills the N-2 elements of a list with default value 0
Sets the value for the last two elements
Concatenates the zeros and last two elements sub-lists of stages 1 & 2
|
63,686,142 | 63,686,182 | Simplest way to assign std::span to std::vector | I wanted to do this
#include <vector>
#include <span>
struct S
{
std::vector<int> v;
void set(std::span<int> _v)
{
v = _v;
}
};
But it does not compile. What are the alternatives?
| v.assign(_v.begin(), _v.end());
|
63,686,222 | 63,688,246 | QT Designer - How to create a layout | I'm new to QT, especially QT Designer and I found it to be quite unintuitive.
I have the following layout which I'm trying to achieve in Qt Designer.
Explication:
YELLOW -> the application window
BLUE -> 2 side buttons with the heigh of red heigh and white heigh
RED -> should be around of 2/3 of the blue heigh
WHITE ... | I think what you are looking for is QGridLayout.
In a QGridLayout you can decide for each widget how many rows it will occupy (just drag its borders) and the various "weigths" (parameter is called rowStretch or columnStretch) of each row/column.
Example:
Your layout may be composed as follows:
A big yellow rectangle is... |
63,686,309 | 63,739,822 | Use Qt3D offscreen-rendered texture in OpenGL | Goal
I'd like to implement an actual widget for Qt3D since QWidget::createWindowContainer just doesn't cut it for me.
Problem Description
My first approach of letting a new class subclass QWidget and QSurface was not successful since the Qt3D code either expects a QWindow or a QOffscreenSurface in multiple places and ... | Update (10th May 2021, since I stumbled upon my answer again):
My Qt3DWidget implementation works perfectly now, the issue was that I had to call update() when the frame action was triggered instead of paintGL (duh, silly me, I actually know that).
Although I didn't find an exact solution to my question I'll post an a... |
63,686,441 | 63,686,519 | Using bitwise or operator in switch case | I have enum,
enum ENUM_MSG_TEXT_CHANGE {COLOR=0,SIZE,UNDERLINE};
void Func(int nChange)
{
bool bColor=false, bSize=false;
switch(nChange)
{
case COLOR:bColor=true;break;
case SIZE:bSize=true;break;
case COLOR|SIZE:bSize=true; bColor=true;break;
}
}
case SIZE: and case COLOR|SIZE: b... | If you want to make a bitmask, every element of your enum has to correspond to a number that is a power of 2, so it has exactly 1 bit set. If you number them otherwise, it won't work. So, the first element should be 1, then 2, then 4, then 8, then 16, and so on, so you won't get overlaps when orring them. Also, you sho... |
63,686,677 | 63,689,886 | best way to inherit from a class without virtual functions | I am trying to implement some event handling.
There are different types of events: integerChangedEvent, boolChangedEvent, stringChangedEvent and so on...
Each of these events hold some of the same information like: std::string settingsName, std::string containerName...
But also each of these different event types also ... | OK so the event knows what type it is.
switch (event->type)
{
case IntegerChangedEventType: {
IntegerChangedEvent* ievent = static_cast<IntegerChangedEventType*>(event);
handleIntegerChangedEvent(ievent);
break;
}
case StringChangedEventType: {
StringChangedEvent* sevent = static_... |
63,686,729 | 63,687,041 | A portable C++ alternative to compound literals that is guaranteed to be free of heap allocation | C99 compound literals are not supported in C++. In many cases, list intialization provides an excellent alternative. However, they are not guaranteed not to heap-allocate memory.
Are there any convenient and portable alternatives for C++ code that needs to work entirely without heap allocations?
| As the answers on the linked question indicate, since C++14 the compiler cannot heap-allocate an initializer list. Moreover, even pre-C++14 compilers won't heap allocate initializer lists, as there's absolutely no reason to do so (and plenty of reasons not to).
|
63,686,765 | 63,686,922 | Double to uint64_t conversion | Following demo program demonstrates some behaviour I don't understand.
#include <string>
#include <limits>
#include <iostream>
constexpr double bits64 = 18446744073709551616.0; // 2^64
void diff_hash(double diff)
{
double hash = bits64 / diff;
uint64_t hash_64_1 = hash;
uint64_t hash_64_2 = hash... |
18446744073709551616.0 / 1.0 is evaluated as a double. Its value is 18446744073709551616.0, assuming IEEE754. The behaviour on converting this to an out of range uint64_t is undefined. A common manifestation of that undefined behaviour is wrap-around to 0. (That's what most folk assume happens, but the behaviour is un... |
63,686,834 | 63,687,092 | Infer the type of the class owning a member function | Let's consider a kind of "invoke" function (here named "call") that helps to call a member function passed by a template argument.
In this function, I would need to know the type of the class that owns the member function. Is there a way (in c++14 preferably) to do so ?
#include <functional>
template<typename F, typen... | template <typename>
struct class_of;
template <typename C, typename R, typename... Args>
struct class_of<R(C::*)(Args...)> {
using type = C;
};
Then you can get the type like typename class_of<F>::type. E.g.
template<typename F, typename... Args, std::enable_if_t<std::is_member_pointer<std::decay_t<F>>{}, int> = 0... |
63,686,966 | 63,713,700 | Using Eigen - how to solve sparse (SPD) linear systems with zero columns? | (I'm using Eigen C++ library)
I need to solve a system of equations with the form of Ax = 0 in order to find the x vector (A is sparse).
EDIT: A is SPD (symmetric positive definite)
Because some of the x values are known, I removed them out of A to create Af and into another matrix Ac with the same dimensions as A, and... | You have "A" and "b = 0" given, and know A is symmetric positive definite.
Because A is spd, it has no nontrivial null-space (this is an important property). That is, the only "x" that exists such that Ax = b = 0 is x = 0.
So you won't find a solution if given nonzero values. It will always be x = 0.
I say this to emph... |
63,687,026 | 63,687,582 | C++ private char* member allocation failure 'Expression must be a modifiable lvalue' | I am trying to create a simple exception class but I have encountered this annoying issue and have no idea what's wrong. Please note that I am C++ noob (hence trying to learn how to use new instead of malloc).
Here is the code:
#include <errno.h>
#include <exception>
#include <string.h>
/**
* An exception describing ... | The member function is const qualified. Therefore it cannot change the values of the members.
In practice, exceptions should initialise their message within their constructor, and only return a pointer to the already constructed message within what.
Also, errno may have been overwritten by some operation. You should pa... |
63,687,059 | 63,687,467 | performance improvements for cube root in Eigen | I did profile my code using Valgrind (using the "release with debug information" build) and found out that a significant amount of time (~25%) is spent on one line where I calculate the element-wise cubic root of a big matrix.
Now, I would like to accelerate this step if possible.
Currently, I'm simply using .pow( 1.0 ... | You can use DenseBase::unaryExpr and a C++ lambda:
VectorXd s = v.unaryExpr([](double coeff){ return std::cbrt(coeff); });
A small benchmark using Google Benchmark:
#include <Eigen/Dense>
#include <benchmark/benchmark.h>
using namespace Eigen;
static void BM_Pow(benchmark::State& state)
{
VectorXd v = VectorXd::Ra... |
63,687,470 | 63,687,737 | C++ I don't know what it means to use "this" and "std::placeholders::_1" when using the callback function | I am trying to make a server by looking at the sample code of cpprestSDK.
But I don't know why I bind in the sample code.
Below is the sample code.
stdafx.h
class Handler{
public:
Handler() {};
Handler(utility::string_t url);
pplx::task<void> open() { return m_listener.open(); }
pplx::task<void> close(... | The member function
void support (const http::method &method,
const std::function< void(http_request)> &handler)
expects handler to be a callable which has
an argument of type http_request
a return type void.
A plain function void handle(http_request) would match this required signature.
If you want to... |
63,687,617 | 63,960,788 | Compiler does't recognize overloaded method in another method | I have two classes: "Station" which has method getName() returning string and "Profit" which has the overloaded method sellAt(string stName), sellAt(Station st). To avoid duplicate code I call sellAt(string stName) in sellAt(string stName), however in some cases (see code example below) compiler gives an error: "no ins... | Yksisarvinen answered in the comment below the original question:
st.getName() is a temporary. You cannot bind non-const reference to a temporary. I suppose you shouldn't want to modify stName in Profit::SellAt(), so change the type of argument to const std::string&.
Thanks for the help!
|
63,687,805 | 63,687,882 | Argument type for std::move as a parameter | https://stackoverflow.com/a/18300974/462608
If you pass an rvalue reference to another function, you are passing a
named object, so, the object isn't received like a temporal object.
void some_function(A&& a)
{
other_function(a);
}
The object a would be copied to the actual parameter of
other_function. If you wa... | An rvalue reference is not an rvalue. It's confusing because an rvalue was passed in the argument list of some_function; but a, as with other named values, is an lvalue. std::move is required to take a (an rvalue reference, which is an lvalue) and convert it into an rvalue.
It's probably easiest if you take function ca... |
63,687,902 | 63,687,960 | Are lambdas cached at compile-time in C++? | Allocating a lambda is expensive. On MSVC it allocates ~128 bytes last time I checked. This makes creating lambdas in a loop a serious performance issue.
In Python, all literals are treated kind of like constexpr, they are calculated (if needed, like x = 10 * 25) and then cached at compile-time and simply substituted w... | Since your lambda is noncapturing and invoked immediately, any compiler worth its salt will hoist the lambda to a static function and inline the call with zero overhead.
Are you sure you're not confusing lambdas with std::function?
|
63,688,062 | 63,688,424 | Need a C++ map and list which contain iterators to each other | I have a custom templated container using a map and list being kept in sync. The map needs to hold MyList::const_iterator and the list needs to hold MyMap::const_iterator. The only solution I've been able to find is to pun one of the iterators, as in the example below.
Is there a proper way to forward declare this so... | Forward-declaring at least one of your inner classes breaks the cycle:
template<class ObjectT> class MyClass
{
public:
struct ListEntry;
private:
typedef std::list<ListEntry> List;
// Rest of the class, using List as you like
Note that the following List::const_iterator works thanks to std::list<T> not re... |
63,688,639 | 63,690,216 | c++20 library support for xcode 12 | can i use the c++20 library with xcode 12? (xcode 12 beta 5, with clang version 10.0.0).
so in xcode build settings, instead of
// in xcode build settings, "c++ standard library"
CLANG_CXX_LIBRARY = libc++
maybe use something like (does not work => clang err: invalid library name)
CLANG_CXX_LIBRARY = libc++20 // eg. l... | There can be easier ways, or I might have done something redundant (let me know what can be removed), but here's a surefire way.
If you download the LLVM binaries from LLVM releases, do Step 1 - a and not Step 1 - b.
Step 1 - a
Download the LLVM + Clang binaries of your choice.
https://releases.llvm.org/
https://githu... |
63,688,770 | 63,688,806 | Explain what this c++ bool line mean in this cpp book | playpen pp;
bool more(true);
do{
display_content();
int const choice(get_choice));
more = do_choice(pp, choice);
} while (more)
function code >>
bool do_choice(int choice){
bool more(true);
switch(choice){
case 0:
clear_playpen(???);
break;
case 1:
more = false;
break;
case 2:
change_plotmode(??... | You're confusing the assignment operator (=) with the comparison operator (==).
The call to do_choice updates more so the loop will stop eventually.
|
63,688,972 | 63,689,210 | Access derived virtual function from base class, good practice? | Is there a good practice to access a derived virtual function from it's base class?
Here's what I got so far:
class A {
public:
enum class AType{A,B,C,D};
AType aType = AType::A;
virtual void Do(){}
};
class B : public A {
public:
int val = 0;
B(int i) {
aType = AType::B;
... | You should assign a pointer or reference to use polymorphism in C++. If you assign a child class as value, there would be a object slicing. I'd use std::unique_ptr than raw pointer like following, which prints out 10 15 80 as excepted.
#include <memory>
#include <map>
class A {
public:
enum class AType { A, B, C, ... |
63,689,097 | 63,689,268 | Does optional typename apply to concept? | GCC implemented P0634R3 that discards the need of specifying typename when the type is in known context.
Does it apply to concept as well?
Because the following code does not compile:
template<typename T>
concept sample_concept =
std::default_initializable<T::value_type> &&
requires (T t) {
{ t.some_fun... | From the paper, emphasis mine:
We therefore propose we make typename optional in a number of commonplace contexts that are known to only permit type names.
That paper makes typename optional only in those places where you need to have a type. On the right-hand side of an alias declaration, needs to be a type. In a st... |
63,689,124 | 63,689,253 | Array allocated like char* const pointer gives Gibberish output | I am trying to figure out, why my char* const isn't new and empty?
char* const a = new char[10];
Gives me:
\r\r\r�����������
EDIT: Ran a test,
std::string text = "Hello world!";
int length = text.size();
char* const a = new char[length];
std::memset(a, '\0', length);
std::strncpy(a, s.c_str(), length); // <-- after t... |
why my char* const isn't new and empty?
Because you didn't create an empty array, but an array of size 10. Therefore there are 10 elements.
Furthermore, you didn't initialise any of the elements. More specifically, you didn't initialise any of the elements to be the null terminator character. As such, your array is n... |
63,689,476 | 63,689,497 | c++ printf float - how to specify precision programmatically? | printf("float: %.3f", myvar); prints myvar with 3 digits after the dot. But how can I do that if the number of digits I want to print is dynamic and specified in an int variable?
| You can use %.*f and add the int value before the data to print.
#include <cstdio>
int main(void) {
double myvar = 3.141592653589;
for (int i = 0; i < 10; i++) {
printf("float: %.*f", i, myvar);
putchar('\n');
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.