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 |
|---|---|---|---|---|
68,226,830 | 68,227,059 | What is the meaning of the /Fx option in MSVC compiler? | In the MSVC compiler, there is the option /Fx which generates merged source files. However, on the documentation of the option, there is no information about how to inject code into my source files nor what is the purpose of doing it.
If I take a dummy C++ project and add the /Fx option, nothing changes, no .mrg file i... | I found https://assets.ctfassets.net/9pcn2syx7zns/524v1rKJCe8GHLT3OE8nso/0c198e1ab4059da9cd902f120defa4b5/c__.pdf which, on page 198, explains that this is for attributes. (emphasis mine)
Basic Mechanics of Attributes
Microsoft defines a set of C++ attributes that simplify COM programming and .NET Framework common
la... |
68,226,850 | 68,227,155 | How to detect argument list of a function in C++? | I am designing an interface that accepts a user-defined function as parameter, which is then executed in a built-in function, like below.
#include <stdio.h>
#include <vector>
using namespace std;
template <class USERDEF>
void builtin(USERDEF userdef){
std::vector<int> vec = {1, 2, 3};
if("parameter list is (ve... | With if constexpr:
template <class F>
void builtin(F func){
std::vector<int> vec = {1, 2, 3};
if constexpr(std::is_invocable_v<F, std::vector<int>&>) {
func(vec);
} else if constexpr (std::is_invocable_v<F, std::vector<int>::iterator, std::vector<int>::iterator>)
func(vec.begin(), vec.end(... |
68,227,019 | 68,227,073 | overload shift so it supports chaining and also should work with cout | So I tried to make program according to Title of this question, and my code only couts the first one.
Here's the code
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
class Distance {
int feet;
int inches;
string display();
public:
Distance();
Distance(int, int);
... | The normal thing to do is to simply have one overload
//This requires a friend declaration inside the class first.
std::ostream& operator<<(std::ostream& os, const Distance &distance) {
return os << distance.feet << '\'' << distance.inches << '\n';
}
This lets you chain as expected:
std::cout << 3 << myDistance <<... |
68,227,190 | 68,227,342 | How can this constructor that has pointer as the parameter receive string? | This is a constructor that I found from the internet, but it didn't have enough descriptions so I couldn't understand how it's even possible for this constructor to have string as a parameter.
For instance, if I say MyString str1("hello world this "hello world" goes into the constructor, but I have no idea how this str... | So what is happening is the constructor doesn't actually receive a string, it receives a pointer that points to something of type char (and what is a string if not a sequence of chars, and I mean the concept of string and not the string object in C++ itself).
When you do "MyString str1("hello world")" what is actually ... |
68,227,353 | 68,227,488 | reusability : function with vector as argument | Here is the kind of code I often have:
struct MyData
{
public:
double a;
double b;
};
std::vector<double> complexFunction(const std::vector<double>& vIn)
{
std::vector<double> vOut;
// complex calculations on the vector vIn to make vOut
return vOut;
}
int main(int argc, char **argv)
{
std::vector<MyData> ... | You can pass a lambda function for getting a field of a complex data.
std::vector<double> complexFunction(const std::vector<MyData>& vIn, double (*get)(const MyData&))
{
std::vector<double> vOut;
// complex calculations on get(vIn[i]) to make vOut
return vOut;
}
// Usage
std::vector<double> vOut_a = complexFunction(... |
68,228,067 | 68,228,686 | C++ How Many Page-Faults are Created with COW? | I have seen this question online, and am not sure if my answer is correct or not:
#include <unistd.h>
#include <sys/wait.h>
#define N 100*1024*1024
int a[N];
int main() {
if (fork() > 0) {
wait(nullptr);
} else {
for (unsigned int i = 0; i < N; ++i) {
a[i] = 1;
}
}
... | Page faults don't show up in strace; they are not even something that happens "explicitly".
A page fault happens every time a piece of memory is accessed for which the assigned physical page is either not created yet, or mapped into the address space.
In practice the number of page faults for your program is sizeof(int... |
68,228,181 | 68,486,846 | How do you install the Protobuf Compiler (Protocol Buffers / protoc) on Mac M1 ARM? | Here is the link to the Protocol Buffers / Protobuf Github
https://github.com/protocolbuffers/protobuf
Should I follow the C++ installation instructions?
There is no pre-built binary for Mac M1 ARM architecture.
"Protocol Compiler InstallationThe protocol compiler is written in C++. If you are using C++, please follo... | As of July 2nd, the estimate delivery time for the Mac M1 ARM binary is 4 months.
|
68,228,222 | 68,228,352 | Can value of buffer change after destructor executes | Code:
#include <cstdio>
#include <new>
struct Foo {
char ch;
~Foo() { ++ch; }
};
int main() {
static_assert(sizeof(Foo) == 1);
char buffer;
auto const* pc = new (&buffer) Foo{42};
// Change value using only the const pointer
std::printf("%d\n", +buffer);
pc->~Foo();
std::printf("%d\n", +buffer);
... | In your final line, the lvalue buffer doesn't access any object.
The char object that was there initially had its lifetime ended by reusing its storage for a Foo. The Foo had its lifetime ended by invoking the destructor. And no one created any object in the storage after that.
lvalue-to-rvalue conversion (which is w... |
68,228,303 | 68,228,455 | How can I do this easier? | Let's say I have two classes, a and b, and I have 2 objects, choice1 and choice2.
I ask the user to enter a number. If user enters 1, I will use choice1, otherwise choice2 if it is 2.
When I try to use the object which the user has chosen, I don't know how I will proceed because I don't know which object it is.
Is ther... | In comments, you say that a and b have a common base class. In which case, setName() should be a member of that base class, and then you can do this:
base *b;
if (choice == 1)
b = &choice1;
else
b = &choice2;
/* alternatively:
base *b = (choice == 1) ? static_cast<base*>(&choice1) : static_cast<base*>(&choice... |
68,228,394 | 68,230,214 | Is this a valid way to return an iterator element and post-increment? | My class (let's call it A) takes in a string::iterator and it implements two methods:
auto peek() const -> const char &: Returns a reference to the data at the current position.
auto get() -> const char &: Returns a reference to the data at the current position then increments the position.
The solution I have come u... | Yes, return *(_s++); is perfectly valid and safe, provided s is a valid iterator to begin with (ie, the string is alive, and s is within the string's valid iterator range).
_s++ will increment s, returning a new iterator that is a copy of s before it was incremented.
Then * dereferences that copied iterator, yielding a... |
68,228,499 | 68,229,363 | Are Arrays Contiguous in *Physical* Memory? | I know that array elements are contiguous in virtual memory for sure, but are they in terms of physical memory like this one?
#define N 100*1024*1024
int arr[N];
Please Note, Until now most of you said the answer is NO but again my main question is the one below in bold.
If not, at-least if one element was found in ... | Each page of virtual memory is mapped identically to a page of physical memory; there is no remapping for units of smaller than a page. This is inherent in the principle of paging. Assuming 4KB pages, the top 20 or 52 bits of a 32- or 64-bit address are looked up in the page tables to identify a physical page, and th... |
68,228,722 | 68,254,091 | Specifying a newer C++ standard library dependency for a Debian package | I am completely new to Debian packaging and the documentation I've found takes either the form of really-incomplete tutorials (with overly-specific examples), or encyclopaedic-style manuals (with scant examples). From these, I'm trying to piece together how to package some C++17 code -- which I do not control -- to mak... | It turns out that:
Depends: libstdc++6 (>= 10.2.1)
...is enough and Apt will just complain and refuse to install until you have manually added a source that provides that package. Thanks to @KnudLarsen's comment, the actual minimum version I needed was 9.1.0.
|
68,228,871 | 68,228,944 | How to get difference between two times using date library? | I`m using date library. I didn`t understand how to get difference between 2 time points in milliseconds?
date::time_of_day<std::chrono::milliseconds> time1;
date::time_of_day<std::chrono::milliseconds> time2;
// set some time...
auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(time2 - time1);
std::cout... | Late during the standardization process, time_of_day was renamed to hh_mm_ss. The time_of_day name still exists as a type alias to hh_mm_ss in date as a backwards compatibility helper.
hh_mm_ss<milliseconds> is just a {hours, minutes, seconds, milliseconds} data structure that is handy for getting the "fields" out of ... |
68,229,184 | 68,458,723 | Split macro parameters at `=` for smart enum implementation | Is there a way to write a macro ENUM such that ENUM(Animal, Dog, Cat = 5, Horse = 2) expands to
enum class Animal { Dog, Cat = 5, Horse = 2 };
template<typename EnumT>
constexpr std::array<std::pair<std::string_view, Animal>, 3> get_enum_map() {
return {{ {"Dog", Animal::Dog} , {"Cat", Animal::Cat} , {"Horse", ... | As pointed out in the comments, there is no way to split macro inputs at a certain char, like =.
However, the better-enums library uses a neat trick by absorbing (or "eating") assignments via an _eat_assign helper class. For example
(EnumType)((better_enums::_eat_assign<EnumType>)EnumType::Name = EnumValue)
reduces to... |
68,229,876 | 68,259,641 | How can a project use wstring without including <string>? | An existing C++ project builds fine with VS2017 but in VS2019, fails with errors about undefined symbol std::wstring.
Digging into the code, <string> is never included anywhere but std::wstring is used which has me scratching my head how it ever built.
I happened to spot in the build logs a reference to corecrt_wstring... | Credit really goes to Ben for the hint but it turns out <vector> was causing <string> to be included on the VS2017 build.
|
68,230,583 | 68,230,647 | Why am i getting invalid types float[int] for array subscript? | So i've looked at other questions on stackoverflow that seemed to describe the same problem, but the problem in each of these cases seems to be a wrong reference, e.g. the object was not an array. I think i've referenced my array correctly, but today is my first day doing C++. Could anyone tell me what i'm doing wrong ... | You're passing a linear array as argument of the function yet you are using it as if it was a 2D array, that's not possible.
As it's passed, arr can only be used like arr[i], not like arr[i][j].
|
68,230,705 | 68,230,782 | Proper non-returning control function | I have a function which shows some message, properly finishes the program and finally calls exit(-1);. Here is an example of usage:
Data SomeFunction()
{
Data data;
if (some_condition) {
// filling the data
return data;
}
ShowErrorAndExit("Some message");
//return data - I don't want it here!
}
The p... | ShowErrorAndExit should be labeled [[noreturn]]. This will remove the warning.
Example:
[[noreturn]] void ShowErrorAndExit(std::string message) {...}
|
68,230,802 | 68,237,672 | Can Go work with memory at the page level? | I am a Go developer reading a book called Database Internals. The author talks extensively about working with memory at a very low level (specifically, at the page level).
As I am trying to build my own database, I have looked through Go documentation and other articles for discussions about work with memory at this le... | The book is talking about "On-Disk Structures". Page in this context simply means a block of data. Disk access works in sectors or clusters, so the data should be optimized for locality in order to fit in those blocks as best as possible. The challenge in database file design is to translate data's temporal locality in... |
68,230,820 | 68,232,569 | cpp - large array pass by reference | I have a very large array which has around 10000000 double entries (in the code below this number was set to NX=1000 but actually it will be 10000000 in realistic situations). I want to do some calculations with this array from which I get a new array. Then I do again some calculations with this new array and so on. I ... | According to your comment, you are very close to the answer. One thing you missed is that besides array is stack-based and vector is heap-based there is one more difference between array and vector: the vector needs to call its constructor(or resize) to enlarge size. So after switching to vector, we need a slight modif... |
68,230,863 | 68,231,451 | Why is std::optional's assignment operator not usable in compile-time context in this simple example? | After fiddling with the Compiler Explorer (as well as reading cppref.com on std::optional) for half an hour, I give up. Not much else to say other than I don't understand why this code doesn't compile. Someone please explain this, and maybe show me a workaround if there is one?
All the member functions of std::optional... | Let's simply this a bit:
constexpr std::optional<size_t> index_for_type() noexcept
{
std::optional<size_t> index;
index = 1;
return index;
}
static_assert(index_for_type().has_value());
With index = 1; the candidate you're trying to invoke amongst the assignment operators is #4:
template< class U = T >
op... |
68,231,067 | 68,231,220 | How to concrete a string with GetWindowsDirectoryA returned result? | I'm using this GetWindowsDirectoryA Windows API function to get the location for Windows folder.
#include <iostream>
#include <string>
#include <vector>
#ifdef __WIN32
#include <fcntl.h>
#include <io.h>
#include <Windows.h>
#include <sysinfoapi.h>
#endif
std::string GetOSFolder() {
std::vector<char> buffer(MA... | You could initialize the string with the path, you wouldn't even need to know the size (which is returned by GetWindowsDirectoryA as stated in the comment section), but it's advisable to use it given that it does optimize std::string initialization.
Example:
std::string GetOSFolder() {
char buffer[MAX_PATH + 1];
... |
68,231,069 | 68,231,747 | Configure c++ debugger in VSCode | I recently moved to VSCode and im a little be lost.
If i compile my program with this console command
g++ -Wall -o main main.cpp src/*.cpp -I included
It compiles and generates the .exe file correctly.
But i have a bug in it, so i want to use the debugger to know what is happening.
When i hit run -> star debuggin in ... | If you already have a compiled version with debug information (-g) then you do not need to include the header files again.
Just remove the line "preLaunchTask": "C/C++: g++.exe compilar archivo activo" from the configuration since your program is already compiled.
|
68,231,184 | 68,231,230 | using an index number, append that index (a character) to char array | I'm attempting to do something like this.
class testClass {
public:
void testFunction(char charArray[])
{
char output[].append(charArray.at(1));
char output[].append(charArray.at(7));
char output[].append(charArray.at(3));
cout << output;
}
int main() {
testClass ... | Do you mean like this:
#include <string>
#include <iostream>
class testClass {
public:
void testFunction(const std::string& charArray)
{
std::string output;
output.push_back(charArray.at(0));
output.push_back(charArray.at(6));
output.push_back(charArray.at(2));
std::... |
68,231,285 | 68,231,418 | Why do we need the second definition below in a `simple-declaration`? | simple-declaration:
decl-specifier-seq init-declarator-listopt ;
attribute-specifier-seq decl-specifier-seq init-declarator-list ; <====
attribute-specifier-seqopt decl-specifier-seq ref-qualifieropt [identifier-list]initializer ;
Note that the attribute-specifier... | Given that we want our grammar to accept:
DSS;
DSS IDL;
ASS DSS IDL;
(plus accept array forms, which this answer will not deal with any further)
but not
ASS DSS;
That is, if the attribute-specifier(s) are provided, the init-declarator-list becomes required.
The grammar productions as shown in the question provide for... |
68,231,535 | 68,232,381 | How do I get C++ signaling_nan() to throw an exception, without needing if tests? | I am trying to use signaling_nan() to automatically throw an exception if a variable whose value will be set post-initialization, is used before being set.
I have tried using the floating point exception functionalities via fenv.h, however that solution needs an if test for FE_INVALID, which I would like to avoid.
I am... | So, there's a lot of ways to go about this problem:
Custom Classes, Which Check for FPE in Operations
The simplest way is just to write a wrapper class, that checks for floating-point exceptions, and then never have to deal with it later, with all the numeric operations built-in.
#include <exception>
#include <fenv.h>
... |
68,231,583 | 68,231,724 | How can i return unique_ptr with pointer function? | i don't understand fully this problem. This is my function and i need return class with unique_ptr how can i this?
my list:
std::list<std::unique_ptr<Maths> > l_MathsList;
my function
Maths* Maths2::FindMathsID(int iID)
{
auto mpClass= std::unique_ptr<Maths>();
for (auto&& it : l_MathsList)
{
if (it... | You probably just want to return a non-owning pointer to the collection element right?
In that case just use .get():
Maths* Maths2::FindMathsID(int iID)
{
for (auto& it : l_MathsList)
{
if (it->IsMy(iID))
return it.get();
}
return nullptr;
}
|
68,231,723 | 68,231,853 | Error when writing a function that pushes a unique pointer into a vector | I have a function that takes in a unique pointer as a parameter and pushes it into a function.
#include <memory>
#include <vector>
class SomeObject
{
};
std::vector<std::unique_ptr<SomeObject>> someObjects;
void PushSomeObject(const std::unique_ptr<SomeObject> pSomeObject)
{
someObjects.push_back(pSomeObject);
... | You are copying a unique ptr twice. Unique ptrs cannot be copied, as each unique ptr claims exclusive ownership over the lifetime of the pointed to resource.
std::unique_ptr<SomeObject> pSomeObject = std::make_unique<SomeObject>();
PushSomeObject(std::move(pSomeObject));
this fixes the first copy.
'
The secon... |
68,231,735 | 68,521,508 | filesystem:error cannot remove: Input/output error | I'm trying to delete a font file using this way,
std::filesystem::remove(std::filesystem::path("C:\\Windows\\Fonts\\segmdl2.ttf"));
But this fails and throw an exception,
filesystem:error cannot remove: Input/output error
The exception is not helpful. What's the correct way to delete this kind of files?
Update,
I mad... | The error happened because I don't have permission to delete the file and in some cases it happened because the file already opened by another process.
To fix permission issue, I had to invoke the following commands from command promot,
takeown /f C:\Windows\Fonts /r /d y
icacls C:\Windows\Fonts /grant administrators... |
68,232,011 | 68,232,647 | Is checking the tick of a monotonic clock in C++ wait free? | Say we have a very basic code to check an elapsed interval
#include <iostream>
#include <chrono>
int main()
{
auto start = std::chrono::steady_clock::now();
// some work
auto end = std::chrono::steady_clock::now();
std::chrono::duration<double> diff = end-start;
std::cout << "T... | The C++ standard is silent on this issue.
Rationale: Every OS has some way of getting monotonic time. Down at the hardware level this is a counter per clock cycle. At the OS level this may or may not translate to scaling to some convenient units such as nanoseconds.
The problem <chrono> solves is that the OS API for... |
68,232,111 | 68,232,170 | Can someone please explain user-defined comparisons? c++ | I am having trouble understanding the following code. I understand the concept of a user-defined comparison is to sort an object in a certain way, but I don't understand how this code works.
struct P {
int x, y;
bool operator<(const P &p) {
if (x != p.x) return x < p.x;
else return y < p.y;
... | The C++ compiler doesn't know what to do when you compare one instance of P with another instance so you have to define the operator in order to use it.
The boolean function for < is to return True if the current object is smaller than the other object (p). What "smaller than" means is up for you to decide. The code th... |
68,232,668 | 68,232,733 | C++: Initialization within switch case is not consistently giving out error | I read that initialization within cases of switch is supposed to give compiler error.
But when I tried two different version. One is not giving out the error (Ex1), I can't understand why.
Ex 1:
switch (i)
{
case 1:
int k;
break;
case 2:
int j=3;
break;
}
Ex2:
switch (i)
{
case 1:
int k=3;
brea... | In a switch block, every declaration that comes before a case is available at that case. The error occurs when there is a case to which the switch can jump to which is located after the initialization of a variable that you could access there. If that case was jumped to, you could use the variable despite its initializ... |
68,233,079 | 68,233,338 | How to add a struct to a vector from another class? | I am student, and I am trying to build a project. My program is throwing an error while accessing the vector. The size of the vector is 1, but when I call RenderQueue.front it throws an error:
front() called on empty vector.
My code is below:
global.h
struct RenderStruct {
std::function<void()> testfunction1;
... | static linkage variables are not shared between compilation units (cpp files).
Make your variable non static, mark it as extern, then export it from one cpp file (by declaring it without extern there).
|
68,233,200 | 68,251,634 | How to catch EM_SHOWBALLOONTIP CEdit Message? | I'm trying to catch CEdit EM_SHOWBALLOONTIP message within PreTranslateMessage function.
Can somebody tell me how to do this ?
thank you
BOOL CTestDlg::PreTranslateMessage(MSG* pMsg)
{
if (pMsg->hwnd == m_edit1.GetSafeHwnd())
{
if (pMsg->message == EM_HIDEBALLOONTIP)
{
}
}
... | PreTranslateMessage is nested inside the message loop. Consequently, it is called for queued messages only. EM_SHOWBALLOONTIP is a sent message, and never winds up in the message queue.
In other words: You cannot observe EM_SHOWBALLOONTIP in a PreTranslateMessage implementation.
|
68,233,400 | 68,233,540 | Double quotes in user input in C++ | The user want to enter the input
;. ,?!"=':
int main()
{
string sep;
cout << "Enter the separators: " << endl;
cin >> sep;
}
I wrote the above program but when i print the sep variable it does not show the string after double quotes.
How can we read the double quotes enter by the user?
| Well, it does not show anything after the space either. The input (;. ,?!"=':) you use has a space after the dot(.) and it does not print anything after that. it's because, as the @Retired Ninja mentioned in the comment,
"Formatted input >> stops when it hits whitespace."
You can use getline if you want to take the e... |
68,233,524 | 68,233,634 | Initialize reference by typecasting the address of the variable | What is this?
1)
CCamera &MyCamera = *(CCamera *)0xB6F028;
We get address of variable: 0xB6F028, typecast it to CCamera* and dereference.
And initialize CCamera reference. What? What its working?
By dereferencing we get a value of this address. And this value assign to reference?
2)
CPool<CVehicle, CHeli> *&CPools::ms... |
By dereferencing we get a value of this address. And this value assign to reference?
You cannot assign a reference. You can only initialise a reference.
Now consider this:
int x = 42;
int& rx = x; // initialises rx to refer to x
So far so good? Let's continue.
int& rx = *(&x); // still initialises rx to refer to x
... |
68,234,342 | 68,234,521 | Returned reference to string literal (passed as parameter) is accessible in calling function, however, returned object storing the reference is empty | I'm passing a string literal to a function that simply returns back a const reference to it. In the calling function, the string is accessible and printed.
However, in another function, I'm instantiating a class that holds a const reference to the string literal. Returning this object back prints nothing in the calling... | In:
const Test& returnString2(const string& str) {
return Test{ str };
}
You are creating a temporary Test, that you are returning a reference to. But this temporary is destroyed at the end of the function resulting in undefined behaviour. This has nothing to do with the passed in str ref - its the tempora... |
68,234,953 | 68,234,983 | Why the "sizeof" operator can get the size of a type? | For example:
A complex class
class complex
{
public:
complex(double r = 0, double i = 0)
: re(r), im(i) {}
complex &operator += (const complex &);
double real() const { return re; }
double imag() const { return im; }
private:
double re, im;
};
I can get the size of complex by:
complex c(1, 2);
cou... | Objects of type complex are all of same size, hence you don't need to create an object to know its size.
sizeof(x) is a constant expression. It is not evaluated at runtime. A class definition is necessary and sufficient for the compiler to know the size of objects of that type. Thats also the reason you cannot use size... |
68,235,039 | 68,243,788 | Why is the program faster when I have the helper function after the priority function | So I have been working with leetcode for the past few months preparing for job interviews. An interesting phenomenon I came across was when I used a helper function after the main function it happened to be faster.
This took 4 ms according to leetcode
class Solution {
public:
int countSubstrings(string s) {
int n... | In order to make a good benchmark, you should run the code multiple times on a computer that you know what priority you get on it.
I have transformed your code so you can run it on your own machine:
here
Compiler Explorer lets you see the compiled code, and is useful for understanding changes within a code. You can che... |
68,235,085 | 68,235,099 | How to save some text into string including whitespaces? | I have a problem with C++, shown at the simple program below:
int main()
{
string n;
cin>>n;
cout<<n;
return 0;
}
I try to save some text into string, but when I write more than one word, it is saved only to the first space sign.
Input:
abba abc abd
Output:
abba
Expected output:
abba abc abd
Can it ... | Try this
std::string str;
std::getline( std::cin, str);
getline() is the member fucntion of istream class, which is used to read string with spaces
|
68,235,236 | 68,240,091 | Should we provide a definition for a discarded function used by a discarded variable's initializer declaration in global module fragment? | When I #include one header file in one module unit's global module fragment, I encountered some link error provided by MSVC and GCC together.
Firstly, I have one header file "Header.h" like this:
#pragma once
int f();
const int value = f();
And then, I defined a primary module interface unit [m1.ixx OR m1.cpp] like t... | “Discarded” in the context of modules just means that it’s not found by lookup from template definitions in the module (being instantiated as part of compiling a client). It doesn’t mean the same thing as a discarded statement in if constexpr. The definition of value plainly odr-uses f, so it must be defined somewher... |
68,235,476 | 68,236,258 | Not proper use of Random Generator for Gamma distribution draws in Rcpp | I wrote the following code in Rcpp, for generating Gamma Distribution random variables, however each time that I run it I take the same output. I read that in order to have different realizations I have to use a random generator as explained here Why is this random generator always output the same number
The code that ... | The Rcpp package interfaces the random number generators (and special functions) from R, while properly interfacing the (high-quality) RNG inside R itself.
So I recommend you rely on that as it is in fact easy to use:
> Rcpp::cppFunction("NumericVector mygamma(int n, double a, double b) { return Rcpp::rgamma(n, a, b); ... |
68,235,564 | 68,236,770 | GLSL: CPU-shared atomic loads | I'm working on a C++/Vulkan application that heavily relies on compute shaders. One of these must read (never write) buffer memory that might be concurrently modified by the CPU.
Assuming that the CPU and the shader use the appropriate atomic operations, could this work?
To put it in another way, can you safely perform... | There is no mechanism by which plain atomic accesses can simultaneously exist between the host and the GPU. You have to use a barrier or event and prevent the host from modifying the memory so long as the GPU is looking at it.
|
68,235,581 | 68,322,483 | Qt QTextBrowser/QTextEdit: Tab key changes bullet/ordered list indentation | I am using C++ and Qt6 and I am creating a text editor that mimics basic functionality of Word or Evernote for those that use it.
I want when the user presses the key tab for this to happen:
The second bullet is what I am getting and the third bullet is what I want.
I have this code ready:
QTextCursor cursor = ui->tex... | I have solved it!
I re-implemented the QMainWindow eventFilter for my class instance that inherits QMainWindow.
bool SummaryWindow::eventFilter(QObject *obj, QEvent *event)
{
if (obj == ui->textEditor)
{
if (event->type() == QEvent::KeyPress)
{
QKeyEvent *keyEvent = static_cast<Q... |
68,235,631 | 68,235,666 | std::pair substitution failed with std::size_t | #include <utility>
#include <vector>
using namespace std;
std::pair<std::size_t, std::size_t> func(const std::vector<int>& numbers, int target) {
for(std::size_t i =0; i < numbers.size(); i++)
{
for(std::size_t j = i; j < numbers.size(); j++)
{
if(numbers[i] + numbers[j] == target)
... | When you specifying template argument as std::size_t, the type of function parameter of std::make_pair becomes std::size_t&&, i.e. an rvalue-reference; i and j are lvalues and can't be bound to rvalue-reference.
Just letting std::make_pair do the template argument deduction like std::make_pair(i,j) (template parameter ... |
68,235,681 | 68,235,748 | One function that can be called with multiple function psuedonames/synonyms | First of all, this is completely for fun, and has little practical purpose, I guess.
What I'm attempting to do is. have 1 function, but I can call it with different function psuedonames.
so instead of doing:
calculate_result(int x, int y);
I could also do:
calculate_answer(int x, int y);
or I could even do:
calculati... | The answer is: pointer to a function.
#include <iostream>
using namespace std;
int calculate(int x, int y)
{
int answer = x + y;
return answer;
}
int main()
{
// calculate_answer can now be used as a synonym to calculate
auto calculate_answer = calculate;
cout << calculate_answer(3, 4) << endl;
return 0;... |
68,235,728 | 68,235,765 | I can't have two classes pointing at each other | This code
class x {
y* ptrY;
};
class y {
x* ptrX;
};
int main() {
}
Gives me these unhelpful errors
Am I doing something that is not allowed or there is a way around this
| When x is defined, y is not known yet, so x can't be compiled properly. One way around this is to use a forward declaration - essentially, you'd be declaring that "y is a class, and I'll define it later":
class y; // Forward declaration of y
class x {
y* ptrY;
};
class y {
x* ptrX;
};
int main() {
}
|
68,236,968 | 68,237,692 | Setting up a Qt6 project in CLion with CMake | I am trying to make a Qt6 application, however I do not like qtcreator so much so I would like to work in CLion. I have been trying to configure my project with CMake but I am kind of new to all that and I am stuck even though I have followed this "tutorial" on the jetbrains website: https://www.jetbrains.com/help/clio... | After further research I realized I was not using the good version of MinGW (hence the error message). I downloaded the 64bit version of MinGW and tried with that compiler itself and built the project correctly. Moreover I had an issue where it would compile fine but not run and return an error code. I had to put the Q... |
68,237,583 | 68,239,860 | Boost asio reading from the streambuffer after async_read_until stripes spaces | So after I use async_read_until to read until a delimiter there is some extra data that is left in the buffer and I have been trying to read it like this
void Connection::read_left_over(std::string &req, size_t &bytes) {
std::istream_iterator<char> itr(this->input_stream);
std::cout << buffer_.in_avail() << std::en... | This is behaviour of istream. You can get other behaviour using
std::getline
using std::streambuf_iterator
using the stream >> std::noskipws manipulator (which ends up calling stream.unsetf(std::ios::skipws) under the hood)
|
68,237,597 | 68,238,315 | Why are there three comparisons to add a second map element? | When I run the following code (with a line commented out) I get no output (no comparisons are made).
But the moment I uncomment the last line I get three lines of output (three comparisons are made). When a second item is added, 1-2 comparisons is understandable, but why a third?
#include <map>
#include <iostream>
usi... | In a visual studio debug build it generates a lot of extra code in the standard library to catch various bugs.
In the case of std::map after inserting a new value it checks that the comparator correctly returns false for comp(key, key) and therefore implements the required strict weak ordering.
If you switch to a relea... |
68,237,662 | 68,238,220 | Inserting a struct as a value in Multimap and Iterating the same to get the values | #include <stdio.h>
#include <map>
struct temp
{
int x;
int id;
};
int main()
{
temp t;
int key;
typedef std::multimap<int,struct temp> mapobj;
t.x = 10;
t.id = 20;
key=1;
mapobj.insert(pair<int,struct>key,t);
//mapobj.insert(1,t);
return 0;
}
I am new to STL multimap, I... | I think you need to make some minor code changes to fix the compile error as follows:
Add 2 brackets: mapobj.insert(std::pair<int,struct temp> (key,t) );
Add "struct temp" in mapobj.insert(std::pair<int,struct temp>(key,t)); (Note: You did not have the name of the struct: temp).
Please note that you should specify... |
68,238,144 | 68,238,283 | Boost Graph: with vertices as integral type, how to provide arguments to Edmund's arborescence algorithm that requires vertex iterators | I am trying to solve the problem of finding an arborescence in a directed graph. This functionality is not provided directly by the boost graph library. However, an implementation is available here that builds on boost graph library.
The interface provided by the author available here specifies the following function s... | Iterators are generalizations of pointers. Pointers are iterators, but more complicated things like whatever std::vector<T>::begin and std::vector<T>::return return and whatever std::back_inserter constructs are also iterators. The key thing about them that you appear to be missing is that if it is an iterator, then th... |
68,238,264 | 68,238,680 | C++20 Template Template Concept Syntax | With concepts, C++20 provides nice syntax like
template<typename T>
concept SomeConcept = true; // stuff here
template<typename T>
requires SomeConcept<T>
class Foo;
template<SomeConcept T>
class Foo;
where the two ways of concept restricting the class are equivalent, but the latter is just more concise.
If i now ... |
What is the correct syntax for declaring such a template template class with a concept restriction to the template template parameter?
The only way to write a constraint that depends on a template template parameter or a non-type template parameter is with a requires-clause. The shorter type-constraint syntax is only... |
68,238,804 | 68,238,939 | how to separate header and cpp file cmake | I'm trying to set up a chat app project and it looks like this:
project hierarchy
I've found some tutorials, but I cant find out how to set up this How would the CMakeLists.txt files look?
P.S. Maybe I'm not doing the project folder hierarchy correctly. Could you then tell me how to do it better?
| To he honest, I haven't got you structure well but answering you question - this is how you make your files executable in CMakeList.txt
What about including headers in source files, you can do it 2 ways:
Include header by relative path, e.g. #include "../../include/client/client.h"
What doesn't look good
Include head... |
68,238,856 | 68,239,022 | Understanding C++ variable number of input parameters to test_function(Test<T>...) | I have a generic class Test<T> and I want to have a function test_function() that has a variable number of Test<T> object input parameters with .... In the function, I want to iterate over all the parameters. The generic type T can be different across the parameters. Something like this:
template <typename T> class Tes... | There are multiple problems here.
First, the correct variadic template function declaration should be:
template <typename ...T> void test_function(const Test<T> ...tests)
But that won't solve all the problems. The first one is that all the parameters are const objects, therefore the class method must also be a const c... |
68,239,341 | 68,239,365 | Is there a standard library class for substrings? | I have a big read-only string that I scan for syntax and based on that simple syntax I extract a bunch of smaller strings that I use later for further processing. Based on testing, creating and copying most of the big string into the small strings is kind of a performance bottleneck (there are thousands of them per eac... | Yes, since C++17 you have std::string_view.
Example:
#include <iostream>
#include <string>
#include <string_view>
int main() {
std::string foo = "Hello world";
std::string_view a(foo.c_str(), 5);
std::string_view b(foo.c_str() + 6, 5);
std::cout << a << '\n' // prints Hello
<< b << '\... |
68,239,547 | 68,239,782 | Return bit positions without loops | Is there any way of finding bit positions without using loops (for/while) in C++, using std::bitset?
Suppose we have a binary number 11001 and we'd like to find all 0s positions.
Any sort of prebuilt, time-space efficient functions?
|
without using loops
we have a binary number 11001 and we'd like to find all 0s positions
Unroll the loop yourself.
void check(unsigned pos, unsigned number, std::vector<unsigned>& out) {
if (!(number & (1u << pos))) out.push_back(pos);
}
std::vector<unsigned> positions_of_0s(unsigned number) {
std::vector<uns... |
68,239,692 | 68,241,914 | my code seems perfect but showing wrong output. can someone help me what wrong am i doing here? | i have to return the max len of consecutive seq present in an array.
consider the example:-
N = 7
a[] = {2,6,1,9,4,5,3}
my code should return 6 but its giving 1. don't know how?
int findLongestConseqSubseq(int arr[], int N)
{
//Your code here
unordered_map<int,int> mp;
int ans=0;
for(int i=0;i<N;i++)... | There are two problems with your implementation.
The first issue is the code:
if(mp.count(arr[i])>0){
continue;
}
this code is not sufficient to ensure that repeated numbers do not make it into the rest of your loop (to see why this is, consider what happens with neither len1 or len2 are ze... |
68,239,801 | 68,239,885 | std::to_string return empty string when using std::allocator | I got the empty return of std::to_string when I use std::allocator. The code is:
#include <iostream>
#include <memory>
#include <string>
int main()
{
std::allocator<std::string> allocatorStr;
auto const pStr = allocatorStr.allocate(5);
for (int i = 0; i < 5; ++i) { *(pStr + i) = std::to_string(i); }
fo... | To quote from cppreference, (emphasis mine):
[allocate] ... allocates n * sizeof(T) bytes of uninitialized storage
In other words, there are no valid std::string objects there yet and trying to use them (even as the target of a copy) invokes undefined behaviour (I got a segfault).
To fix this, use placement new to co... |
68,239,834 | 68,308,951 | Template argument deduction for aggregate template with array | Consider the following program:
template<typename T>
struct A { T t[2]; };
int main()
{
A a{1}; // only one value provided for 2-element array
return a.t[0];
}
In C++20 mode it compiles fine in gcc, but fails in Visual Studio with the error:
<source>(6): error C2641: cannot deduce template arguments for 'A'
<s... | GCC is right, the code should be accepted, and the type of a should be deduced as A<int> using class template argument deduction (CTAD) for aggregates.
N4868 (closest to the published C++20 standard) [over.match.class.deduct]/1 says (I've excluded some parts that aren't relevant here):
When resolving a placeholder for... |
68,240,214 | 68,247,617 | How can I fill the region between 2 lines in OpenCV c++? | I have this image with 2 curves:
How could I fill the region between the red and blue curve?
| Here is the simple way and code how you can get it:
Check each row pixel by pixel
If you meet non-black pixel index values 2 times, then save these points
Fill between these 2 points with the desired color
Here is the output and code:
Output:
Code:
#include <iostream>
#include <opencv2/highgui.hpp>
int main()
{
... |
68,240,538 | 68,341,271 | How to get ROS GSCam to Work in a Docker Container? | I am trying to use the ROS GSCam package in a Docker container to read from a camera stream and publish to a ROS topic. Using GStreamer via gst-launch works fine in the container. For example, running
gst-launch-1.0 -v tcpclientsrc host=10.0.0.20 port=7001 ! decodebin ! filesink location= xyz.flv
in the container succ... | From the answer given here I realized that my problem stemmed from the fact that the common ROS GSCam package (downloaded via ppa) uses GStreamer0.10, but because I was building the package from source inside the Docker image it used GStreamer1.0. Changing the build dependencies to
<build_depend>libgstreamer0.10-dev</b... |
68,240,700 | 68,247,050 | Changing memory address values and hex data | So i want to change the value of an address to something else.
Say if the value of the address is 42859105827 and the address is 0A2BC6FC, How would i change the value of this address?
Example:
Address | Type | Value
0A2BC6FC 4 Bytes 42859105827
| I think you'll need to reinterpret cast. This probably isn't a super safe way but should work:
size_t address = 0x0A2BC6FC;
int new_value = ...;
reinterpret_cast<int&>(address) = new_value;
|
68,240,712 | 68,240,750 | Searching a General Tree? Function is stopping at end of tree instead of searching the next branch | I have a general tree where the root's children are stored in a linked list as follows:
class node
{
int identifier;
node *parent;
std::vector<node *> children;
I am trying to implement a function that will search the tree and either return a pointer to the node whose int identifier matches the key to sea... | check if the child returned null before you return it
node* childfound;
for (node* child : this->children){
childfound = child->find(identifier);
if(childfound) return childfound;
}
|
68,241,147 | 68,313,004 | What's the best way to make DLL size as small as possible? | I am using LoadLibraryA to load my DLL's into my project. I've just started to notice their sizes are starting to get large as I keep adding more functions, etc. Are there any options in my project settings that can help reduce the size of my DLL's?
| As every other person mentioned, you can use compiler options to reduce your size. At first, try to tweak these options for better result. These options normally affect size of your code.
But if you have a lot of resources in your EXE/DLL, you will not see much difference. If you really need a small size in this case, ... |
68,241,250 | 68,241,309 | Confused about the scope of object when return it from a method | I create an vector object in a method, when I return the vector, it should be out of scope, but why the invoker method could still get the returned object. My code a following:
#include <iostream>
#include <string>
#include <vector>
class Person{
public:
std::string name = "jack";
};
std::vector<Person> test() {
... | The result object of the function call is copy-initialized from vec, before vec (and other local objects) gets destroyed.
For return statement:
The copy-initialization of the result of the function call is sequenced-before the destruction of all temporaries at the end of expression, which, in turn, is sequenced-before... |
68,241,327 | 68,241,424 | Passing Int* and double* from C++ to C# | I am trying to retrieve two arrays from C++ plugin to be used in C#.
The code is as follows:
C++
The function "funcplugin" has a void return type and I wish to return two single dimension array's of length 16 and 24.
extern "C" __attribute__ ((visibility ("default")))
void funcplugin(int* corners, double* points)
{
... | In the C++ code, the pointers are being passed in by value, so no matter what addresses the function sets them to point at, the caller will not be able to receive these addresses. To accomplish that, you would need to pass the pointers by reference or by pointer, eg:
extern "C" __attribute__ ((visibility ("default")))
... |
68,241,858 | 68,242,014 | How to pass pointer array to function template in C++ | i have a template class and inside i have function operator> which should call a template function from another file. How do i set the function parameters or how do i have to pass the arguments to this function.
I have removed the code from the lambda function and the cmpFn, because this should be irrelevant for this e... | You need to declare your compare function like this:
template <typename T>
bool cmpFn(T *a, T *b, int (*fnEq)(std::type_identity_t<T>, std::type_identity_t<T>))
{
return false;
}
But std::type_identity_t is C++20 and for previous versions, you need something like this for it:
template< class T >
struct type_identi... |
68,242,421 | 68,242,432 | Array values output incorrectly | I am having a very simple function to input values. But I am getting a wired output. I get different values to what I am inserting? What am I doing wrong?
#include <iostream>
using namespace std;
void testFunc(float arr[], int sizeOfArray);
int main() {
int sizeOfArray = 4;
float arrA[] = {};
float arrB[]... | The float arrA[] = {} creates an array of floats with 0 size. When you iterate over it, you access an out of bound memory in here:
for(int i=0; i<sizeOfArray; i++);
You can list initialize an array and not specify the size of an array, using braces {...}. But in such case, the size is deduced from the elements in the ... |
68,242,477 | 68,243,881 | Why no compile error for `std::reference_wrapper<void>` in C++20? | #include <functional>
#include <type_traits>
template<typename T>
requires (!std::is_void_v<T>)
struct A {};
int main()
{
A<void>* p1{}; // compile error as expected.
std::reference_wrapper<void>* p2{}; // no expected compile error!
}
Now since C++20 has concepts to restrict the ... | Because no one has written the concept requires (!std::is_void_v<T>) for std::reference_wrapper. I agree, void should not be valid for std::reference_wrapper, and allowing void is probably an oversight from the standard.
You would think that std::reference_wrapper<void> wouldn't compile anyway, as void& isn't legal. B... |
68,242,576 | 68,265,788 | Macro which will not compile the function if not defined | Currently using to show debug output when in debug mode:
#ifdef _DEBUG
#define printX(...) Serial.printf( __VA_ARGS__ )
#else
#define printX(...) NULL
#endif
yet this still include the printX in the result code, and the parameters which have been applied still consume memory, cpu power, and stack size, so my question... | The macro
#define printX(...) NULL
replaces printX function call with all its arguments with plain NULL. This is a textual replacement that happens before a compiler is able to take a look at the code, so any nested calls inside printX, e.g.
printX(someExpensiveCall())
will also be completely eliminated.
|
68,243,063 | 68,246,865 | Read value from frida hooked native method basic_string parameter | Recently I started using Frida and playing with some native methods. But i have a problem with reading value of basic_string
Here is method which I'm hooking:
Here is JavaScript code which I'm using to hook method:
Interceptor.attach(Module.getExportByName('libsigning.so', '_ZN8Security4signEP7_JNIEnvP6rsa_stRKNSt6__n... | Problem was resolved using this frida code:
function readStdString (str) {
const isTiny = (str.readU8() & 1) === 0;
if (isTiny) {
return str.add(1).readUtf8String();
}
return str.add(2 * Process.pointerSize).readPointer().readUtf8String();
}
source: https://codeshare.frida.re/@oleavr/read-std-string/
fina... |
68,243,072 | 68,245,993 | How does GCC create an array on the stack without its size being given by a constant variable? | How does this example compile and run?
#include <iostream>
int main() {
int input;
std::cin >> input;
int arr[input];
return 0;
}
My understanding is that since the input's value is not known during compile time, it'd have to be a heap allocated array. Isn't the stack space for things like arrays (wit... |
My understanding is that since the input's value is not known during compile time, it'd have to be a heap allocated array.
While the C++ language rules do indeed say that you can’t do this, from a technical perspective about how the call stack is typically implemented this actually isn’t necessarily true. Generally, ... |
68,243,152 | 68,243,659 | What is memory location modification in C++? | C++ standard says:
6.9.2.1. Two expression evaluations conflict if one of them modifies a memory location (6.6.1) and the other one reads or modifies the same memory location.
But what counts as "modifies memory location"? The standard has mentions "modification" just 12 times before this sentence, and none of them i... | Most related rules I could find are (quotes from latest standard draft)
access [defns.access]
⟨execution-time action⟩ read or modify the value of an object
[Note 1: Only objects of scalar type can be accessed.
Reads of scalar objects are described in [conv.lval] and modifications of scalar objects are describred in [e... |
68,243,238 | 68,247,687 | Maximum Median competitive programming question | You are given an array consisting of N integers. Now you can perform one type of operation on it which is to choose any index i and increment ai by 1 i.e. ai=ai+1. With this operation, you want to maximize the median. Also, you can apply this operation at most K times. The median of the odd-sized array is the middle el... |
My thoughts are, they have asked for the maximum median and if we just sort and pick the middle element and increase it with k. Then it would be the maximum median.
Not really, because once it's incremented that element may very well not be the median anymore. Consider the example 1, 2, 1, 1, 1. The median is 1 (sort... |
68,243,388 | 68,243,412 | Convince a constructor to move an object a parent's constructor | I've been attempting to forward an object to a parent without having the object copied. I cannot seem to be able to do this, and don't know why.
Here is an example of the kind of thing I would like to do. It does not compile, however.
class Initialisee {
public:
Initialisee() = default;
Initialisee(... | Move operation is supposed to perform modification on the object to be moved from; but i is marked as const and can't be moved from. Especially, const Initialisee can't be bound to Initialisee&&, then it can't be passed to move constructor of Initialisee.
If your intent is to perform move operation it's better to decla... |
68,243,613 | 68,243,692 | Calculating arcsecant, arccosecant and arccotangent | I'm writing a wxWidgets C++ calculator application. I'm implementing the trigonometric functions (sin, cos, tan, arcsin, arccos, arctan, sec, csc, cot, arcsec, arccsc, arccot). How do I calculate arcsec, arccsc and arccot of a number n?
| For secant
sec(x) = 1/cos(x)
sec(x) = y <=> 1/y = cos(x) <=> x = acos( 1/y)
Thus
x = arcsec( y) = acos( 1/y)
The others are similar.
The arc functions have a caveat. For example if |y| > 1 then acos( y) returns nan.
You might want to include atan2 in your functions, as it is sometimes more useful than atan. For examp... |
68,244,265 | 68,244,592 | Conditionally override templated class member variable | Is it possible to override a class member variable based on the template parameter? If yes, how?
Roughly my problem: I have my array class (it is a dynamic array with some special functionality I need) as a base which looks like:
template<class T>
class Array
{
protected:
uint size_;
uint capacity_;
T *data... | If I understand correctly, what you want is a partial template specialization:
// This specialization of the class will be used when N > 1
template<uint N>
class SOA : public std::conditional_t<N == 1, Array<double>, Array<Array<double>>> {
protected:
Array<double> data_[N];
// ...
};
// This specialization w... |
68,244,305 | 68,244,513 | How is it that this file handling code doesn't read from files even though it saves data in the files? | I am working on a college project and this is a railway ticketing system I developed. Now, the problem is that the data is being saved on the files created but when I want to read that data from the files nothing shows up in the console window. I have tried altering it many times but the problem stays there. I can't se... | Changing the char b[13] to string b has worked for me.
else if (choice == 4)
{
string b;
cout << "\n\nPress 1 to display Rawalpindi to Lahore Queue";
cout << "\nPress 2 to display Lahore to Karachi Queue";
cout << "\nPress 3 to display Rawalpindi to Karachi Queue"... |
68,244,629 | 68,246,880 | nth odd digit palindrome number | The following is the code of an nth even length palindrome, but i wanted to know the code for nth odd length palindrome.
#include <bits/stdc++.h>
using namespace std;
// Function to find nth even length Palindrome
string evenlength(string n)
{
// string r to store resultant
// palindrome. Initialize same as s... | If you want an odd length palindrome (i.e. 101 for an input of 10 or 1234321 for an input of 1234), you might be able to replace the for loop with:
for (int j = static_cast<int>(n.size()) - 2; j >= 0; --j)
res += n[j];
(note n.length() - 2 rather than n.length() - 1)
This will skip the last character when ... |
68,244,713 | 68,244,757 | Is it possible to call a consteval function with a non-const reference parameter? | If I understood the rules for immediate functions correctly, the following is a legal usage:
consteval void func(int& a) { /* Anything here... */ }
Is it possible to call this function? I could not find any way to do so as consteval forces that this has to be called in a compile time expression, but int& a forces it t... |
but int& a forces it to be a runtime expression because of the missing const
No, that's a gross oversimplification and not how constant evaluation works. We can have moving parts (non-const qualified objects) as part of the evaluation. So long as they obey a strict set of rules that are checked when evaluating the co... |
68,244,907 | 68,766,370 | How to use 'UWidgetLayoutLibrary::GetMousePositionOnViewport(...)' in Unreal Engiene 4.26 C++? | I created simple class, who implemented AActor. In this class i want get mouse position in game-dispaly. I know, that i must included 'Blueprint/WidgetLayoutLibrary.h' in *.cpp-file and in method 'Tick' write the following:
FVector2D mousePosition = UWidgetLayoutLibrary::GetMousePositionOnViewport(GetWorld());
so that... | Maybe you have found the answer now, but this question has been bothering me for several days, so I decided to reply to you here, just add "UMG" in the specified position in Project.build.cs, maybe this question is too simple, there is almost no answer online.But for those who are just learning Unreal and C++, it is no... |
68,244,957 | 68,257,363 | Overload operators on different templated types with C++ concepts | I am trying to provide out-of-class definitions of arithmetic operators +-*/ (and in-place += etc.) for differently templated types. I read that C++20 concepts is the good way to go, as one could constrain the input/output type to provide only one templated definition, although I could not find much examples of this...... | template<int n, typename T, Vector<n, T> V>
V operator + (const V& lhs, const V& rhs) {
return V([&] (int i) {return lhs[i] + rhs[i];});
}
here, you have to have a way to deduce n and T. Your V does not provide that; C++ template argument deduction does not invert non-trivial template constructs (because doing so i... |
68,245,109 | 68,246,675 | Read uchar value from hooked method using Frida | How can i read value of uchar* ?
I tried many ways, it's code which i used:
Interceptor.attach(Module.getExportByName('libsigning.so', 'EVP_DigestSignFinal'), {
onEnter: function (args) {
console.log("RSA.doFinal() [VALID]")
console.log("arg0: OpenSSL object")
console.log("arg1: " + Memory.r... | The method you hook is documented
int EVP_DigestSignFinal(EVP_MD_CTX *ctx, unsigned char *sig, size_t *siglen);
According to it's documentation the second argument receives the created signature:
signs the data in ctx and places the signature in sig. If sig is NULL
then the maximum size of the output buffer is writte... |
68,245,178 | 68,249,654 | How can I take average of second column for degenerate values of first column in c++/python or using any other linux command? | I have a collection of data in a text file arranged in two columns. What I want is to calculate the average value for repeating numbers in the first column. e.g. for the first three rows take one average of the second column and so on. I will be grateful for any help you can provide.
0.628319 0.123401
0.628319 0.... | Put the data in an Excel file and read it into a Pandas DataFrame. Compute the mean of the second column grouped by the first column.
import pandas as pd
# header=None because there are no column headers in my XLSX file
# Column names will be integers: 0 and 1
data = pd.read_excel("physics.xlsx", header=None, engine=... |
68,245,760 | 68,245,815 | Can I access a location in vector which I haven't declared? | Suppose my vector size is defined as 6.
vector<int>v(6);
But when I output , it doesn't give me error.
cout<<v[7]; //works
I know how vector actually grow , they will predefine some size x and the double it. So it can be acceptable for position 7.
But it still works for position 10000 why?
Why can I access a memory l... | The answer can be read in the C++ reference.
Here you can read that no boundary check will be done and no new element will be inserted. You simply have undefined behaviour.
So, in moredetail:
using an index operator with an index bigger than the size of the vector, will not increase the size of the vector and add new ... |
68,246,216 | 68,246,556 | C++ Makefile on "complex" tree structure | I have found a lot of related questions, but I was still not able to make my own Makefile.
This makefile is using Mingw64 on Windows, and I want it to run on *nix, currently Debian, but I would like to be able to make it run on Alpine too, as it's used in a Docker container.
The project tree structure is something like... | Consider the rule...
$(OBJS): $(SRCS)
$(CXX) $(CXXFLAGS) -c -o $@ $< $(LIBS)
This tells make that all items in $(OBJS) depend on all items in $(SRCS). But the command...
$(CXX) $(CXXFLAGS) -c -o $@ $< $(LIBS)
...always compiles the first dependency as identified by $<. It just so happens that in your case $< is... |
68,247,144 | 68,470,144 | Using DISM Api to Capture Image Programatically within Windows PE Environment | I've been going through the windows documentation for the Dism API with the goal of writing an exe in C++ (or whatever language can accomplish this) that can create a WIM image while running in Windows PE. I found a .NET Wrapper for the Dism API that seems like it might be useful for this purpose, but I'm unsure if a .... | I work on a project that works with DISM in WinPE quite a bit. We configure WinPE with all the .net packages as described here. Then WinPE can be configured to start an application.
I use c#, but you can do managed apps in c++ as I'm sure you know. I find putting c# code into WinPE substantially easier, but that's more... |
68,247,332 | 68,247,712 | Windows multi-threading enforcing thread priority | What I'm expecting to happen:
Since the process affinity is restricted to a single core, all the threads of the current process have to compete for the execution time.
Since thread a has a higher priority than thread b and it never blocks, thread b is never executed.
What I'm seeing:
Thread b gets spuriously executed.
... | Priorities are not absolute. As soon as you use multiple threads, and all of the threads are in a runable state (that is, they are not suspended or waiting on a synchronization primitive), they will run sooner or later. Priorities only ensure that threads with a higher priority get scheduled with less latency / larger ... |
68,247,413 | 68,248,470 | Iterator for custom container | In my project I have some custom classes, with roughly the structure below.
Point, which represents a 2D int coordinate
struct Point {
int x;
int y;
}
Line, which represents a line drawn between two Points
class Line {
Point start;
Point end;
}
Polygon, which represents the polygon that is defined by numb... | Looking at your code again, satisfying forward iterator requirements would be tricky, because you essentially generate the lines on the fly. Hence I suggest making an input iterator.
operator++ should just increment m_ptr, nothing unusual. But you might want to store an std::vector iterator instead of a pointer (then, ... |
68,247,818 | 68,247,918 | Lambda capture (by value) of array is only copying the pointer? | I'm trying to capture (by value) an entire C-style array. The array seems to decay to a pointer... How do I prevent this so that the whole array is captured?
Code:
#include <iostream>
int main()
{
char x[1024];
std::cerr << sizeof(x) << "\n";
[x = x] // copy
{
std::cerr << sizeof(x) << "\n";
... |
[x = x]
This one is equal to
auto x1 = x;
Which is actually decay to a pointer.
Just change your lambda capture to [x] to capture x by value. Also you can capture it by reference with [&x].
|
68,248,048 | 68,248,756 | how template instantiation doesn't lead to linking error | I know that the following code will result in a linking error:
//first.cpp
void test(){
//random code
}
//second.cpp
void test(){
//random code
}
so lets say that we have this function template:
template<typename T>
T test(){
//random code
}
and are doing this:
//first.cpp
...
test<void>();
//second.cpp... | The linker doesn't complain because the standard says so:
[basic.def.odr]/13
There can be more than one definition of a
...
— inline function or variable ...
— templated entity ...
In this regard, the linker handles them as if they were inline.
Note that they're not actually inline (for the purposes of optimizations... |
68,248,118 | 68,248,147 | Why there is a segmentation fault when calling printf from a class? | This is the relevant part (I think) of my source code
#include <iostream>
#include <cstdarg>
#include <cstring>
#include <cstdlib>
class Poly
{
private:
double *coefficients;
size_t degree;
inline double *cfp(size_t i);
public:
Poly();
Poly(size_t n, ...);
void Print() const;
~Poly();
}... | Looks like you corrupted your heap by writing past the end of your heap-allocation. I think your problem is here:
register double *cfs = new double(n);
Note that the above code allocates a single double set to value n, when I think what you wanted to do was allocate an array of n doubles. To do that you'd need to us... |
68,248,443 | 68,248,595 | Conversion of string to string * | I'm facing an error while assigning the reverse of a string to another string.
[Error] incompatible types in assignment of 'char*' to char[20]
This is my code
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char str[20],str2[20];
int length;
cout<<"Enter the string\n";
cin>>str... | As other people have recommended, a simple solution is to use std::string and not char [20], and then you can call method reverse() to do the job.
Here is my simple code:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string str, str2;
std::cout << " Please Enter The String : \n"... |
68,249,196 | 68,249,856 | Installing boost via vcpkg, I get the wrong toolset | I recently switched from using the Visual Studio 2015 IDE to the Visual Studio 2019 IDE. Around that same time I started using vcpkg for library installations. I've been using a pre-build version of an earlier version of boost, which I compiled myself. Thinking I ought to switch to a newer version of boost using vcpkg,... | The answer is a modified version of the GitHub issues,
Edit file from your VCPKG path
vcpkg\triplets\x86-windows.cmake
To add line
set(VCPKG_PLATFORM_TOOLSET v142)
|
68,249,219 | 68,249,369 | Passing RAII socket class to thread | I am making a HTTP server and I want to pass a socket client class to thread to handle the request. The problem is that the destructor gets called right after starting the thread so the socket gets closed.
The simplified version of code looks like this.
while (true) {
TcpSocket client = m_socket.accept();
std::... | Your RAII class TcpSocket should really be move only because it is logically wrong to make copies. Of course you could implement it like a std::shared_ptr but then the value semantics are a bit misleading. It would then probably be better to call it something that reflects its shared nature.
To make a class move only y... |
68,250,246 | 68,250,264 | Why does operator new need constructor to be public? | I was trying to find the relationship between operator new and constructor.
#include <iostream>
using namespace std;
class Foo {
public:
void* operator new(size_t t) {
cout << "new()" << endl;
}
void operator delete(void* ptr) {
}
Foo() {
cout << "... |
It seems like constructor is called by operator new right?
No. new Foo() is new expression, which attempts to allocate storage (via operator new) and then attempts to construct the object (via the constructor of Foo). So the object is constructed from the context of main(), which can't access the constructor of Foo a... |
68,250,848 | 68,251,946 | wxWidgets tips for dynamic list of checkboxes | I am using wxWidgets and trying to display tooltips for a dynamic list of devices (checkboxes):
for (DeviceHolder devH : *devices) {
uint64_t addr = devH.bleAddress;
wxCheckBox* cbox = new wxCheckBox(panel, wxID_ANY, AddrToString(addr));
checkboxsizer->Add(cbox, 0, wxLEFT, 20);
Connect(cbox->GetId(), wx... | Mouse events don't propagate upward, so whatever your trying to connect the event to in the line
Connect(cbox->GetId(), wxEVT_MOVE, wxMoveEventHandler(DeviceListDialog::onMove));
will never receive the event. Incidentally, you should use Bind instead of connect for various reasons.
Instead you should use the Bind me... |
68,250,858 | 68,251,206 | Graceful Win32 windowless process termination | I am working on a console application, written in C#, where I trigger Application.Run() to manage the system tray. The application itself is window-less.
Here's the challenge I am encountering - when the user closes the application, I need to do cleanup, and make sure that I remove the application icon from the system... | I think, you should implement own method of communication. IMHO, simplest way is using named event. Console application creates named event and sometimes checks it. External application sets event in case to exit first application.
This method works for Windows only.
|
68,251,281 | 68,252,284 | wxButtons not Scrollable When Receiving Data from WorkerThread in wxWidgets | I am using a wxNotebook to represent two tabs in my app. And in the 1st tab i have a wxScrolledWindow which receives data from the worker thread and displays it. The problem is that when the data is received from the worker thread and displayed onto the 1st tab(in terms of wxButtons), the buttons are not scrollable. Bu... | In MyScrolledWindow::onWorkerThread, in addition to calling Layout you need need to call FitInside to recompute the virtual size of the window. Add the line FitInside(); to the end of the method.
|
68,251,375 | 68,261,433 | disable all obvious elimination when compiling with gcc (without changing my source code!) | I want to keep all dead code (or anything that is even obviously can be optimized) when compiling with gcc, but even with -O0, some dead code are still optimized. How can I keep all code without changing my source code? The sample code is as follows, and when compiling with g++ -S -O0 main.cc, the if-statement will be ... | This is not possible with GCC to keep the conditional in this case since it is removed during a very early stage of the compilation.
First of all, here is the compilation steps of GCC:
Code parsing (syntax & semantics) producing an AST in GENERIC representation (HL-IR)
High-level GIMPLE generation (ML-IR)
Low-level GI... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.