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 |
|---|---|---|---|---|
69,313,891 | 69,315,133 | C++ open folder and fetch for subfolder | I'm finding a way to fetch all the subfolders in a known folder, and open them, then keep finding all the subfolders in that folder, keep opening them until there aren't any subfolders left more, then move to another folder in C++. Thanks for help!
| Following up on Serge Ballesta's comment.
If you can compile c++17, then make use of std::filesystem.
This SO provides a solution to 'LS' a specific dir. Need to add recursion.
However, if you are not able to run c++17, then you need to consider the OS you are working on.
If Linux and using GCC, use native "dirent.h"... |
69,314,116 | 69,325,936 | Why Python complains when called method of pybind11 type_cast-ed class that derives from C++ std::vector? | Using pybind11 I wrap a C++ lib that I cannot modify. An issue came from a class that derives from std::vector. (Notes: This my first pybind11 project. I am not 'fluent' in Python. I was looking for solution on the web but without success.)
Intro. Instance of E carries error data. E could be instantiated only by Es - a... | Since you want to use C++ member functions specific to Es, I think you shouldn't try to use type-casting in this case. If you would type-cast Es, that means your Python type will be a copied list of E objects but it wouldn't have methods like addFront - you'll have append etc.
What you can do is to wrap your type as an... |
69,314,747 | 69,314,772 | Robotics code not working right, giving redefinition of main error | This is my first time working on c++ and I have no idea how to fix this, I've asked around for a while but got no answer.
Deleting either of the int main() will cause an error, I also tried putting void and that didn't work.
error shown:
Redefinition of 'main' (63, 5)
#include "vex.h"
// Allows for easier use of the... | You have two main functions in your code. You must have only one. Either this one:
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
}
Or this one:
int main() {
// register event handlers
Controller1.Axis3.changed(onevent_Controller1Axis3Changed_0);
Controller1.Axis2.changed(... |
69,315,201 | 69,315,402 | Lambda Expression returning a bool flag not stopping condition variables wait() function | I have a WorkDispatcher class which holds Worker class objects as properties and launches their function in new threads.
Here is a example:
WorkDispatcher.h:
class WorkDispatcher
{
private:
std::thread m_reconstructionThread;
std::shared_ptr <Reconstruction::RGBDImageModel> m_currentRGBD;
public:
WorkDis... |
why doesn't the lambda work?
It works just fine, by itself.
However, C++ requires complex rules to be followed to properly synchronize multiple execution threads. Just because one execution thread sets a particular variable to a value does not guarantee you, in any way, that other execution threads will see the varia... |
69,315,273 | 69,316,613 | Process of conversion of types inside selection and iteration statements in C++ | According To C++ ISO:
The value of a condition that is an initialized declaration in a
statement other than a switch statement is the value of the declared
variable contextually converted to bool (7.3). If that conversion is
ill-formed, the program is ill-formed. The value of a condition that
is an initialized declara... | Comments already discussed that you are misinterpreting the two paragraphs. I will focus on the second. The important message is the following:
There are certain contexts where values might implicitly undergo converions even though the conversion is actually only possible explicitly.
Some code examples might help:
str... |
69,315,783 | 69,327,913 | Replace wildcards in a binary string avoiding three identical consecutive letters | Given a string S of length N, return a string that is the result of replacing each '?' in the string S with an 'a' or a 'b' character and does not contain three identical consecutive letters (in other words, neither 'aaa' not 'bbb' may occur in the processed string).
Examples:
Given S="a?bb", output= "aabb"
Given S="?... | Possible Implementation for rules in my answer.
This implementation is
left-to-right
single pass with 2 look-behind and 1 look-ahead (despite initial checking)
O(n) time complexity
can be O(1) space complexity since the context is at most 4 character
does not check for invalid Input
First merge the rules
a?? => ab... |
69,315,914 | 69,351,512 | Cmake - I have to run cmake --build . twice for a binary to be build | I have a problem with Conan and Cmake:
With conan i'm downloading my libraries and i want to compile with Cmake, here is my CMakeLists.txt :
cmake_minimum_required(VERSION 3.16)
project(BABEL)
set(CMAKE_CXX_STANDARD 20)
set(PROJECT_NAME BABEL)
set(SOURCES qt/main.cpp)
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmak... | So apparently there is a bug when writing all the command in one, typing them one by one solved the problem.
|
69,316,348 | 69,319,500 | PyPy ephem couldn't install on linux | I want to install ephem package on PyPy 3.7 but i couldn't make it. Because i got following message during install. I guess, i'm missing something.
gcc -pthread -DNDEBUG -O2 -fPIC -Ilibastro -I. -I/root/pypy3.7/include -c extensions/_libastro.c -o build/temp.linux-x86_64-3.7/extensions/_libastro.o -ffloat-store
extensi... | After the Ronan Lamy answer, I changed the body->OB_TYPE with Py_TYPE(body) and it worked for v4.0.1
|
69,316,388 | 69,317,230 | VSCode - custom snippet to create multiple different lines from selected C++ declaration | I have a line:
int INTVAR;
I would like to highlight this line, and run a snippet which automatically creates the following set of three lines in place of the single line above.
int INTVAR;
int intvar() {return INTVAR;}
void intvar(int val){INTVAR = val;}
That is, a function that it a getter/setter for the variable s... | The following snippet will also handle the different types:
"var set get":{
"prefix": "varsetget",
"body":[
"${1:int} ${2:VARNM};",
"$1 ${2/(.*)/${1:/downcase}/}(){return $2;}",
"void ${2/(.*)/${1:/downcase}/}($1 val){$2 = val;}"
]
}
I think it can be done with selected text but... |
69,316,420 | 69,317,280 | Boost module machine type 'X86' conflicts with target machine type 'x64' | I am building a 64bit program on Windows and need to link to a Boost library.
I am using other 64bit libraries successfully.
When I built boost I specified exactly that I need 64bit libraries using the command
`.\b2 address-model=64'
And it built the library I need:
`libboost-serialization-vc120-mt-s-x64_1_77.lib'
This... | Ok, I "figured out" how to get round this.
Basically, what I thought was happening was happening. Despite specifying a 64bit build and those libraries getting the name appropriate to a 64bit build, they were being built using the 32bit tool-chain.
To anyone from Boost who happens to see this - this is a REALLY bad expe... |
69,316,446 | 69,316,543 | Calling lambda with non-parameter template argument | MSVC 2019 allow me to define a lambda like this, where the template argument is not used in the parameter list:
auto foo = []<bool B>() {
return B;
};
However, it gives syntax error when trying to call it like this?
foo<false>();
What is the correct way to call a lambda with a non-parameter template argument?
| The template parameter is used with operator() of lambda.
(since C++20) If the lambda definition uses an explicit template parameter list, that template parameter list is used with operator().
You can specify the non-type template argument for operator(), call the lambda in an unnormal style as:
foo.operator()<false>... |
69,317,225 | 69,321,614 | Doxygen not auto-linking to C++ function with argument list in an undocumented namespace | I am trying to generate a link to a specific version of a function by specifying the arguments. If I just use the plain function name fn() then Doxygen auto-links to one version of the function. If I include the arguments then no link is generated.
Doxygen says I should be able to link using either of these forms:
<f... | Thanks to @albert I realised the function references need to be on a single line. But then I found another problem when I went back to the full version of the code.
Turns out that the problem is caused by being in a namespace.
The plain function name fn() is auto-linked to a version of the function.
If the arguments ar... |
69,317,311 | 69,317,794 | Makefile cant find directories C++ | I am working on a project related to Chess and I use a makefile to compile everything. My goal is to compile only files that have been changed,instead of everything everytime. Folder structure can be seen clearer here. make main.o results in an error :
fatal error: chesspieces.h: No such file or directory
5 | #incl... | The thing you didn't make clear in your question is the structure of your directory, or the directory you were in when you ran make. By reviewing the github repo we can see that your makefile is in the root directory and your source files are in subdirectories: for example you have src/main.cc, src/Application/chess.c... |
69,317,427 | 69,317,590 | C++ Must take either one or zero argument error (Operator+) | I have the following statement in my Hour.cpp file: (after class Hour)
Hour Hour ::operator+(const Hour& h1, const Hour& h2) const{
return Hour(h1.getHour()+ h2.getHour(), h1.getMinute() + h2.getMinute(), h1.getSecond() + h2.getSecond());
}
However, after running it I get:
error: must take either zero or one argu... | While overloading an operator as a member function, you can only another class as a second operand. The first operand is the object of the class itself. So, you have two options:
You can modify the overloading function as
Hour Hour::operator+(const Hour& h) const{
return Hour(hour_ + h.getHour(), minute_ + h.getM... |
69,317,629 | 69,318,409 | C/C++ recvmsg() causes error 'unaligned tcache chunk detected' but recv() is successful | I observe the below error when receiving UDP packets via Epoll:
'unaligned tcache chunk detected'
I've managed to locate which part of the code but it doesn't make much sense.
This is the original code:
while (_listen)
{
const int count = epoll_wait(_epollFd, &events[0], MAX_SOCKETS, -1);
assert(count != -1);
... | In your code you forgot to set member msg_name of the struct msg:
iovec iov;
char control[1024];
msghdr msg;
// add the following line:
sockaddr_in addr;
iov.iov_base = _buffer;
iov.iov_len = sizeof(_buffer);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = &control[0];
msg.msg_controllen = 1024;
// set the... |
69,318,119 | 69,318,511 | Generalizing input arguments for Eigen-types | The template guide provided by Eigen recommends using Eigen::MatrixBase to implicitly deduce template parameters to functions. In this example I want to pass an expression:
#include <iostream>
#include "Eigen/Dense"
template <typename D>
void eval(Eigen::MatrixBase<D>& in, Eigen::MatrixBase<D>& out)
{
out.array() ... | You have to use two template parameters and make the input reference refer to a const type. The issue is that the product operator will return a const value.
Like this
template <typename U, typename V>
void eval(const Eigen::MatrixBase<U>& in, Eigen::MatrixBase<V>& out)
{
out.array() = in.array() + 1;
}
|
69,318,879 | 69,319,138 | process a string using regular expression with C++14 | I need to extract 3 vars from a string in C++14. The string format is:
a single uppercase char + `->` + a single uppercase char + `,` + a number
For example: A->B,100, C->D,20000, E->F,22. And I want to extract both single uppercase chars and the number, like A, B, 100. So far I can write a tokenized function to separ... | With regexes in C++ there is one thing you need to know : you need to do the iteration over multiple matches yourself. Here's an example :
#include <iostream>
#include <regex>
#include <string>
#include <vector>
//-----------------------------------------------------------------------------
// if you're going to token... |
69,319,035 | 69,319,421 | How to use a shared_ptr from interface implementation | Let’s say that DoSomething method is the implementation of an interface. I can’t change its signature.
How could DoSomething instantiate MyClass2 with the second constructor and provide a smart pointer to the current instance of MyClass (not a copy) ?
#include <Windows.h>
#include <iostream>
class MyClass;
class MyC... | The only way for this to work is if DoSomething has access to a smart pointer pointing to the instance of MyClass. You can't place a shared_ptr in MyClass because that would create a reference loop, creating a memory leak.
However, there is another type of smart pointer: weak_ptr. It was designed for pretty much this p... |
69,319,153 | 69,319,542 | Iterator concepts are weaker than the corresponding named requirements, which ones apply to the non-range standard algorithms? | In C++20 we got concepts for iterator categories, e.g. std::forward_iterator corresponds to named requirement ForwardIterator.
They are not equivalent. In some (but not all) regards, the concepts are weaker:
(1) "Unlike the [ForwardIterator or stricter] requirements, the [corresponding] concept does not require derefe... |
Do they still use the same iterator requirements in C++20 as they were pre-C++20, or did the requirements for them get relaxed to match the concepts?
The existing std:: algorithms still use the named requirements. For instance, [alg.find] has both:
template<class InputIterator, class T>
constexpr InputIterator find... |
69,319,268 | 69,319,355 | What is the /d2vzeroupper MSVC compiler optimization flag doing? | What is the /d2vzeroupper MSVC compiler optimization flag doing?
I was reading through this Compiler Options Quick Reference Guide
for Epyc CPUs from AMD: https://developer.amd.com/wordpress/media/2020/04/Compiler%20Options%20Quick%20Ref%20Guide%20for%20AMD%20EPYC%207xx2%20Series%20Processors.pdf
For MSVC, to "Optimize... | TL;DR: When using /favor:AMD64 add /d2vzeroupper to avoid very poor performance of SSE code on both current AMD CPUs and Intel CPUs.
Generally /d1... and /d2... are "secret" (undocumented) MSVC options to tune compiler behavior. /d1... apply to complier front-end, /d2... apply to compiler back-end.
/d2vzeroupper enab... |
69,319,480 | 69,320,030 | Why do all my items go to unordered_map bucket 0? | This is the log (truncated) from my analysis of the hashmap:
unsigned nbuckets = octree->Nodes.bucket_count();
LOG(Error, "bucket size = {0}, kk = {1}", nbuckets, octree->Nodes.max_load_factor());
for (auto& x : octree->Nodes) {
LOG(Warning, "Element [{0}:{1}] is in bucket {2}", x.first.morton, x.second.position, ... | Your hash function is very bad. The greatest common divisor of the morton values you shown is
GCD(132120576, 115343360, 98566144, 81788928, 65011712, 48234496, 31457280, 16515072, 14417920, 12320768) = 2^18 = 262144
It is divided by 512. All values go to the (first) bucket 0.
You can try
return pos.morton % 511; // or... |
69,319,600 | 69,319,643 | How to extract one row of a 2D string vector to vector of double? | I have a function to calculate moving average:
void MovingAverage(double inputSeries[]
, size_t inputSize, size_t window, float* output )
My train of thought to do my calculation:
construct a loop and extract one row of vec2D each time
use the MovingAverage function to get output
For the first step... |
I tried vector<double> copyRow(vec2D[0].begin(), vec2D[0].end()); but it doesn't work because the 2D vector is string type.
You can make use of the algorithm function std::transform from <algorithm> to do this.
Since the first element of each row cannot be transformed to a double , you can skip it by starting from on... |
69,320,075 | 69,328,012 | When is an ellipsis needed when dealing with parameter packs? | I'm trying to understand some code from cppreference.com. The relevant part is here
template<typename... Ts>
std::ostream& operator<<(std::ostream& os, std::tuple<Ts...> const& theTuple)
{
std::apply
(
[&os](Ts const&... tupleArgs)
{
os << '[';
std::size_t n{ 0 };
... | Ellipses are needed there because sizeof...(Ts) is a special form of sizeof that returns the size of a parameter pack. Ordinary sizeof(Ts) could not be used for this purpose because it needs to remain possible to use standard sizeof behavior in expanded patterns i.e. sizeof(Ts) returns the size of an individual type in... |
69,320,259 | 69,328,603 | UE4 add Widget Class BP which inherits from UUserwidget in BP Editor? | I have a AActor class in cpp. I created a BP inherits from it named My_Actor_BP. In cpp class i declared some UPROPERTY :
UPROPERTY(EditAnywhere, Category = "Event Section")
TArray<UUserWidget*> Event_Dispatcher_0;
UPROPERTY(EditAnywhere, Category = "Event Section")
TArray<UUserWidget*> Event_Dispatcher_1;
UPRO... | In the case where you want your user to specify the class of an object to be managed by another object, you want to use the TSubclassOf<> template. In the code above, you're asking the property to point to an actor, but that actor hasn't been created yet. What you want to do is point to the class, and you can then crea... |
69,320,288 | 69,320,345 | Different ways of checking for a bit | quick question here...
What is the difference between...
if ((flags & bit1) == bit1) {
// ...
}
and...
if (flags & bit1) {
// ...
}
?
That's all. Pretty sure this has been answered before, but I haven't been able to find it.
| The first checks whether flags has all of the bits set where bit1 is also set. The second checks whether flags has any (i.e. at least one) of the bits set where bit1 is also set (or vice versa; in other words, whether there's any common set bits). If bit1 has a single bit set, then there is no difference between "any" ... |
69,320,320 | 69,320,398 | std::invoke does not like variadic template member functions? | I am trying to call a variadic function template using std::invoke() and std::apply().
And I apologize ahead of time, because I'm basically dropping a snippet of code here and asking someone to help me understand the error messages to solve the problem.
So, in the example code below,
std::invoke() on the non-variadic ... | The std::invoke expect a callable function. The funcn is a function template, and you need to instantiate to get a real function out of it and there-by you can take the address of it.
That means (explicitly) provide the template parameter to the function, how you want to instantiate it, so that std::invoke can see the... |
69,320,322 | 69,320,820 | Sorting array of objects in c++ | I'm a newbie and this is my first question. So I am working for a task organizer and I want to organize list of tasks by their "urgency" value. Here is my code:
#include <iostream>
#include <math.h>
#include <vector>
#include <stdlib.h>
#include <list>
using namespace std;
struct Task {
public:
string name;
f... | In your case you can use the std::sort function, defined in <algorithm> header, on the p vector defining a custom compare function:
std::sort (p.begin(), p.end(), sortTaskByUrgency);
where sortTaskByUrgency() is defined as:
bool sortTaskByUrgency(const Task& lhs, const Task& rhs)
{
return lhs.getUrgency() < rhs.ge... |
69,320,400 | 69,320,704 | Compare two numbers in a QString | There are two values:
QString str1 = "3.5.8", str2 = "20.3.6";
Let's imagine that these two numbers represent the software version, as it were.
It is known that QString compares character-by-character.
What if we approach this decision in this way:
str1.replace(".","");
str2.replace(".","");
int n = str1.toInt();
int ... | The QVersionNumber class was designed to solve this problem (requires Qt 5.6+):
QVersionNumber version1 = QVersionNumber::fromString(str1);
QVersionNumber version2 = QVersionNumber::fromString(str2);
if (version1 > version2)
{
qDebug() << "YES";
}
else
{
qDebug() << "NO";
}
|
69,320,703 | 69,320,774 | Recording how much time is required to run a portion of code and store it to an array in C++ | Need help in recording time taken to run several parts of code in C++. I need to store these times to an array for use later. In MATLAB I would do something like this;
for i=1 : n
tic
this is some stuff I want to run();
array[1,i] = toc;
tic
this is some other stuff I want to run();
array[2,... | You can use std::chrono::steady_clock::now() to get the current time (tic in your exemple).
You can find more details in this answer.
For a 2d array, a simple std::array<T, n> where T is some kind of std::tuple should do the trick.
|
69,320,918 | 69,321,080 | Why does taking `istream&` to a temporary `stringstream` work, but not when taking `stringstream&`? | Consider the following code, it compiles and runs:
#include <iostream>
#include <sstream>
struct Foo {};
void operator>>(std::istream &, Foo) {
}
int main() {
std::stringstream{} >> Foo{};
}
However, if I change std::istream to std::stringstream, I get an error:
c.cpp: In function 'int main()':
c.cpp:7:25: error: ... | As strange as it might seem, this code is well-formed. It should always compile. See Godbolt. It should also compile when the operator>> overload is changed to take std::stringstream&.
The reason is that there exists a special rvalue operator>> overload for classes derived from std::ios_base, marked (3) here:
template<... |
69,321,843 | 69,323,061 | Wrong overload selected when implicity converting to a const type | Consider the code below:
#include <iostream>
// General overload using a template
template <typename SomeType>
void some_func(const SomeType p) {
std::cout << "Using the general function" << std::endl;
}
// Specific overload, accepting a 'const double*' type
void some_func(const double* p) {
std::cout << "Usi... | During template instantiation, this const SomeType p would turn into double* const p which is a better match than const double*. That is, the template's parameter would become a const-pointer to mutable data.
In the template function, you can actually modify the data through that pointer, so it can be assumed it is a ... |
69,322,094 | 69,322,144 | operator[] caller's site source location current workaround | sadly, the current source location can't be used directly in the parameter list of operator[], as this operator has to have only one argument. However, is there a workaround so I can get the callers source line? Consider this code for example:
#include <iostream>
#include <string>
#include <source_location>
struct Te... | Found a solution:
#include <iostream>
#include <string>
#include <source_location>
#include <string_view>
#include <concepts>
struct string_like
{
std::string_view strView;
std::source_location s;
template <typename T>
string_like (T strView, std::source_location s = std::source_location::current())
r... |
69,322,194 | 69,322,221 | Conditionally enable member function of base class | I have some classes similar to:
class A {
void func();
};
class B1 : public A {
using A::func;
};
class B2 : public A {
void func();
};
Because class B1 and B2 in my project share most things, I want to make them as a common class that is distinguished by a template parameter:
class A {
void func();
... | You can use a specialization:
template<bool Use>
class B : public A {};
template<>
class B<false> {};
If the rest of the class is common, you can join them:
template<bool Use>
class C : public B<Use>
{
int i;
};
|
69,322,437 | 69,323,026 | Getting all Polite numbers below a certain number | I am trying to write a C++ program that displays all polite numbers that are below a certain number. So for example, if someone were to enter 6, then I would want to print out 3,5,6. I would want to print out 3,5,6,7,9 if the number 9 was to be entered.
I've already done the two for loops. I just can't figure out how t... | You can break this down into two smaller problems.
Here's an example of an implementation. There are likely far more efficient ways to do this, but this should give you an idea of what needs to be done.
// calculate the sum of all integers between "start" and "end" inclusive.
// hint: the sum of integers between 1 and ... |
69,322,519 | 69,322,572 | Is taking a substring in python an O(n) operation? | In C++ if I were to remove the first character from a string it would look something like:
string s = "myreallylongstring";
s = s.substr(1);
and this would be O(1). [correct me if I'm wrong about that]
However in Python's "immutable string" world, does this code run in O(n)?
s = "myreallylongstring"
s = s[1:]
Would i... | Slicing any built-in type in Python (aside from memoryview) is O(n) in the general case (main exception being a complete slice of immutable instances, which usually returns the original instance without copying it, since it's not needed).
A list of characters wouldn't help; removing a character from the beginning of a ... |
69,322,614 | 69,327,507 | Can you write depth values to a depth buffer in a compute shader? (Vulkan GLSLS) | I have a raytracer that I need to use in combination with traditional triangle projection techniques, I need to make the raytraced image be able to occlude projected triangles. The easiest way would be to write depth values directly to a depth buffer.
Apparently imageStore can only work with color images. Is there a me... | https://vulkan.gpuinfo.org/listoptimaltilingformats.php
It would appear that most implementations don't allow using depth images as storage images. I suggest creating an extra image and copying/blitting it to the depth image.
|
69,322,655 | 69,322,858 | Why "terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::at: __n (which is 0) >= this->size() (which is 0)"? | So, I keep receiving the
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::at: __n (which is 0) >= this->size() (which is
0)
message when I try to run my code. What I'm trying to do is to make it so that it outputs the double stored between the first curly brace and the comma i... | The first problem is this:
std::string nm_1;
nm_1.at(temp) = ...
You can't overwrite characters that don't exist in the string. You should rather append to the string. The easiest would be using += operator:
nm_1 += ...
The second problem is with this:
std::string nm_1;
for (...) {
std::string nm_1;
nm_1 += .... |
69,322,775 | 69,322,843 | Class instances not retaining data | I'm running into snags where class instances that I'm storing within a management class are not retaining their data. I wrote out the core concepts that I'm wrestling with into an example here: https://onlinegdb.com/KFqNSz2r6
I have an Action class that acts as a container for some arbitrary action. It's primary functi... | In your original version, the problem is that when you iterate over the actions, you make copies of the actions instead of referencing them.
In for (auto action: _actions) the action is copied. Use for (auto&& action: _actions) instead.
The version using pointers, doesn't have that problem and once the difference betwe... |
69,322,948 | 69,322,973 | My division function returns a zero. Should I declare x differently in main? | #include <iostream>
using namespace std;
int division(int c, int d);
int x = 2;
int y = 2;
int division(int c, int d)
{
return (c/d);
}
int main()
{
cout << "Hello World!\n";
int x = division(x,y);
cout << x;
return 0;
}
I expected the code to show 1 after Hello World!, but it prints 0.
I remov... | This expression:
int x = division(x,y);
is equivalent to writing this:
// 'x' was defined globally somewhere here before
int x;
x = division(x, y);
This shadows the previous x variable defined globally and defines a local variable x which again is uninitialized so after passing it in the division() function, your cod... |
69,323,135 | 69,323,250 | What actually is done when `string::c_str()` is invoked? | What actually is done when string::c_str() is invoked?
string::c_str() will allocate memory, copy the internal data of the string object and append a null-terminated character to the newly allocated memory?
or
Since string::c_str() must be O(1), so allocating memory and copying the string over is no longer allowed. ... | Since C++11, std::string::c_str() and std::string::data() are both required to return a pointer to the string's internal buffer. And since c_str() (but not data()) must be null-terminated, that effectively requires the internal buffer to always be null-terminated, though the null terminator is not counted by size()/len... |
69,323,228 | 69,323,242 | My computeAverage function is not returning value c++ | The problem I am facing is my computeAverage() function is not calculating the average of marks.
// computeAverage receives the array with the test scores, and its size,
// as paramaters, computes the average and returns the average value.
// Uses the local variable average to store temporary and final values.
// Uses... |
I have used this computeAverage(&theScores[arraySize], arraySize) to call the function
Because you need to simply invoke it as
result = computeAverage(&theScores[0], arraySize);
Or more generally:
result = computeAverage(theScores, arraySize);
As you have it now, you are passing the set of elements past the end of ... |
69,323,327 | 69,323,677 | Why does the C++ array not work beyond the 4th element? | I am learning C++ and had an assignment that asked to take two numbers and insert them into an array. First number is the base number the second number was the array length. The length of the array would be the number of times the base was multiplied by the exponent.
For example, if base was 2 and array length was 4 th... | I would first fix your code indentation to make code blocks more clear:
1 #include <iostream>
2 using namespace std;
3
4 int main()
5 {
6 int power, powarray[power];
7 double base;
8
9 while(power >= 0) {
10
11 cout << "Please enter a base number.\n";
12 cin >> base;
13 c... |
69,323,375 | 69,323,615 | How to make a C++ map with class as value with a constructor | I have a class that has a constructor. I now need to make a map with it as a value how do I do this? Right now without a constructor I do.
#include <iostream>
#include <map>
using namespace std;
class testclass {
public:
int x = 1;
};
int main()
{
map<int,testclass> thismap;
testclass &x = thismap[2];
}
If I a... | This is how you can add items of your own class to your map.
Note : I used a string in testclass to better show difference
between key and value/class.
#include <iostream>
#include <string>
#include <map>
class testclass
{
public:
explicit testclass(const std::string& name) :
m_name{ name }
{
};
... |
69,323,387 | 69,323,425 | Printing each character of char array instead of each partial one | Recently I found an interesting question in my exam: what would be printed by the following code. I wondered why this code didn't print sequentially each character of the char array (i.e "dcba") but each partial one (i.e "dcdbcdabcd"), in the reverse order.
By the way, I also want to know which topic is related to this... | char mess[] = "abcd"; means mess aka &mess[0] is the address of the string {'a', 'b', 'c', 'd', \0 }. ptr = mess + strlen(mess); means ptr initially points to the \0 of mess. In the loop ptr is decremented, and the subsequent printf() will print from where ptr points to till it sees \0 (i.e. tail of mess):
// initial:... |
69,324,126 | 69,350,133 | Resizing window cause my 2D Lighting to stretch | I am trying to implement a simple artificial 2D lighting. I am not using an algorithm like Phong's. However, I am having some difficulty in ensuring that my lighting do not stretch/squeeze whenever the window resize. Any tips and suggestions will be appreciated. I have tried converting my radius into a vec2 so that I c... | I'm going to compile all the answers for my question, as I had done a bad job in asking and everything turned out to be a mess.
As the other answers suggest, first I had to use an orthographic projection matrix to ensure that the light source position was displayed at the correct position in the viewport.
Next, from th... |
69,324,677 | 69,324,918 | GCC, GTK on Windows10 ld.exe: cannot find -ldwmapi | I'm pretty new to all this so excuse me if I put useless info, or forget useful ones on this post.
I'm trying to code a GUI with GTK in C on Windows10. So I have installed Msys2 in order to use GTK. In Msys2 I have installed the basic pkgs and all the GTK pkgs. Then on VScode I have installed an extension to link exter... | Different MinGW versions usually don't play well together.
Since MSYS2 ships it's own MinGW, you should uninstall the other version you have in C:\mingw, or at least remove it from PATH.
|
69,324,768 | 69,324,978 | C ++: library for conversion, Ex: binary -> decimal | binary -> hexadecimal etc | for my project i need to convert some numbers, exemple:
Binary --> decimal
Decimal--> binary
Binary --> hexadecimal
Hexadecimal --> binary
Etc...
I tried to create some functios, but it's long operation and i immediately need a converter.
Someone know a library for do this, then, where do i find it.
| Example some steps involving strings and numbers
#include <iostream>
#include <bitset>
#include <cassert>
#include <string>
#include <sstream>
int main()
{
auto binary = std::stoi("0110", nullptr, 2);
auto hex = std::stoi("f", nullptr, 16);
assert(binary == 6);
assert(hex == 15);
std::stringstre... |
69,324,896 | 69,324,936 | I convert Int to Float but the Id-Type doesn't change | I convert int to float and input 1.23 to 'a' but output is 1
what is wrong?
int a = 123;
static_cast<float>(a);
cout << typeid(a).name(); //int
cin >> a; //1.23
cout << a; //1
return 0;
| You have to asign the return value to a variable of the preferred type:
float result = static_cast<float>(your_var);
|
69,324,980 | 69,325,109 | Is shared_ptr<void>::reset() lock-free? | Imagine the following:
// SECTION A
MyClass* object = new MyClass();
std::shared_ptr<void> sharedObject;
// SECTION B (sharedObject is empty)
sharedObject.reset(object);
Is section B lock-free for an empty sharedObject? Or does it depend of the implementation?
| This depends on implementation.
Some pointers:
Overhead and implementation of using shared_ptr
Linking pthread disables lock-free shared_ptr implementation
|
69,325,050 | 69,325,321 | Customized widget in scroll area cannot be scrolled up or down after setting setWidgetResizable to true in qt | I have a problem when working with QScrollArea. Mainly, I want to add a customized widget into a scroll area to reach:
scroll widget if widget's size is larger than parent(scroll)
customized widget can automatically resize its size to fill all space of scroll if it is smaller than scroll
But I failed. Setting setWidg... | A possible solution is to set the sizePolicy to Minimum:
CustomWidget::CustomWidget(QWidget *parent) : QWidget(parent)
{
_size = QSize(120, 200);
for(int i = 0; i < 10; i++)
{
QRectF rect(QPointF(10, 60*i+2),QSize(100, 50));
_rects.push_back(rect);
}
setSizePolicy(QSizePolicy::Minimu... |
69,325,234 | 69,325,314 | My implementation of mathematical formula returns different value than calculator | using namespace std;
#include <iostream>
#define _USE_MATH_DEF
#include <conio.h>
#include <cmath>
int main()
{
const double e = 2.71;
double x, a, b, c, A, B, C, M;
cout << "Enter the value of x, a, b and c: ";
cin >> x >> a >> b >> c;
A = x + pow(sqrt(x + a), 3);
// cout << A;
B = x -... | Here I see some problems, namely A must be
A = x + pow(sqrt(x + a), 1.0/3.0);
B and C definition is correct, but M must be
M = pow(e, -1 * c * x) * C;
I would also like to point out that conio.h is a non standard header file and _getch() is non standard.
|
69,325,382 | 69,325,449 | How do i switch console output to horizontal perspective? Chessboard problem | I got asked by my teacher to do a chessboard, this is what it looks like when I build it
, my problem is that my teacher wants it horizontally like A8, B8, C8, and when I build it it's A8, A7, A6, so I kinda need to swap it but I don't know-how.
#include <iostream>
using namespace std;
int main()
{
for(char i = 65... | You have to print letters from A to H on each line. Also, printing numbers is much easier with a loop too.
for(int i = 8; i >= 1; i--)
{
for(char c = 'A'; c <= 'H'; c++)
{
std::cout << c << i << " ";
}
std::cout << '\n';
}
|
69,325,414 | 69,325,717 | Substitute all chess pieces in a .o file makefile | I have a makefile about a chess project. The current make Chess rule looks like this
Chess: main.o board.o player.o chess.o square.o piece.o position.o pawn.o rook.o king.o queen.o bishop.o knight.o
$(CC) main.o board.o player.o chess.o square.o piece.o position.o pawn.o rook.o king.o queen.o bishop.o knight.o $(OU... | I'm not sure if its even possible to combine many source files into a single object without using weird hacks. .o files are separate compilation units and its the linkers job to merge them to create binaries (e.g. libraries).
Your getting undefined references because what your actually doing for chesspieces.o is genera... |
69,325,425 | 69,325,465 | Access violation in custom comparator in priority queue | I have an issue were a program of mine throws an access violation.
Through debugging I found that for some reason the comparator-function is null.
However I am not sure on why that is or how to fix it.
I created a minimum working example to reproduce the issue:
#include "Tryout.h"
#include <queue>
struct Event {
u... | You need to specify the comparison function explicitly in the constructor
std::priority_queue<Event, std::vector<Event>, decltype(&CompareEvents)> mt_eventQueue( CompareEvents );
Otherwise the default argument will be used for the comparison function that will yield a null pointer.
The used constructor has the followi... |
69,325,512 | 69,325,863 | Is "overcrowding" a member initializer list a thing? | Let's say I have a class which has many members that do have a default constructor defined, so it's not required to initialize them in initializer list (like in the example below).
Is there a point, where initializing list gets "overcrowded" so much so that it's kinda awkward to read and it's better to assign things in... | You can use whitespace to make "overcrowded" code more readable. Example:
Foo(const std::vector<Thing>& things) :
m_Vec1(1.0f, 1.0f, 1.0f),
m_Vec2(1.0f, 1.0f, 1.0f),
m_Vec3(1.0f, 1.0f, 1.0f),
m_Vec4(1.0f, 1.0f, 1.0f),
m_SomeFile("some/path/to/file.txt"),
m_Model("some/pat... |
69,326,062 | 69,326,336 | Template explicit specialization in class using inheritance | Yesterday I asked about template explicit specialization in class.
Link.
Now I have the same purpose but now I wanna use inheritance to avoid code duplication. If I declare a function in the base class I cannot declare specialization of this function in the derived class.
My code:
#include <stdexcept>
#include <iostrea... | This will compile if you add a public template definition of fun in Derived.
But that will probably not do what you want.
In particular d.fun<bool>(); will not execute the implementation in Base, but the implementation in Derived.
You cannot specialize template functions in derived classes.
You also cannot use subtype ... |
69,326,243 | 69,357,867 | What is the correlation between RadioMedium's maxCommunicationRange parameter and Radio transmitter's power parameter? | Warm greetings to all
I want to have an understanding of the RadioMedium's parameter: maxCommunicationRange and the Radio transmitter's parameter : power
Indeed, I wanted my nodes don't communicate with neighbors if those later are beyond a threshold range. I parameterized as follow :
*.radioMedium.*.power = -110dBm
*.... | The maxCommunicationRange is the parameter of the MediumLimitCache submodule of RadioMedium. The medium limit cache is an optimization, so that the radio medium doesn't have to calculate the ranges with each transmitter/receiver pair from the power and sensitivity, but you can specify some values to use (by default the... |
69,326,545 | 69,326,708 | connect dynamically created buttons in qt5 | I have a scenario where I am asking the user for a number between 1 and 10 and creating that number of buttons of the type QPushButton. I then want to create a function such that when I click the button the number on the button gets printed.
| Just use a lambda function like this:
for (int i = 1; i < numButtons; i++)
{
QPushButton *btn = new QPushButton(...);
connect(btn, &QPushButton::clicked, [=]() {
// Do something with 'i'
}
}
|
69,326,660 | 69,326,874 | How to make a function call via pointer-to-member-function to a templated function? | I tried to compile the following code.
#include <iostream>
class Base
{
public:
template <typename T>
T fun()
{
std::cout<<"CALLED!"<<std::endl;
return T();
}
};
class Derived : public Base
{
};
template<class T>
T (Derived::*func_ptr)() = &Base::fun;
int main()
{
Derived d;
... |
However, I cannot think of what the syntax should be to call the function by this pointer. What is the syntax for it?
(d.*func_ptr<int>)(); // or other template argument
How is it explained? Where is this behavior defined in C++ standard?
func_ptr is a variable template. There are very few rules in the Standard s... |
69,327,002 | 69,346,099 | Arduino HTTP.post() returns -11 | I cannot not find a solution for this problem. Everything worked very well when I tried a month ago, but now, when I launch it, it does not work anymore. The problem occurs when I send http.POST(data); request to the given address, but Serial.println(httpResponseCode); returns -11. I've tested my domain URL on Postman ... | http.begin(client, authentication);
Please make sure the authentication URL is HTTP and not HTTPS.
|
69,327,086 | 69,327,189 | Global Array of Functions pointers | How to make a global array of functions in C++?
I want this:
//f.cpp
#include "head.h"
void f() {};
//g.cpp
#include "head.h"
void g() {};
//head.h
#pragma once
void f();
void g();
typedef void (*f_t)();
f_t Fs[2] = {f,g};
//main.cpp
#include "head.h"
int main() {
Fs[0]();
}
Something like this worked for me ... | Add one more file:
//head.h
#pragma once
void f();
void g();
typedef void (*f_t)();
extern f_t Fs[2];
//head.cpp
#include "head.h"
f_t Fs[2] = {f,g};
|
69,327,246 | 69,327,378 | Converting HEXA 64 bits numbers to int | I'm making a college job, a conversion between hexa numbers enclosed in a stringstream. I have a big hexa number (a private key), and I need to convert to int, to put in a map<int,int>.
So when I run the code, the result of conversion is the same for all the two hexa values inserted, what is incorrect, it should be dif... |
Firstly, the HEX numbers in your examples do not fit into an unsigned int.
You should clear the stream before loading the second HEX number there.
...
std::cout << "Result 1: " << static_cast<std::int64_t>(x) << std::endl;
ss.clear();
ss << std::hex << "0x3C29786A4F7E78255E9A965456A6D989A4EC37BC4477A934C52F39ECFD573... |
69,327,416 | 69,359,111 | MoveWindow does not scale the window when moving to a different screen | I have a Windows application with floating windows. I am running it on a multi-monitor setup (FHD, 4K). The application is marked as system-aware, so we pick the current DPI value for the primary monitor and scale according to that. After that, the OS bitmap-scales it. The application is running on Windows 10.
Now, whe... | So it depends on how the window is created. I fixed it by creating the window using WS_CAPTION style and then removing that style later. I am not sure what is does internally but it now scales correctly when it is moved to another screen either through mouse-drag or by using an API such as MoveWindow.
::CreateWindowEx(... |
69,327,986 | 69,328,453 | Reading array elements from string | I have an array of pairs<string,string> encoded into a database string, I am attempting to access the array element to eventually construct a std::map<std::string,std::string> but attempting to acccess array elements from my string gives me an exception
bool
test_json_map_string_string() {
std::string database... | get_to() is an assignment, and does not parse. What you want is:
json object_array = json::parse(database_string);
Example:
https://godbolt.org/z/WsrvEc5MK
|
69,328,493 | 69,401,578 | Why is compile-time execution significantly faster than runtime execution? | Contrary to what this question says, this piece of code is exhibiting some weird behaviour:
long long int fibonacci(int num) {
if (num <= 2) return 1;
return fibonacci(num - 1) + fibonacci(num - 2);
}
int main() {
auto t1 = std::chrono::high_resolution_clock::now();
long long int x = fibonacci(45);
... | Basically, for that short piece of code, compile time does not matter.
Even, if you do compile time evaluation.
The main problem is here the utmost bad algorithm used here. Using 2 recursive calls which will then call again 2 recursive functions and so on and so on has really the worst case time complexity for such a s... |
69,328,638 | 69,328,726 | Error "Invalid padding length on received packet" when connecting to winsock server using PuTTY | I'm mostly new to new to networking so I thought I'd start with something simple so I was trying to make a simple C++ echo server. I'm using PuTTY for testing. When I connect to the server through PuTTY I get a PuTTY error of
Invalid padding length received packet
When I check the server console it says that the PuTT... | It looks like you are trying to connect with SSH. Your code is not an SSH server.
To connect to a raw socket server with PuTTY, you need to select the "Raw" connection type.
|
69,329,072 | 69,329,281 | Vector of Pairs of integers | I'm asked to get a value N and I will then get N pairs of values. These pairs will be the size of my 2D array, and this 2D array's elements will range from 1 to the size of the 2D array.
Sample input:
N = 2
Two pairs of values are
(2,3)
(3,4)
Sample output:
{(1,2,3),(4,5,6)}
{(1,2,3,4),(5,6,7,8),(9,10,11,12)}
The... | I did not quite get what the task is, but I fixed few errors in the code, so that it runs and satisfies the sample you've provided.
#include<bits/stdc++.h>
using namespace std;
void makeArray(int a, int b){
//int arr[a][b];
int temp = 0;
cout<<"[";
for(int i=1; i<=a; i++){
cout<<"[";
if (1 <=... |
69,329,900 | 69,330,260 | Data in 2D array is Gone | I'm having a hard time with this 2D array in CPP.
I tried following this link, but it did not solve my problem.
In the saveApToEeprom() function I save two strings.
This works fine. Then i want to read from the EEPROM using getConfigForEeprom(). This is where things go wrong.
The function getConfigForEeprom() prints 2 ... | Solved
I had a fault in my for loop in the function. I was writing the data of the EEPROM index [32-63] also to array index [32-62], but that needed to go array index [0-32]
orginal:
for(uint8_t j = PARAMETER_SIZE_IN_BYTES; j < BYTES_NEEDED_FROM_EEPROM; j ++ ) {
valueEeprom[1][j] = EEPROM.read(j);
S... |
69,329,993 | 69,350,397 | CreateDxgiSurfaceRenderTarget Keep failling | Okay I am creating A d2dwindow that can render another surfaces
so i did that
HR(D3D10CreateDevice
(
NULL,
D3D10_DRIVER_TYPE_HARDWARE,
NULL,
NULL,
D3D10_SDK_VERSION,
&D3dDevicePtr
));
HR(D3dDevicePtr->QueryInterface(__uuidof(IDXGIDevice), (void**)&DXGIDevicePtr));
D3dDevicePtr->Release();
and ... | so i found the problem is the surface and the d2d api was not from the same dxgi so to solve that i followed
https://learn.microsoft.com/en-us/windows/win32/direct2d/devices-and-device-contexts
but there was some diffrances like it use core window not normal one
and it alittle bit messy with api1 or 2 or 3
like ID2D1De... |
69,330,082 | 69,429,495 | How would one generalise `clearerr()` under C++?… | TL;DR
I am aware that if a program listens for EOF (e.g. ^D) as a sign to stop taking input, e.g. by relying on a conditional like while (std::cin) {...}, one needs to call cin.clear() before standard input can be read from again (readers who'd like to know more, see this table).
I recently learned that this is insuffi... | This does what you need:
#include <iostream>
int main()
{
std::cin.sync_with_stdio(true);
char c = '1', d = '1';
std::cout << "Enter a char: \n";
std::cin >> c;
std::cout << (int)c << "\n";
std::cout << std::cin.eof() << "\n";
std::cin.clear();
clearerr(stdin);
std::cout << std::cin... |
69,330,184 | 69,330,282 | How to access values from a pointer-to-array in C++ | I am using the dereference operator but I don't seem to getting values of x.
#include <iostream>
using namespace std;
class Array {
public:
int* get() {
int x[] = { 31, 45, 39, 32, 9, 23, 75, 80, 62, 9 };
int *r;
r = x;
return r;
}
};
int main() {
Array arr;
int *temp = arr.get()... | When a variable, that is allocated on stack, goes out of scope, it gets destroyed.
In your example functionArray::get:
int* get() {
int x[] = { 31, 45, 39, 32, 9, 23, 75, 80, 62, 9 };
int *r;
r = x;
return r;
}
variable x gets destroyed. If you don't want this to happen, you can mark your... |
69,330,253 | 69,339,645 | what are the correct arguments for D2D1Factory::CreateDxgiSurfaceRenderTarget() | i want create direct2D render target that will render on screen with direct3D, so i try to call the D2D1Factory::CreateDxgiSurfaceRenderTarget() funtion to make a direct2D render target, but it keep fails. The error i get from HRESULT is invalid argument-s passed. I tried these 3 codes
FLOAT dpiX;
FLOAT dpiY;
factory->... | After some research and as i haven't access to main application and also wasn't able to attach debugger, i finally found the issue.
According to microsoft, when you call D3D11CreateDeviceAndSwapChain to create the D3D device, the flag D3D11_CREATE_DEVICE_BGRA_SUPPORT required for Direct2D interoperability with Direct3D... |
69,330,295 | 69,330,753 | Why does VSCode C++ yield 'explicit type is missing' warning for templates | I have the following code
using namespace std;
template <class T>
vector<T> func(){
return vector<T>(100,0);
}
int main(){
auto test = func<int>();
cout << test[0] << " " << test.size() << endl;
return 0;
}
It compiles without warning and runs correctly, but VSCode intelisense highlights test with th... | The language version needed to be configured correctly. To resolve this I followed the configuration steps here:
https://code.visualstudio.com/docs/cpp/config-mingw#_cc-configurations
I ended up with the following global settings.json
{
"C_Cpp.default.cppStandard": "c++17",
"C_Cpp.default.intelliSenseMode": "wi... |
69,330,416 | 69,330,748 | How to print substring contained between braces? | I'm writing a function, which is supposed to output whatever is between curly braces in string
(e.g. hello world for text{hello world}).
But it isn't outputting anything when I try running it. Do you have any idea what could be wrong?
#include <iostream>
#include <string>
using namespace std;
int main(){
start: ... | As I understand, you want a function that is parsing a string and printing whatever is within a construction like 'text{...}'
Here is a few issues in your code:
std::cin >> funct will only read a word (whitespace separated text). If you want to get an entire line, use std::getline(std::cin, yourString)
You look for a... |
69,330,428 | 69,330,979 | Is there a binary search algorithm that takes a unary predicate rather than a search value? | I have this exercise:
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, input [3, 4, -1, 1] should give 2 a... | Yes, std::partition_point does exactly what you want.
|
69,330,986 | 69,331,116 | How to monitor clipboard changes in X11 Windows? | I am pretty much exhausted all the possibilities of finding an X11 API to perform the following thing.
I have a thread which is trying to monitor for an event or notification to know when anything is copied into clipboard by any X11 client. I do not want to monitor a specific Atom Target (clipboard format), but general... | To monitor changes, use XFixes. With XCB it is used like:
// Enable XFixes
auto xfixes = xcb_get_extension_data(connection, &xcb_xfixes_id); // do not free!
ev_selection_change_notify = xfixes->first_event + XCB_XFIXES_SELECTION_NOTIFY;
auto *version = xcb_xfixes_query_version_reply(xcb_xfixes_query_version(connection,... |
69,331,785 | 69,331,803 | New type of auto-generated constructor in C++20 | The code below doesn't compile on GCC 11 with -std=c++17, but does with -std=c++20:
#include <iostream>
#include <string>
struct Foo {
std::string s;
int i;
};
int main()
{
Foo foo("hello", 42);
std::cout << foo.s << ' ' << foo.i << '\n';
}
What's the feature in C++20 that enables this? What kind of ... | The C++20 feature being used here is the initialization of aggregates from parenthesis (P0960R3):
This paper proposes allowing initializing aggregates from a parenthesized list of values; that is, Aggr(val1, val2) would mean the same thing as Aggr{val1, val2}, except that narrowing conversions are allowed.
Here is an... |
69,331,986 | 69,332,146 | How to push back a vector into a map<int, vector<int>> | What I want to do here is to create a map like this:
0 -> 0,1,...,4;
1-> 0,1,...,4;
...
9 -> 0,1,...,4;
int main(){
map<int, vector<int>> m;
for(int i=0; i<10; i++){
vector<int> temp;
for(int j=0; j<5; i++){
temp.push_back(j);
}
m.insert({i, m.push_back(temp)});
... | std::map does not have a push_back() method. You need to insert the vector itself that you prepared, eg:
int main(){
map<int, vector<int>> m;
for(int i=0; i<10; i++){
vector<int> temp;
for(int j=0; j<5; j++){
temp.push_back(j);
}
m.insert({i, temp});
}
}
Alterna... |
69,332,236 | 69,336,498 | How does c++17 std::variant determine which type to use? | I am curious how std::variant works.
From what i understand it is "basically" a union with an additional index variable.
I am, however, confused how does it determine which type to forward the construction/assignment to efficiently. I have looked at it via godbolt.org and it does seem to be pretty efficient, even when ... |
Another way would be to have a union with fixed types and whenever it would need to use a constructor/destructor etc. a big switch would decide which union member to use depending on the index variable, but that would require a lot of code bloat and would only work for fixed types.
But this (morally) works fine for a... |
69,332,621 | 69,332,720 | How to make a function that accepts code blocks | What I am seeking is a way to create a function that accepts a block of code as argument.
I've seen this in boost's for-each loop
But I can't find a way to do it myself
I've searched but didn't find anything(probably my terminology was wrong)
An example of what I want:
int main() {
DO_SOMETHING_FUNC(arg1, arg2, arg... | This specific syntax can only be achieved with a macro.
If possible, you should prefer a macro-less approach, i.e. passing a lambda to the function:
do_something_func(foo, bar, [&]
{
});
The last parameter of my_for_each either needs to have a templated type:
template <typename F> void my_for_each(/*blah, blah, */ F ... |
69,332,664 | 69,386,313 | Qt Insert two different QGraphicsWidgets in the same QGraphicsScene, setZValue is invalid | Calling collidingItems when two QGraphicsWidgets are visible overlapping, but returns null
QGraphicsWidget0, QGraphicsWidget1 inherit from QGraphicsWidget.
Eventually I see that icon1 is shown on top, how can I get icon1 to show on the bottom without changing the insertion order?
icon0= new QGraphicsWidget0();
icon1= n... | Thanks for the replies guys, I have solved the problem, I had set QGraphicsItem::ItemStacksBehindParent on some icons causing the other icons to look like setZValue() was not working.
|
69,332,862 | 69,332,927 | Unhandled exception : An invalid parameter was passed to a function that considers invalid parameters fatal. in insertion sort | I am working on an insertion sort with vector in C++.However, I got an problem when I want to print the vector for the first 10 element.
void insertion_sort(vector<int> &data, int n)
{
int temp;
int i;
int j;
for (i = 1; i < n; i++)
{
temp = data[i];
j = i - 1;
while (j >= 0... | I fixed the problem with size < 10 (correct count being displayed and crash), language of message, printing out the values (main issue), use new line instead of ", " after last value, and also reduced scope of variables, return from main:
#include <iostream>
#include <vector>
using namespace std;
void insertion_sort(v... |
69,333,165 | 69,333,677 | Mutual referencing among objects in C++ | I want to create two objects with mutual member-references between them. Later it can be extended to e.g. closed loop of N referencing objects, where N is known in compile time.
The initial attempt was with the simplest struct A lacking any constructors, which make it an aggregate (v simulates some payload):
struct A {... | B z{ z.a2, z.a1 }; attempts to copy-construct a1 and a2, rather than aggregate-initialize them with z.a2, z.a1 as first fields.1
B z{{z.a2, 0}, {z.a1, 0}}; works in GCC and Clang. MSVC gives error C2078: too many initializers, which looks like a bug.
1 Here, direct-list-initialization is performed for z, which in this... |
69,333,549 | 69,334,015 | C++: Allocating memory within multiple threads | this is more a general question rather than a specific coding problem. Does (and if yes, how) C++ avoid that multiple threads try to allocate the same memory adresses?
For example:
#include <vector>
#include <thread>
int main() {
std::vector<int> x, y;
std::thread do_work([&x] () {
/* push_back a lot of ints to x... | Allocation memory (via malloc/new/HeapAlloc and such) are thread-safe by default as long as you've compiled you application against thread safe runtimes (which you will, unless you explicitly change that).
Each vector will get its own slice of memory whenever they resize, but once a slice is freed any (other) thread co... |
69,333,608 | 69,335,044 | How to make threads with std::execution::par_unseq thread-safe? | I am reading C++ concurrency in action.
It says that when you use std::execution::par, you can use mutex per internal element like below.
#include <mutex>
#include <vector>
class X {
mutable std::mutex m;
int data;
public:
X() : data(0) {}
int get_value() const {
std::lock_guard guard(m);
return data... | It is only thread-safe because you do not access shared data in the parallel algorithm.
The only thing being executed in parallel are the calls to y.increment(). These can happen in any order, on any thread and be arbitrarily interleaved with each other, even within a single thread. But y.increment() only accesses priv... |
69,333,609 | 69,333,884 | Explaining C++ (C Binding Library) Function | I'm trying to understand a Function/Method in a Library in order to port it to Java however some parameters don't make any sense to me and reading the source code the library is based on is not helping.
Function (Note the API has few comments (We can also ignore the calc handle since it's got a supplier method))
Ssr ca... |
NoteInfo * rows here is pass by pointer. So, rows actually is a pointer to an instance of type NoteInfo. This is one of the ways to pass arrays in c++ to a function. Since arrays are contiguous in memory so we can just increment the pointer by one and get the next element of the array.
for example look at these thre... |
69,333,790 | 69,333,816 | Is C++ compiler obligated to generate 'ret' instruction for a function without 'return' statement? | Recently I encountered a problem that a thread in my programe was somehow stopped (GDB indicates thread's state as STOPPED). I have spent a couple of days debugging. This problem happended after I changed the version of the compiler some days ago. Finally I found out that the problem happens because a function is defin... | No.
For any non-void function except main, if there is any path through the function that does not return, your program exhibits undefined behaviour if that path is taken at runtime. Then the compiler is allowed to do whatever it feels like. Generally this results in just a missing ret statement but I have seen much we... |
69,333,792 | 69,333,839 | How to create objects based on user input? | I want to make a program which creates an object each time user enters an employee name. The object should be named according to the name of the employee.
#include <iostream>
using namespace std;
class employee
{
public:
int salary;
int ma = 300;
float da = 1.25;
float hra = 0.15;
};... | Give the employee class a name field, and a constructor to initialize it
#include <iostream>
#include <string>
using namespace std;
class employee
{
public:
string name;
int salary = 0;
int ma = 300;
float da = 1.25;
float hra = 0.15;
employee(string name) : name(name) {}
};
int main()
{
... |
69,333,936 | 69,334,256 | std::vector::emplace_back with a POD C++ | I have a fairly bog standard Vector4 struct (the math kind not the C++ kind) which is a POD and is templated:
template<typename T>
struct Vector4 {
T x, y, z, w;
Vector4 operator+(const Vector4& other) const { return Vector4{ x + other.x, y + other.y, z + other.z, w + other.w }; }
Vector4 operator-(const ... | emplace_back uses parentheses to initialize the value, which means a constructor is required to use it until C++20. C++20 introduced parenthesized initialization of aggregates, so you code becomes valid as is.
Until then you can just do
vec.push_back({1.0f, 2.0f, 3.0f, 4.0f});
|
69,333,938 | 69,334,218 | Store multiple std arrays of variable size | I have different std::arrays with variable sizes, e.g.
std::array<int, 5> array_one;
std::array<int, 8> array_two;
std::array<int, 2> array_three;
The primary type is always the same (int in this example).
Now I have to iterate over all those arrays and in order to do that with as little code as possible, I thought I ... | In case you just need to iterate, not to store arrays together, use std::span
std::span<int> span[] = {array_one, array_two, array_three};
You may also flatten the views with std::views::join
for(int &i : span | std::views::join)
{
...
}
If arrays are constant, then
std::span<int const> span[] = {array_one, array... |
69,334,823 | 69,334,895 | Why access deleted pointer won't crash the program? | #include <iostream>
#include<list>
using namespace std;
template <class T>
class Ptr {
public:
Ptr() {
a = nullptr;
l.push_back(0);
}
std::list<int> l;
void print_this() {
cout<<this<<endl;
}
protected:
int *a;
};
int main()
{
Ptr<int> *ptr = new Ptr<int>();
delete ptr;
/... | When you have a pointer to a class, and call a non-virtual function on it, whatever the address is at the pointer will be considered the this pointer. Even if it is zero. As long as you don't try to access members at that address, you should have no problem printing the this poniter.
struct A {
void printThis() {
... |
69,334,861 | 69,335,095 | Should class be not trivially destructible, if standard specifies that it has a destructor? | Consider std::latch [thread.latch.class]:
namespace std {
class latch {
public:
static constexpr ptrdiff_t max() noexcept;
constexpr explicit latch(ptrdiff_t expected);
~latch();
latch(const latch&) = delete;
latch& operator=(const latch&) = delete;
void count_down(ptrdiff_t update = 1);
... | This is implementation freedom. The C++ standard defines the class, the implementation of the class is up, well, to the implementation.
There are some classes where the standard explicitly mandates a trivial destructor. For example, if an existing class is trivially destructible then its std::optional also must be triv... |
69,335,019 | 69,347,055 | Is there an alternative on nested loop for displaying possible combination in range of n? | I created some code where, whenever you put number in pinCombo(x) (for example pinCombo(3)), the output will be:
000
001
002
… until it reaches 999.
So, pinCombo(4) output will be:
0000
0001
....
....
9999
Here's my code:
#include <iostream>
using namespace std;
void pinCombo(int x)
{
int a,b,c,d,e,f,g,h,i,j;
... | Here's a solution using setwidth and setfill.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
void pinCombo(int x){
for (int i = 0; i < pow(10, x); i++){
cout << setw(x) << setfill('0') << i << endl;
}
}
int main(){
pinCombo(3);
return 0;
}
|
69,335,200 | 69,335,302 | Variadic template function | I was trying to code a function that takes unbounded number of arguments in C++. To do so, I had to try it in the function below.
With two arguments :
unsigned int bitClear(uint32_t &bitNum, unsigned int pos)
{
bitNum = bitNum & (~(1 << pos));
return bitNum;
}
But with unbounded number of arguments, ... | Something along these lines, perhaps:
template <typename Val, typename ... Pos>
Val& bitClear(Val& v, Pos... pos) {
((v &= ~(1 << pos)), ...);
return v;
}
Demo
|
69,335,493 | 69,335,619 | What is the difference between returning auto&& and decltype(auto)? | I am trying to make template wrapper function, that should forward parameters and return value. And I can't decide what is better to use auto&& or decltype(auto) for return type. I've read Scott Meyers article and understood that it is necessary to return decltype(auto) compared to auto not to strip ref_qualifiers.
As ... |
What is the difference between decltype(auto) and auto&&?
decltype(auto) covers three cases. When returning lvalues, the return type would be T& (lvalue-reference); for xvalues, the return type would be T&& (rvalue-reference); for prvalues, the return type would be T (non-reference, i.e. return by-value).
auto&& cove... |
69,335,535 | 69,412,274 | Using a basic function of CGAL, e.g. `square` | I am starting to work my way through CGAL and have a question about the Algebraic foundations package.
How do you use the square function defined here?
I tried the following
// tmp.cpp
#include <CGAL/number_utils.h>
int main() {
double dist = 0.002;
auto sq_dist = CGAL::square(dist);
return 0;
}
The compiler th... | The issue arises because of the -s tmp argument.
The solution is to call it in either of the following formats
cgal_create_CMakeLists tmp
cgal_create_CMakeLists
The documentation gives an explanation
$ cgal_create_CMakeLists -h
Usage: cgal_create_CMakeLists [-s source] ...
...
-s source If this parameter is given t... |
69,335,705 | 69,335,755 | Increment default constructed int in the unordered map | I have unordered map of counters, e.g:
std::unordered_map<std::string, std::size_t> counters_;
Do i need to manually create a value before trying to increment it? Will the next line be considered undefined behavior?
std::unordered_map<std::string, std::size_t> counters_;
counters_["non_existing_key"] += 1;
| By using the std::map::operator[], you're creating a new value in the map if it didn't exist before.
Furthermore, the value new will be value-initialized, so incrementing the value is well-defined.
|
69,336,152 | 69,349,134 | install pytorch c++ api CUDA11.4 for ubuntu | I'm trying to use the PyTorch c++ API on an ubuntu 18.04. I've installed CUDA 11.4 and cuDNN 8.2.4.15. The source I'm compiling is available here. compiling CUDA with nvcc works and the cuDNN installation test succeeds. But I am unable to find a good documentation for installing and compiling projects with PyTorch c++ ... | I used the next ones to install on Ubuntu 16, it can be helpful for you.
PyTorch C++ API Ubuntu Installation Guide
tutorial to compile and use pytorch on ubuntu 16.04
Also can it will be util to refer the official documentation to use PyTorch c++ for Linux systems and the GCPdocumentation.
|
69,336,301 | 69,336,345 | Use C++20 Concept to constrain template parameter | I want to use concepts to replace a design which currently uses SFINAE (enable_if). To simplify, I have created a simpler example which shows an identical problem:
template<typename T>
concept smallerThanPointer = sizeof(T) < sizeof(void*);
template<typename T>
concept notSmallerThanPointer = !smallerThanPointer<T>;
... | The correct syntax for the partial template specialization for constraints should be:
template<typename T>
concept smallerThanPointer = sizeof(T) < sizeof(void*);
template<class T>
class MyClass
{
public:
MyClass() { std::cout << "MyClass[...]\n"; }
};
template<class T> requires smallerThanPointer<T>
clas... |
69,336,491 | 69,354,434 | C++ Linking SQLite to Visual Studio 2019 project | I am trying to use SQLite with Visual Studio 2019.
I downloaded "amalgamation" package and included"sqlite3.h" and "sqlite3.c" files to the project but I get errors(link to pastebin below)
#include "sqlite3.h"
#include "sqlite3.c"
https://pastebin.com/6T5HMnyh
What am I doing wrong?
| I had hit this same thing today. As S.M. stated, you don't want to include the .c file anywhere in this process. You should include the sqlite3.h file and follow these instructions.
I found that I not only had to download the amalgmation files but also the dll files (for either x64 or x86 depending on your flavor).
I... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.