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 |
|---|---|---|---|---|
70,433,788 | 70,434,677 | Proper C++ type for nested list of arbitrary and variable depth? | I'm trying to port some code from Python to C++. The Python code has a function foo that can take nested lists of ints, with variable list depth. For example, these are legitimate function calls to foo:
foo([ [], [[]], [ [], [[]] ] ])
foo([1])
foo([ [1], [2, 3, [4, 5]], [ [6], [7, [8, 9], 10] ] ])
What should the meth... | Here's a way that's pretty simple to define and use:
#include <variant>
#include <vector>
struct VariableDepthList : std::variant<std::vector<VariableDepthList>, int> {
private:
using base = std::variant<std::vector<VariableDepthList>, int>;
public:
using base::base;
VariableDepthList(std::initializer_list... |
70,435,254 | 70,435,410 | How to use dollar / euro sign in code to initialize a variable? | I want to write some code that uses different types of currencies, eg
struct euro {
int value;
};
struct dollar {
int value;
};
Now I'd like to use the euro and dollars sign in code, something like
euro e = 3€;
dollar d = 3$;
Is this possible somehow?
| What you need is user defined lietrals. The code below worked for me using g++ 11.1.0 but I guess that there could be some problems with non ASCII €. Maybe try using EUR suffix? For negative values see this.
#include <charconv>
#include <cstring>
#include <iostream>
struct euro
{
unsigned long long val;
};
eu... |
70,435,306 | 70,435,367 | C++ Perfect Forwarding function | I've read about perfect forwarding, but still I've got questions)
Consider this code
template<typename Input , typename Output>
struct Processor
{
Output process(Input&& input)
{
startTimer(); // Starting timer
auto data = onProcess(std::forward<Input>(input)); // Some heavy work here
... | Perfect forwarding is possible when you have a forwarding reference.
Example:
template<class I, std::enable_if_t<std::is_convertible_v<I, Input>, int> = 0>
Output process(I&& input)
{
startTimer(); // Starting timer
auto data = onProcess(std::forward<I>(input));
stopTimer(); // Stopping timer
logTimer()... |
70,436,520 | 70,436,788 | What is the advantage of constexpr virtual functions in C++20? | I can easily say that by declaring a function as constexpr, we evaluate it during the compile-time and this saves time during run-time as the result was already produced.
On the other hand, virtual functions need to be resolved during run-time. Hence, I guess we cannot get rid of the resolution process. Only the result... | Well the obvious benefit is that you can even do virtual function calls at compile time now.
struct Base {
constexpr virtual int get() { return 1; }
virtual ~Base() = default;
};
struct Child : Base {
constexpr int get() override { return 2; }
};
constexpr int foo(bool b) {
Base* ptr = b ? new Base() ... |
70,436,549 | 70,466,900 | Detect if file is open locally or over share | I'm trying to check if a file is open in Win32:
bool CheckFileUnlocked(const TCHAR *file)
{
HANDLE fh = ::CreateFile(file, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
if(fh != NULL && fh != INVALID_HANDLE_VALUE) {
return (CloseHandle(fh) == TRUE);
}
return false;
}
I need to be able to dist... | You can try GetFileInformationByHandleEx:
FileRemoteProtocolInfo should return properties of network access, and probably should fail on local files
FileStorageInfo should return properties of the storage, it might fail on network (but need to verify that)
|
70,437,299 | 70,473,250 | OpenCv Troubleshooting (-4:Insufficient memory) Failed to allocate | QCoreApplication a(argc, argv);
cv::Mat src=imread("/home/cdukunlu/Downloads/EuFFJ.jpg");
float data[9]= {161.837869,0.059269,319.778713,0.000000,165.648492,230.424626,0.000000,0.000000,1.000000};
float rectification[9]={1.000000,0.000000,0.000000,0.000000,1.000000,0.000000,0.000000,0.000000,1.000000};
cv::Vec<float,... | I had solved the problem with checking the opencv libraries.
Since ı had two different libraries installed to my ubuntu; the precompiled version of OpenCV version is 3.x but my code is tested on different version of opencv which it is OpenCV 4.5.2
As soon as ı had changed the version from 3.x to 4.5.2 the problem has g... |
70,437,364 | 70,437,719 | What memory/data structure should I use to divide the memory into blocks/chunks and its implementation? | (THE ALLOCATED DATA CAN BE OF ANY TYPE - int, char, etc..)
I am given a sheet size of 1024 bytes and a maximum of 5 sheets. I need to make some sort of dynamically allocated structure (or structures) that will keep all of the data in one place and divide it into blocks. So I basically need to allocate 1024 bytes (or ma... | I would start out with something like this :
#include <array>
#include <memory>
#include <iostream>
template<std::size_t N>
struct heap_t
{
public:
// todo add your memory managment
// using templates like
template<typename type_t>
type_t* allocate()
{
// use sizeof(type_t) etc...
... |
70,437,618 | 70,437,721 | Why does glTranslatef() resize object? | I have 3 rectangles and I need to place them in shape of podium. At this moment they look like this:
Code of display func:
glPushMatrix();
glRotated(rotate_x, 1.0, 0.0, 0.0);
glRotated(rotate_y, 0.0, 1.0, 0.0);
glScalef(1, 3, 1);
glColor3fv(gold);
glutSolidCube(2);
glPopMatrix();
... | You moved it farther away. Objects which are farther away appear smaller; that's just how perspective works. And since you have no lighting, background objects, or any other depth cues, being farther away is visibly identical to scaling it to a smaller size.
|
70,437,623 | 70,438,168 | Returning Eigen matrices and temporaries | Consider the following function Foo:
// ...
Eigen::Vector3d Foo() {
Eigen::Vector3d res;
// ...
return res;
}
int main () {
Eigen::VectorXd foo = Foo(); // (1)
return 0;
}
The line (1) should not create any temporaries due to return value optimization. But consider the following case:
// ...
... |
The line (1) should not create any temporaries due to return value optimization.
No, it must materialize a temporary for the return value of Foo.
The return type of Foo and the type of the variable foo do not match (up to cv-qualification): Vector3d vs VectorXd.
But this is a necessary condition for copy elision to b... |
70,437,772 | 70,437,958 | Base class is an ambiguous base of derived class | I am having trouble understanting how to differentiate between multiple instances of the base class in a multiple inheritance situation. When looking for solutions, i only found answers about virtual inheritance but that does not solve my problem at all, since i do not want to have a single instance of the base in the ... | You can use an intermediate conversion of the pointer type to control which instance of the repeated base class you get
Arr[i] = upcast<Car*>(new Trailer_Car);
or
Arr[i] = upcast<Trailer*>(new Trailer_Car);
I recommend to avoid a "real cast" for something that should be an implicit conversion. It won't force the com... |
70,438,520 | 70,438,773 | Is pointer-difference a valid way to find the index of an element in a vector within a range-based for loop? | Is it valid to use pointer-difference to find the index of an element within a range-based for loop?
A number of questions have been asked here concerning using indices and range-based loops together, but they almost all say to not use range-based loops if you also need the index of an element. But it seems like, at le... | If the underlying iterator meets the requirements of the LegacyContiguousIterator (C++17), then yes. This requirement indicates that *(itr + n) is equivalent to *(addressof(*itr)+n).
This is from https://en.cppreference.com/w/cpp/named_req/ContiguousIterator
C++20 replaced it with the contiguous_iterator concept.
The ... |
70,438,781 | 70,438,935 | How can i make space after punctations in C | My Homework is
Some certain punctuations, period (.), comma (,), colon (:), semi-colon (;), question mark
(?), and exclamation mark(!), should be followed by a space. For example, the following
strings should be corrected because there is no space after the above punctuations.
(There might be some other punctuations wh... | Operator + does not work on operands of type char[]. You should just copy the characters to string1:
for(int i = 0, i1 = 0, string_length = strlen(string); i < string_length; i++)
{
string1[i1++] = string[i];
if (string[i] is one of the punctuation characters)
string1[i1++] = ' ';
}
I moved strlen cal... |
70,438,867 | 70,441,466 | Segmentation fault(code dumped) in c++ after several try I cann't get the solution | #include <iostream>
using namespace std;
int main() {
int T,D;
long long int N;
long long int a[N];
long long int b[D];
cin>>T;
for(int i=0;i<T;i++)
{
cin>>N>>D;
for(int i=0;i<N;i++)
{
cin>>a[i];
}
for(int i=0;i<D;i++)
{
... | There are several things that are wrong.
C-style arrays must be set at compile time. So if you want to use int a[N], N must to known at compile time. If you want a flexible array, one C++ way is to use std::vector.
Then the array a goes from 0 to N-1. So going a[N] is going too far. So a[i+N] is way out if bounds and w... |
70,439,229 | 70,439,266 | How to use a makefile across multiple folders in C++ | I have a fairly large program, so I am using a makefile to compile the program. However, I would like to separate parts of the program into different folders instead of having the whole program in one folder.
Root folder with makefile and other folders
Folder inside of root folder with files
Basically I have one p... | You could could make the root makefile call the makefiles inside the folders.
Example:
# The list of your directories under the root directory:
SUBDIRS := foo bar baz
.PHONY: build all test subdirs $(SUBDIRS)
.SUFFIXES:
all: subdirs
subdirs: $(SUBDIRS)
# for each sub directory, do "make -C the_directory"
$(SUBDIRS... |
70,439,358 | 70,442,710 | Compatibility layer in C++ to access template functions from C | I have some code implemented in template variadic functions that uses modern c++17 features. Being templates, they are implemented in the .h files.
// .H FILE
template <typename... T>
inline constexpr void foo(const T& ...values){
// Do stuff
}
Is there a way to create a compatibility layer that would allow users ... | The way I actually solved may not be valid to all particular cases!!
I found that trying to pass arguments directly to a c++ variadic function was not possible (to the best of my knowledge). Instead, a void vector would be passed, and the results will not be the ones expected. In this case, stringifying the c input, an... |
70,439,547 | 70,440,331 | Add shell script as executable to catkin package to use with rosrun | When using a catkin package it is possible to start the c++ executables, that were added in the CMakeLists.txt, using the command rosrun <package_name> <executable_name> from anywhere on the computer.
Is there a way to add a shell script as an executable to the catkin package so that it can be called using rosrun <pack... | Yes it is. You can do this by performing the following steps:
You need to place your script in the scripts folder of your package. Also the script needs to be marked as executable (chmod +x your_script.sh).
After sourcing your workspace, you can run and launch the script with ROS tools like
rosrun your_package your_scr... |
70,439,557 | 70,439,989 | What is the correct usage/syntax for the c++17 alignas() specifier for dynamically allocated arrays of fundamental types? | This must be a repeat question, but I have not found it after searching for 2 days ...
I'm using MSVC with /std:c17 /std:c++17 and trying to get alignas(64) to work with arrays of doubles. The syntax in the code below is the only one I have found that compiles, but it's not aligning ... typically, the array is unaligne... | While C++17 does have the means for operator new to be given an alignment for the memory it allocates, there is no mechanism in C++ to specify the alignment for memory allocated by a new expression outside of the alignment of the type being allocated. That is, if you perform a new T or new T[], the alignment of the all... |
70,440,025 | 70,444,228 | Using C++ Libraries on Linux | I'm trying to follow along here to use a speech recognition model. The model is in C++, and almost all of my experience is in Python.
I installed a virtual machine running Ubuntu, and still the installation procedure was failing for me. I decided to simply try to compile the model so that I could call it in a Python sc... | You've installed only the runtime libraries. You also have to install the development version (e.g. header files), most likely called something like cereal-devel or so.
Alan Birtles provided a link to the development packages in the comments section above.
https://packages.ubuntu.com/focal/libcereal-dev
|
70,440,451 | 70,440,681 | Is there a way to have a version of std::atomic's compare_exchange_strong method that exchanges on inequality? | I have an atomic type where I need to atomically compare it with a value, and if the two values are not equal then exchange the value of the atomic.
Put another way, where compare_exchange_strong essentially does this operation atomically:
if (atomic_value == expected)
atomic_value = desired;
...I'm looking for a ... | auto observed = atomic_value.load();
for (;;)
{
if (observed == expected){
break; // no exchange
}
if (atomic_value.compare_exchange_weak(observed, desired)) {
break; // successfully exchanged observed with desired
}
}
Sure it is suboptimal on architectures where HW has LL/SC, as C++ do... |
70,440,777 | 70,441,000 | int strlen has zero stored in it c++ | i tried strlen for char to get howmany characters in cstring to join a loop which looks for charcaters in the code but strlen just returned 0
the email[] i made that empty to get any value in it
using namespace std;
#include <iostream>
#include <cstring>
int main(int argc, char **argv)
{
char email[] = "";
cout << "... |
char email[] = "";
This is an empty string. The length of the string is 0, and the size of the array is 1. The only element is the null terminator.
but strlen just returned 0
This is hardly surprising given that the only string that can fit in the array is a string of length 0.
cin >> email;
Prior to C++ 20, th... |
70,440,813 | 70,441,361 | Correct usage of std::atomic<std::shared_ptr<T>> with non-trivial object? | I'm trying to implement a lock-free wrapper via std::atomic<std::shared_ptr>> to operate over non-trivial objects like containers.
I found some relevant pieces of information in these two topics:
memory fence
atomic usage
But it still isn't what I need.
Give an example:
TEST_METHOD(FechAdd)
{
constexpr si... | First, a sidenote. std::atomic<std::shared_ptr<T>> gives atomic access to the pointer, and provides no synchronization whatsoever for the T. That's super important to note here. And your code shows that you're trying to synchronize the T, not the pointer, so the atomic is not doing what you think it is. In order to u... |
70,441,031 | 70,445,068 | Cant figure out the testcase where I am getting segmentation fault? | I am getting segmentation fault for some unknown test case and I am unable to resolve it.
It runs for most of the cases. I only want to know in which case I am getting segmentation fault.
The code is written for the Question Maximim Rectangular Area in a Histogram. You can check this question here: https://practice.gee... | The problem got solved by using vector instead of array. I was just using bad c++ syntax for array and hence using vector just solved it.
|
70,441,231 | 70,504,348 | Qt C++ QNetworkRequest not making any requests | I'm trying to fetch some data from an API using QNetworkRequest following this video (https://youtu.be/G06jT3X3H9E)
I have a RoR server running on localhost:3000 and I'm trying to fetch something from it.
.h file:
#ifndef WORKER_H
#define WORKER_H
#include <QObject>
#include <QDebug>
#include <QNetworkAccessManager>
#... | Remember the concepts of scope, life cycle, and local variables? In your case worker is a local variable that will be destroyed instantly so the slot is not invoked, use
Worker * worker = new Worker;
worker->get("abc"); //remember to delete the memory when you no longer use it
|
70,441,410 | 70,441,535 | How can I pass and store an array of variable size containing pointers to objects? | For my project I need to store pointers to objects of type ComplicatedClass in an array. This array is stored in a class Storage along with other information I have omitted here.
Here's what I would like to do (which obviously doesn't work, but hopefully explains what I'm trying to achieve):
class ComplicatedClass
{
... |
How can I pass and store an array of variable size containing pointers to objects?
By creating the objects dynamically. Most convenient solution is to use std::vector.
size_t size;
std::array<ComplicatedClass *, size> objectArray;
This cannot work. Template arguments must be compile time constant. Non-static membe... |
70,442,108 | 70,442,301 | C++ STD Unordered Set/Map vs Boost Unordered Set/Map | What are the differences between them, and when should you use each?
I have tried a few tests on an old laptop and there seems to be no significant performance difference for storing basic types like ints and longs. I think one of the main difference is boost container emplace methods dont support std::piecewise_constr... | The Boost ones have some features that do not exist in the standard library. Off the top of my head:
Boost Hash, which is more flexible and easier to customize than specializing std::hash<> (though specializing boost::hash<> is also supported; the easier route is to implement a inline friend size_t hash_value(T const&... |
70,442,139 | 70,442,389 | Vectors do not satisfy std::ranges::contiguous_range in Eigen 3.4 | Why does Eigen::VectorXd not satisfy the concept std::ranges::contiguous_range? That is, static_assert(std::ranges::contiguous_range<Eigen::VectorXd>);
does not compile.
Also, is there the possibility to specialize a template to make Eigen vectors satisfy the contiguous range concept? For instance, we can specialize st... | Contiguous ranges have to be opted into. There is no way to determine just by looking at an iterator whether or not it is contiguous or just random access. Consider the difference between deque<int>::iterator and vector<int>::iterator - they provide all the same operations that return all the same things, how would you... |
70,442,144 | 70,442,269 | How to make compiler choose a non-member function overload | I am writing a library that performs some operations on built-in types (int, float, double, etc.) and user-provided types. One of those is performed by a template function:
namespace lib
{
template<typename T>
inline auto from_string(std::string const & s, T & t) -> bool
{
std::istringstream iss(s);
iss >> t;
... | Scope based lookup starting from the body of TestHandlerT<T>::from_string hits the member function before it hits lib::from_string. So just reintroduce lib::from_string into the scope of the body with using. This also reenables ADL, as ADL is suppressed when scope based lookup hits a class member.
template<typename T>
... |
70,442,352 | 70,444,438 | Executable Segfaults and GDB gives "not in executable format: File truncated" | I was working on an application, made some changes and now it won't even run anymore. I've reverted the changes, rebuilt the entire application, and still no luck. I don't understand how this error could arise? I erased the .o files and did a brand new build and it's still not working. I didn't change the build setting... | Update:
Previous suspects have been eliminated: filesystems have enough space and md5sum matches between the build and target hosts.
This leaves only one likely possibility: the build toolchain has been corrupted in some way, and produces broken binary.
In particular, I missed this part of the output:
z: ERROR: ELF 32... |
70,442,495 | 70,443,567 | Performance of smart pointer and raw pointer in containers | I'm curious about the answer to this question as I mostly work with containers.
which one is more logical to use in minimum of 100 (and maximum of 10k) elements in vector or map container in?
std:::vector<std::unique_ptr<(struct or class name)>>
std:::vector<std::shared_ptr<(struct or class name)>>
std:::vector<(struc... | This is really opinion-based, but I'll describe the rules of thumb I use.
std:::vector<(struct or class name)> is my default unless I have specific requirements that are not met by that option. More specifically, it is my go-to option UNLESS at least one of the following conditions are true;
struct or class name is... |
70,442,579 | 70,442,967 | does c++ singleton create new instance every time? | C++ singleton code looks like this:
MyClass& MyClass::getInstance(){
static MyClass instance;
return instance;
}
Looking specifically at static MyClass instance;
Is a new instance created each time getInstance is called?
EDIT
I understand that static members are one-per-class. But doesn’t static MyClass instan... | Because the MyClass member variable is declared as static and you are returning a reference to it, not a copy. Static member variables are not created per-object like normal member variables; rather, there is one instance of the variable accessible from all objects of the class.
See here.
|
70,442,652 | 70,442,692 | Maximum Subarray question around abandoning the running sum approach | Looking at Leetcode #53 (Maximum Subarray, https://leetcode.com/problems/maximum-subarray/), I saw this solution in the comments and adapted my code to it. There is one part I don't understand though — can someone explain?
I am looking to solve it with the sliding window approach.
class Solution {
public:
int maxSu... | The code is poorly written, in a way which obscures its operation. In the if-condition you’re asking about, the only way it could be true is if the sum were negative before the beginning of the loop iteration. That’s what it’s really restarting in response to: an overall unhelpful prefix.
|
70,442,963 | 70,443,277 | Does notifying a condition variable guarantee the wake-up of a thread with a successful condition/predicate if one exists? | The information I've found on cppreference is vague in this regard, so I'm asking here. Say I have two threads waiting on a condition with one having a true predicate, and the other a false one (e.g. condition.wait(lock, [=]{ return some_condition; }). The main thread decides to randomly notify one of them with cond.no... |
A notify_all() won't work, because we may accidentally end waking up
multiple threads that satisfy the condition, meanwhile we only want a
single one to go through at most.
That is not entirely accurate. Only one thread can lock a given mutex at a time, no matter what. If all execution threads who are waiting on the ... |
70,443,054 | 70,443,152 | Assigning a non optional variable to std::optional variable | I have a class with an optional field declared of void const * (I'm also confused if to * outside the angle brackets or inside.
class Test {
protected:
std::optional<void const> *_data; // void const *_data
public:
explict Test(void const *data = nullptr);
}
In the Test.cpp file.
Test(const void *data) {
... | In your example, where _data is a non-const pointer to a std::optional (it doesn't matter that the std::optional holds a const void type), you're trying to assign a pointer to a const object (of unknown void type) to a non-const pointer.
This violates the contract of your class constructor, where you promise not to mod... |
70,443,126 | 73,947,123 | Loading and Eigen Matrix from yaml using yaml-cpp | I'm using the very nice yaml-cpp project to read configurations into a C++ program. One of the config items stores an Eigen::Matrix<..> The following code works well but wondering if there is a better way?
main.cpp:
YAML::Node config = YAML::LoadFile("default.config");
const vector<double> eigenVec = config["my_matr... | maybe you can compressed into one line of the code
Eigen::Matrix4d Matrix4x4= Eigen::Map<Eigen::Matrix<double, 4, 4, Eigen::RowMajor>>(config_node_["my_matrix"].as<std::vector<double>>().data());
|
70,443,780 | 70,443,809 | Why noexcept is used twice for global swap function | I'm trying to understand noexcept. I came to know global swap function is generally specified like this
void swap (T& x, T& y) noexcept(noexcept(x.swap(y)))
{
x.swap(y);
}
I want to understand why noexcept specification is noexcept(noexcept(x.swap(y))) but not noexcept(x.swap(y)).
| These are two kinds of usage of noexcept.
The noexcept operator used in noexcept(x.swap(y)) would return true if x.swap(y) is declared not to throw, and false otherwise.
It can be used within a function template's noexcept specifier to declare that the function will throw exceptions for some types but not others.
The... |
70,443,823 | 70,443,934 | Can someone please explain this logic to me when it comes to a priority queue. Get the 3rd highest in the array | There is a question that states. Given an array obtain the 3rd highest element.
Now suppose this is the array (lets assume that its sorted for now for simplicity - otherwise it can be unsorted)
//{1,2,3,4} -->Array under question. The answer is 2.
solution:
int findnHighest(std::vector<int> v, int n=3)
{
std::prior... | The priority queue is created via pq(v.begin(), v.begin() + n);, so it is of size n (3 in your example), and it is initialized to reference the first n elements of v. The top of the priority queue will always reference the element with the greatest priority in the queue. In this case, the element with the greatest prio... |
70,444,562 | 70,447,331 | Intel VTune / Memory Leak Detector -- what additional feature does Valgrind provide | Consider following code:
int main() {
for (int i = 0; i < 10; i++)
int *a = new int[10];
}
Intel VTune Profiler/Inspector is now a free suite from Intel available for both Windows as well as Linux (previously, the full version was only available free for academic noncommercial use). The memory leak detecto... | Valgrind works on several non-Intel architectures: ARM, POWER, MIPS. I don't know how well VTune works on AMD hardware.
Valgrind doesn't run natively on Windows, but it does run on FreeBSD, Solaris and (not very well on) macOS.
VTune and Valgrind features have some overlap but are not identical. Valgrind does not use p... |
70,444,744 | 70,444,993 | C++ Linux fastest way to measure time (faster than std::chrono) ? Benchmark included | #include <iostream>
#include <chrono>
using namespace std;
class MyTimer {
private:
std::chrono::time_point<std::chrono::steady_clock> starter;
std::chrono::time_point<std::chrono::steady_clock> ender;
public:
void startCounter() {
starter = std::chrono::steady_clock::now();
}
double getCounter() {
... | What you want is called "micro-benchmarking". It can get very complex. I assume you are using Ubuntu Linux on x86_64. This is not valid form ARM, ARM64 or any other platforms.
std::chrono is implemented at libstdc++ (gcc) and libc++ (clang) on Linux as simply a thin wrapper around the GLIBC, the C library, which does a... |
70,444,930 | 70,446,038 | How to check that SDP service record was registered correctly in C++/Linux | I am trying to register my bluetooth SDP service in C++ linux as shown here: Example 4-9. Describing a service
Where or how can I check exactly that the service is registered? I've tried viewing all services while running bluetoothctl or sdptool browse commands but service with my UUID is not shown there.
I've also tr... | The document you linked to is refering to a version of BlueZ that most systems don't run anymore.
Many of the tools it refers to (such as hciattach, hciconfig, hcitool, hcidump, rfcomm, sdptool, ciptool, and gatttool) were deprecated by the BlueZ project in 2017.
There is also the following SO question talking about th... |
70,445,044 | 70,445,170 | Constructor invocation order for member objects | I have the following class called Tree, which has a member object of class Leaf. Leaf requires a parameter from Tree (height_) for its construction. I can write an intialize method for this. But do we know the order in which constructors are called, so that dependencies in the construction of member objects are met whe... | Construction of the members happens in the order in which they are declared. This is very important for the following. If the order of declaration does not match the order in which the dependencies are used, then the program will have undefined behavior.
The initializers with which they are constructed can be specified... |
70,445,081 | 70,445,281 | Strange C++ syntax: setting function output with some value | I was trying to get pybind11 up and running, and I ran across some strange syntax:
#include <pybind11/pybind11.h>
int add(int i, int j) {
return i + j;
}
PYBIND11_MODULE(example, m) {
m.doc() = "pybind11 example plugin"; // optional module docstring
m.attr("the_answer") = 42;
m.def("add", &add, "A fun... | It is returning references to objects. Check this example:
class A {
private:
int var;
public:
int& internal_var() { return var; }
};
...
A a;
a.internal_var() = 1;
|
70,445,266 | 70,445,748 | Forwarding references: reference parameter origin | The whole premise about forwarding references (aka universal references) is, that this function:
template<typename T>
void f(T&&) { }
can result in the template parameter either being int& or int, depending if you call it with int a{}; f(a) or f(5) as example. But this is already a step too far I think. Because when I... | There is a specific exception in the template argument deduction rules for the case that a function parameter has the form T&& (cv-unqualified) where T is a template parameter. This special case is as seen in the question known as a forwarding reference.
For forwarding references, if the function argument is an lvalue,... |
70,445,319 | 70,489,878 | LLDB aborts breakpoint command execution after `step`, `next` etc | When I hit a breakpoint in LLDB I want to execute multiple commands that automatically step my program.
Example (this should alter the program to skip the first call made by foo::bar):
breakpoint set --method foo::bar --command s --command 'thread return'
When I try the above example:
I do hit the breakpoint
s is exe... | lldb does "programmed steps" differently from gdb. In lldb, if you want to cons up a "step, check something, step again" type operation, you do that by implementing your own version of a step command, using the same functionality as the built-in lldb step/next/etc operations. Then you add that as a new command alongs... |
70,445,481 | 70,501,473 | Error: Couldn't lookup symbols when calling an stl method in LLDB | When I wanted to alter the execution of the program I am debugging by resizing a vector, but I got an error:
(lldb) expression std_vector_foo.resize(1)
error: Couldn't lookup symbols:
std::vector<string_id<mtype>, std::allocator<string_id<mtype> > >::resize(unsigned long)
Strangely enough the following runs fine:
ex... | There are two ways to work around the absence of template methods that you want to call.
The most straightforward - if it works for you - is to turn on building the "stl module" for use in the expression parser by putting:
settings set target.import-std-module true
in your ~/.lldbinit. This will cause lldb to build a... |
70,445,764 | 70,448,487 | Template specification for a derived class in an std::shared_ptr | How would I provide a template specialisation for the Derived class in this simple case, assuming the Base cannot be changed - in my real code, Base is a library that I cannot change.
#include <iostream>
#include <memory>
class Base
{
public:
virtual void foo() { std::cout << "In base\n"; }
};
class Deriv... | The proper tool here is to use dynamic_cast<Derived*>. This is runtime information and as such must be queried at runtime.
Something like
void wibble(std::shared_ptr<Base*> baz){
if(auto derived =dynamic_cast<Derived*>(baz.get())){
// user derived pointer.
}
}
should allow you achieve something similar ... |
70,446,181 | 70,446,405 | Using Half Precision Floating Point on x86 CPUs | I intend to use half-precision floating-point in my code but I am not able to figure out how to declare them. For Example, I want to do something like the following-
fp16 a_fp16;
bfloat a_bfloat;
However, the compiler does not seem to know these types (fp16 and bfloat are just dummy types, for demonstration purposes)
... | Neither C++ nor C language has arithmetic types for half floats.
The GCC compiler supports half floats as a language extension. Quote from the documentation:
On x86 targets with SSE2 enabled, GCC supports half-precision (16-bit) floating point via the _Float16 type. For C++, x86 provides a builtin type named _Float16 ... |
70,446,294 | 70,446,449 | Concatenation of 2 byte arrays in constructor gives strange result | Qt 6.2.1 MinGW
I have 2 arrays, header FirstArray and body SecondArray. I know that copy-paste, isn't good in programming, so at first, did so :
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
const QByteArray FirstArray=QByteArray(std::begin<char>({static_cast<char>(0xA5), 0x5A, static_cas... | As mentioned in a comment, you are calling
const QByteArray operator+(const QByteArray &a1, const char *a2)
Which, per its documentation:
Returns a byte array that is the result of concatenating byte array a1 and string a2.
It excepts a2 to point to a null-terminated string.
You can rearrange the concatenation to
Fi... |
70,446,464 | 70,446,586 | Mouse and keyboard always get input althoughtI don't do anything | I'm coding a game with SFML library. I have some code to do when I press key and mouse click
I use this:
Sf::keyBoard::isKeyPressed
And this:
Sf::Mouse::isButtonPressed
But somehow there code always run every frame although I don't click or press anything.
Is my computer wrong or something else?
| Can you try like this?
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space))
{
_isGameNotS... |
70,446,529 | 70,446,682 | the best design for mapping enums to const classes | I have this example that works :
I create an object that implements "PartInterface" for each value of the enum and add them in a map. But I don't find this satisfactory, because everything could be inferred at compile time rather than at runtime.
Is there a more elegant way to do this in c++ 11?
Another solution would ... | To be honest I don't understand why you need this whole machinery when a simple int getPart(DatePart,Date) would suffice. Most of the inefficiencies in the code seem to be selfmade. Anyhow, to adress only the mapping from enum to something else at compile time, you can use a template and specialize it for the enum valu... |
70,446,803 | 70,446,876 | How to do actions based on template typename checks? | Just started exploring template feature for one of my task, I need to add some actions based on the typename in the template. Can someone point out what is wrong with this kind of structure:
#include <iostream>
#include <type_traits>
using namespace std;
template <typename T>
T foo()
{
if(std::is_same<T, int>::va... | The problem is that, even if your T is int, all the branches still have to compile. So the second return statement causes an error because the string literal cannot be converted to the int return value.
Since C++17, you can use if constexpr to tell the compiler that the condition is a compile time constant which allows... |
70,446,843 | 70,446,883 | About func(const int&) and func(const int) | #include <iostream>
class Account {
public:
static double GetCircumference(const double &dR) { return 2 * dR * 3.1415926; }
static constexpr double cd = 3.0;
};
// constexpr double Account::cd;
int main()
{
std::cout << Account::GetCircumference(Account::cd) << std::endl;
}
The code is wrong unless I re... | In C++11, this in-class declaration:
static constexpr double cd = 3.0;
is not a definition (... until C++17; after which constexpr static data members are implicitly inline).
This is a out-of-class definition:
constexpr double Account::cd;
A definition is is needed if Account::cd is odr-used, which it is if it is pas... |
70,446,854 | 70,447,093 | Observation (check): same member function name, different signature, one as virtual member | I'm afraid this is not possible:
class A {
public:
A(){}
virtual string s() = 0
string s(int i) {
auto j = this->s();
... modify j ...
return j;
};
class B: public A{
public:
B() : A() {}
string s() override {
return string("Clas... | You may use virtual and non -virtual functions with the same name in base and derived classes.
In the example of classes in your question the definition of the virtual function s in the derived class B hides the non-virtual function with the same name declared in the base class A.
string s() override {
return string... |
70,446,969 | 70,447,543 | "expected primary-expression before ‘{’ token" when calling overloaded "<<" with customized data type | I have a simple class 'A' with the following contents:
class A {
public:
struct data_t {
int32_t val;
data_t(int32_t _val) :
val(_val) {
;
};
};
A& operator << (const data_t &data) {
printf("[%s] %d\n", __func__, data.val);
return *this;
... |
Why a<<{100}; is NG and a.func({100}); is OK?
The grammar of the language simply only allows braced initializer lists in certain places. As operand to (arithmetic) operators in expressions it is generally not allowed, even thought one might be able to make sense of it for overloaded operators.
Braced initializer list... |
70,447,329 | 70,447,520 | c++ program to check entered number by user | I am new to programming, started with C++ quite recently and I use CLion IDE.
I need to solve something, but I am not sure how exactly and I need your help with a basic C++ console program.
if the user enters a ten-digit number and the fifth number is one, the output should be this word - "zadochno".
if the user enters... | You can take the input from the user as std::string and then check if the element at index 4 is 1 or 2 as shown below:
#include <iostream>
#include <string>
int main()
{
std::string input;
//take input from user
std::getline(std::cin, input);
//check if the 5th letter(at index 4 since indexin... |
70,447,572 | 70,447,753 | Trying to pipx install Brownie without installing MS Visual C++ | I'm currently trying to install Brownie for Python on my Windows machine using pipx:
pipx install eth-brownie.
When I run this command, there is a "fatal error" message saying:
pip failed to build packages: bitarray cytoolz lru-dict
I also get a "possibly relevant" error message:
Microsoft Visual C++ 14.0 or greater is... | pip failed to build packages: bitarray cytoolz lru-dict
bitarray PyPI page regarding installation states
If you have a working C compiler, you can simply:
$ pip install bitarray
If you rather want to use precompiled binaries, you can:
conda install bitarray (both the default Anaconda repository as well as conda-forg... |
70,447,594 | 70,447,686 | understanding move semantic for a shared_ptr with an rvalue function call | In the following small program I have two examples of using move with shared_ptr.
The first example behaves as I expected and the ownership of the shared_ptr p is assigned to the new pointer p2. After the assignment p is an invalid pointer.
I would expect the same to happen also in the second example, but it does not. ... |
Why has ownership not transferred to the argument of the function foo?
Because the parameter type of foo is an rvalue reference of shared_ptr, no new shared_ptr object is created, the p in foo is just a reference to the original p which is not moved to any object.
If you change foo to pass by value, a new shared_ptr ... |
70,447,727 | 70,457,992 | Changing the title of uwp process | I want to change the title bar of calc.exe. I read that it's done via SetWindowTextA() but when I used this it only change the title of the preview (1) and I want to change title at (2) as well.
Can anyone explain for me why it change the title at (1) not (2) and how can I change the title at (2)
| The Calculator title is Text Control Type retrieved using UI Automation. However according to Text Control Type, the IValueProvider is never supported by text controls. So you can’t.
Edit:
#include <Windows.h>
#include <UIAutomation.h>
#include <wchar.h>
int Element(IUIAutomation* automation)
{
// Get the element... |
70,448,564 | 70,599,149 | Similar function to Input("msg") from python in C++ | I am looking to make this function in c++, input("x = ");, somewhat like in python, this function prints the message in the () and the expects input. It can take only bool,str,int,double. I thought of making a struct input like so
struct input {
std::string str;
int num;
double dub;
bool boolean;
input(const cha... | What i did was make a class,
template <typename T> using couple = std::pair<bool, T>;
struct input {
std::string inp;
couple<std::string> str = {false, ""};
couple<int> num = {false, 0};
couple<double> dbl = {false, 0};
couple<bool> bl = {false, 0};
input(const char *s) {
std::cout << s;
std::cin >... |
70,448,584 | 70,450,131 | Implementing bluetooth client/server architecture in C++ DBus | I need to connect my android phone to the Linux PC via bluetooth. Phone needs to be able to create connection through the PC MAC and the UUID of the service (or UUID only) fully authomatically. And phone should be the connection initiator.
I've used this example: An Introduction to Bluetooth Programming and ran into pr... | Before diving in to coding it might be useful to experiment with interacting with the BlueZ bluetoothd through the D-Bus API. This can be done with various command line tools. I'm going to assume that you will be using the gdbus library for your C code so that seems like a good choice to experiment on the command line.... |
70,448,592 | 70,450,684 | Tracing recursion calls | I'm learning the concept of recursion and, to pratice my knowledge, I wrote the following program.
#include <bits/stdc++.h>
using namespace std;
int c = 0;
int add(int a) {
if (a == 0) {
return c;
}
c = c + 1;
add(a - 1);
cout << "Hello";
}
int main() {
int x = add(6);
cout << "Final " << x;
}
It... | The main issue of the posted function is that it has undefined behavior.
int add(int a) { // Note that this function is supposed to return an int.
if (a == 0) {
return c; // <- Ok, recursion stopped, first exit point.
}
// else
c = c + 1;
add(a - 1); // Recursive call. When it returns, ... |
70,448,684 | 70,567,681 | Doxygen: why is the first element of my enum class not properly copied with copydoc? | I have the following code:
/**
* @brief OpenGL renderer rescale types
*/
enum class RescaleType {
None, //!< No rescale
Horizontal, //!< Rescale horizontally
Vertical, //!< Rescale vertically
Both //!< Rescale both
};
/**
* @brief
*
* @param type Type of rescaling to apply. It can be one of the... | For those wondering: this was a bug and was fixed in commit ab74ff26b0f9ba3f31d1dce605c4a1809ca9cb5c and is now part of Doxygen release 1.9.3. Huge thanks to @albert for lightning fast patching :-)
|
70,449,141 | 70,460,487 | ATL: OnDrawThumbnail hDrawDC seems to be monochrome in IThumbnailProvider | I'm working on a C++ ATL COM thumbnail/preview/search project, but its bitmap displaying code behavior is monochrome during the Thumbnail process instead of the colored. The Preview process is colored as expected, using the same function.
I used the ATL Wizard to create the IThumbnailProvider and his friends. My small ... | Github helped me. It is definitely an ATL SDK bug.
BUG report on the VS developer community
Solution on the www.patthoyts.tk
And the github repo which helped me: abhimanyusirohi/ThumbFish
In the atlhandlerimpl.h provided GetThumbnail must be override:
BOOL document::GetThumbnail(
_In_ UINT cx,
_Out_ HBITMAP * phbmp... |
70,449,440 | 70,449,844 | C++ destructor destroys objects couple times | I am new in C++ so have a question.
There is C++ code:
class Test
{
public:
std::string name;
Test(){};
Test(std::string name) {
std::cout << "Create " << name << '\n';
Test::name = name;
};
~Test() {std::cout << "Destroy " << name << ... | Let's add a copy constructor (and use a smaller test case, to cut the verbosity) and see what happens...
#include <iostream>
#include <string>
#include <vector>
class Test
{
public:
std::string name;
Test(){};
Test(std::string name) : name(name) {
std::cout << "N... |
70,450,019 | 70,450,307 | Size of object and C++ standard | Looking around I found many places where the way to get the size of a certain object (class or struct) is explained. I read about the padding, about the fact that virtual function table influences the size and that "pure method" object has size of 1 byte. However I could not find whether these are facts about implement... | The memory layouts of classes are not specified in the C++ standard precisely. Even the memory layout of scalar objects such as integers aren't specified. They are up to the language implementation to decide, and generally depend on the underlying hardware. The standard does specify restrictions that the implementation... |
70,450,263 | 70,450,339 | string input not printed correctly on the screen | I am trying to read in a string from the user input and then print it on screen. However, when the string is printed on the console, it is kind of gibberish. The funny thing is that it works in Visual Studio and not in CodeBlocks.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main... | You should explicitly specify memory size for string.
That code:
char sentence[] = "";
declares sentence with max size is 0 (+1 zero symbol). Of course, you write more data into not-your memory.
Try this:
char sentence[200] = "";
|
70,450,406 | 70,450,503 | Optional non-trivial destructor using requires | What is the correct way to declare an optional non-trivial destructor using C++ 20 requires? For copy constructor and move constructors it has worked for me to declare the non trivial requires copy/move constructor first and then the default declaration, but for destructors I'm getting weird behaviour:
#include <string... | GCC is correct. The order should not matter.
Clang documentation indicates that it hasn't yet implemented P0848, which would make your example compile. It's surprising to me that Clang does compile the example in one order but not the other, and that MSVC behaves similarly, but I guess they just look at the first prosp... |
70,450,501 | 70,450,714 | How to pass variable to const char type? | void printLCD(int col, int row , const char *str) {
for(int i=0 ; i < strlen(str) ; i++){
lcd.setCursor(col+i , row);
lcd.print(str[i]);
}
}
void loop(){
lightAmount = analogRead(0);
// Here
printLCD(0, 0, printf("Light amount: %d", lightAmount ));
}
I'm newbie to c language for a... | printf doesn't return the string, it prints it to a standard output which is not configured on most Arduinos by default.
You can use snprintf C function to format a string in Arduino sketch.
void printLCD(int col, int row , const char *str) {
lcd.setCursor(col, row);
lcd.print(str);
}
void loop(){
lightAmount ... |
70,450,584 | 70,466,926 | Different catch2 checks on different inputs | I'm trying to test some code that requires a little bit of setup to use, and I'd like to avoid repeating the setup steps. The setup steps have some dependency on the input, but the results could be significantly different depending on what exactly the inputs are. Is there a good way to set up a catch2 test case for t... | I tend to write small helper functions (or lambdas) even for simple cases. For your example, this could be as short as:
#include <catch2/catch.hpp>
auto rootTest(double x)
{
return SquareRoot{x}.root();
}
TEST_CASE("SquareRoot") {
SECTION("positive") {
CHECK(rootTest(4.0) == 2.0);
REQUIRE(errno == 0);
... |
70,450,713 | 70,450,771 | Are user defined constructors and member functions inline by default? | Let's have
class ClassA
{
public:
ClassA() = delete;
ClassA(int InObjectID):ObjectID(InObjectID){};
int GetID(){return ObjectID;};
private:
const int ObjectID;
}
a. Is the function ClassA(int) inline by default?
b. Is the function GetID(void) inline by default?
|
a. Is the function ClassA(int) inline by default?
b. Is the function GetID(void) inline by default?
Yes. Member functions that are defined within the class definition are implicitly inline.
|
70,450,785 | 70,451,037 | virtual machine for lc3 | Hello I can’t figure out why in the add instruction I need to and by 7
this is the cpp code for the Add instruction
uint16_t dr = (instr >> 9) & 0b111;
uint16_t sr1 = (instr >> 6) & 0b111;
uint16_t sr2 = instr & 0b111;
uint16_t second = registers[sr2];
ui... | Take a look at the first line of code: it tries to decode the destination register, which is in bits 9-11 of your input number.
Assuming instr has 16 bits abcdefgh ijklmnop, then we want to extract bits 9-11, which is efg:
instr >> 9 shifts everything to the right by 9 bits, but the answer still has 16 bits: 00000000 0... |
70,451,679 | 70,453,748 | Why is my explicit constructor creating this ambiguity for my conversion operator? | I'm unable to figure out why my conversion operator is considering the explicit constructor.
#include <utility>
template <typename T = void>
struct First
{
template <typename... Targs>
First(Targs&&... args) {}
};
template <>
struct First<void> {};
template <typename T>
struct Second
{
template <typename... | Although it seems like it does,
static_cast<A<float>>(a);
does not in fact first try to call a user-defined conversion function. In reality it behaves identical to an imagined declaration
A<float> temp_obj(A);
where temp_obj is an invented name for the created temporary.
As a consequence,
A<float> b = static_cast<A<f... |
70,452,255 | 70,452,386 | C++ - How to left/right circular shift a bitset? | Let's say I have a std::bitset<28> called left28.
I'm looking to left circular shift left28.
After doing some searching, I came across std::rotl (C++20) but it doesn't seem to play nice with bitset, so I have no idea how I'm going to pull this off.
| You can implement a left circular shift by combining right shifts with left shifts.
template<size_t N>
std::bitset<N> rotl( std::bitset<N> const& bits, unsigned count )
{
count %= N; // Limit count to range [0,N)
return bits << count | bits >> (N - count);
// The shifted bits ^^^^^^^^^^^^^ ... |
70,452,459 | 70,453,352 | Updating part of a wider integer through a uint8_t reference | #include <cstdio>
#include <cstdint>
struct Registers {
Registers() : af(0),
f(*(reinterpret_cast<uint8_t *>(&af))),
a(*(reinterpret_cast<uint8_t *>(&af) + 1)) {
}
std::uint16_t af;
std::uint8_t& f;
std::uint8_t& a;
};
int main() {
Registers r;
r.af = 0x00FF;
r.a = 0xAA;
... | As you have noted in your question, the fact that you are casting to a "byte" type almost certainly removes any issues of violating strict aliasing requirements.
Nevertheless, from a strict, "language-lawyer" perspective, the reinterpret_cast<uint8_t *>(&af) + 1 expression potentially invokes undefined behaviour – beca... |
70,452,859 | 70,452,921 | Why does it say the length of the array is 1 in this function (C++)? | So I'm trying to make a function that gets the length of an array by returning the sizeof the array and sizeof the integer type...
code:
#include <cstdio>
#include <iostream>
using namespace std;
int len(int *thing) {
return sizeof(thing) / sizeof(int);
}
int main() {
int fard[] = {100, 45, 1, 723, 500};
... | The function parameter has a pointer type
int len(int *thing) {
return sizeof(thing) / sizeof(int);
}
Even if you will rewrite the function like
int len(int thing[]) {
return sizeof(thing) / sizeof(int);
}
nevertheless the compiler will adjust the array type of the function parameter to the type pointer to th... |
70,453,036 | 70,453,146 | Why GCC generates strange way to move stack pointer | I have observed that GCC's C++ compiler generates the following assembler code:
sub $0xffffffffffffff80,%rsp
This is equivalent to
add $0x80,%rsp
i.e. remove 128 bytes from the stack.
Why does GCC generate the first sub variant and not the add variant? The add variant seems way more natural to me than to exploi... | Try assembling both and you'll see why.
0: 48 83 ec 80 sub $0xffffffffffffff80,%rsp
4: 48 81 c4 80 00 00 00 add $0x80,%rsp
The sub version is three bytes shorter.
This is because the add and sub immediate instructions on x86 has two forms. One takes an 8-bit sign-extended immediate, and... |
70,453,149 | 70,453,249 | how do I replace base constructor call | In recent SO answer, part of the snippet I'm unable to understand whats happening,
struct VariableDepthList : std::variant<std::vector<VariableDepthList>, int> {
private:
using base = std::variant<std::vector<VariableDepthList>, int>;
public:
using base::base;
VariableDepthList(std::initializer_list<Variabl... |
what is equivalent to without having using base::base?
You replace it with what base is an alias for:
struct VariableDepthList : std::variant<std::vector<VariableDepthList>, int> {
private:
public:
VariableDepthList(std::initializer_list<VariableDepthList> v) :
std::variant<std::vector<VariableDepthList>,... |
70,453,406 | 70,453,659 | How to remove empty expressions while formatting with clang-format? | Is there an way to remove empty expressions (redundant semi-colons) like below using clang-format?
int main() {
return 0;
}; <- redundant ;
Naïve search-replace won't work due to other valid cases like below:
struct A {
int a;
}; <- required
Search for empty/expression/semi/colon gives nothing relevant on clang... | There is a "Bugprone suspicious semicolon" on clang-tidy but it does not pick up the case you provided.
clang-tidy will fix code for you given the right case. Example:
# cat test.cpp
int main()
{
};
$ clang-tidy --fix -checks=modernize* test.cpp --
1 warning generated.
test.cpp:1:5: warning: use a trailing return typ... |
70,453,567 | 70,453,738 | Global scope friend operator declaration when class in namespace and using templated type as return type | I am struggling with friend statement for a templated operator and namespaces.
Sorry if I'm a bit long but I want to give a good description of my issue.
First, some context. Forget about the namespace at present.
I have a class A and a public operator that needs to access its private member:
template<typename U>
struc... | Unless the befriend function template is declared already, I don't think you define this function template outside the class definition: essentially, there is no way to actually name the operator. To make things a bit more interesting, the two parameter types operated on are actually in a different namespace, i.e., the... |
70,453,599 | 70,453,807 | Is std::ranges::size supposed to return an unsigned integer? | Here it is written that std::ranges::size should return an unsigned integer. However, when I use it on an Eigen vector (with Eigen 3.4) the following compiles:
Eigen::VectorXd x;
static_assert(std::same_as<Eigen::VectorXd::Index,
decltype(std::ranges::size(x))>);
where Eigen::VectorXd::Index... |
Is this a bug of std::ranges::size?
No. The cppreference documentation is misleading. There is no requirement for std::ranges::size to return an unsigned integer. In this case, it returns exactly what Eigen::VectorXd::size returns.
For ranges that model ranges::sized_range, that would be an unsigned integer, but Eige... |
70,455,076 | 70,455,136 | accessing a c++ unique pointer declared in hpp file when set in a cpp file through constructor | I'm a c++ beginner and am a little confused about how I would set a private unique from a class constructor while still managing to access it from other public functions. Should I even be using a unique pointer to begin with or a shared pointer instead?
example: (from a project I was working on)
header.hpp
class PixelH... | Maybe you should do:
ppm = std::make_unique<Ppm>(picture.substr(0, -4) + ".ppm");
Because you can't assign the object (of type Ppm) to a pointer. You need to pass it to the constructor of the std::unique_ptr so that it can create a unique pointer that is pointing to that object.
|
70,455,146 | 70,455,297 | multiplication table on two dimensional array | I did a multiplication table on two dimensional array but I want too change this code and do it on 5 values which I input for ex.
I will input:
2.5 3.0 4.6 6.3 8.1
2.5
3.0
4.6
6.3
8.1
and it will multiplicate 2.5 * 2.5 etc.
int tab[5][5];
for(int i=1; i<=5; i++)
{
for(int y=1; y<=5; y++)
{
... | Okay, now the assumption is that this 2D array is always square, and the column values are the same as the row values (like you show in your example).
You will need to store these values that we want to multiply.
Let's call that array of values x.
You won't have to change much in your current code, but rather than i*y,... |
70,455,494 | 70,455,586 | <ask> modified string using memcpy | Can anyone explain what's wrong with my code
#include <iostream>
#include <cstring>
#include <string.h>
using namespace std;
int main () {
char x[] = "abcdefghi123456"; // length 15
cout << "original string length: " << strlen(x) << endl;
cout << "string before modified: " << x << endl;... | First off, <cstring> and <string.h> are the same thing, just that <cstring> wraps the contents of <string.h> into the std namespace. There is no need to use both headers, use one or the other - use <string.h> in C, and <cstring> in C++.
More importantly, x is a fixed-sized array of 16 chars, as it is being initialized... |
70,455,662 | 70,455,853 | If else function constantly outputting 0 instead of a number conditioned | Below is only a partial function I am trying to execute of a bigger function. I am trying to assign a case number that will convert an integer returned from this function into a string. However, I don't know what the issue is, but this is constantly outputting 0 for some reason. What am I doing wrong?
#include <iostrea... | As suggested by @Remy Lebeau, you can simplify caseCalc a lot.
Here it is:
#include <iostream>
int daysFromNow { };
int caseNumber { };
int caseCalc(const int daysFromNow);
int main( )
{
std::cout << "Please enter how many days from now: ";
std::cin >> daysFromNow;
std::cout << caseCalc(daysFromNow);
}
... |
70,456,010 | 70,456,222 | Loop is not terminating, please someone explain what am doing wrong | I can't find out, why this loop is not terminating. please someone explain. What am I doing wrong.
std::vector<int> vec{};
int result{0};
for (unsigned i = 0; i < vec.size() - 1; i++) {
for (unsigned j = i + 1; j < vec.size(); j++) {
result += vec.at(i) * vec.at(j);
}
}
std::cout << result;
I wanted t... | vec.size() returns an unsigned type, so size() - 1 will wrap around to a very large value if size() is 0. You don't need the - 1 in the first place, since your inner loop already handles the edge cases where pairs of integers are not available to multiply.
You also don't need the overhead of vec.at(index) since your lo... |
70,456,198 | 70,456,737 | Automatic callback to close fstream contained in file logger class | To log different values in different parts of my c++ application I want to be able to instantiate a class that abstracts all the required commands for logging different values in a file. This is a prototype header of the class:
#include <string.h>
#include <fstream>
#include <iostream>
#include <Eigen/Dense>
....
cl... | The destruction of each FileLogger solves this automatically since fileHandle_ will be closed when the FileLogger either goes out of scope or when you call std::exit.
|
70,456,209 | 70,456,411 | Any workarounds for this MSVC specific vector<unordered_map<Trivial, NonCopyable>> bug? | The following code does fail on MSVC but compiles on GCC and Clang, godbolt
#include <unordered_map>
#include <vector>
using namespace std;
struct NonCopyable
{
NonCopyable() = default;
NonCopyable(NonCopyable const &) = delete;
NonCopyable(NonCopyable &&) = default;
};
int main()
{
using Data = unord... | Apparently this is a long time know bug with a combination of MSVC STL implementation choices and Standard specifications...
The issue I found when I was going to submit a bug report, from 2018:
https://developercommunity.visualstudio.com/t/C2280-when-modifying-a-vector-containing/377449
This error is present in MSVC ... |
70,456,273 | 70,456,305 | Why does passing lambda to constrained type template parameter result in `incomplete type` compiler error? | I have a concept that helps me detect the signature of a function:
template <typename>
struct FuncHelper;
template <typename R, typename... Args>
struct FuncHelper<R(Args...)> {
template <typename Func>
static constexpr bool is_like = requires(const Func& f, Args... args) {
{ f(std::forward<Args>(args).... | These two:
template <typename T> requires function_like<bool(), T>
void testWorks(T&& func) { }
template <function_like<bool()> T>
void testFails(T&& func) { }
are not equivalent. The latter is equivalent to:
template <typename T> requires function_like<T, bool()>
void testFails(T&& func) { }
Note the different orde... |
70,456,434 | 70,456,665 | Understanding assembly instructions for a function summing three ints of an std::array | I have the following c++ function which simply sums the three elements of the given input array.
#include <array>
using namespace std;
int square(array<int, 3> ar) {
int res = 0;
for(int idx = 0; idx < ar.size(); idx++){
res += ar[idx];
}
return res;
}
This code compiled with Clang (gcc and ic... | The array is packed into registers for parameter passing as if it was a simple struct of 3 ints.
So, two 32-bit int elements are passed in the first argument register, and the remaining one in the second argument register.
How those first two are packed into one register may seem somewhat arbitrary, given that there is... |
70,456,518 | 70,456,535 | How to pass a template function as an argument in C++? | Consider this for a second:
template <class T_arr, class T_func>
void iter(T_arr *arr, int len, T_func func)
{
for(int i = 0; i < len; i++)
{
func(arr[i]);
}
}
void display(int a) {
std::cout << "Hello, your number is: " << a << std::endl;
}
int main(void)
{
int arr[] = {1, 2, 3};
... | You need to specify the template argument for display explicitly:
iter(arr, 3, display<int>);
Or make iter taking function pointer:
template <class T_arr>
void iter(T_arr *arr, int len, void (*func)(T_arr))
{
for(int i = 0; i < len; i++)
{
func(arr[i]);
}
}
then you can
iter(arr, 3, display); // t... |
70,456,581 | 72,510,853 | How to detect main keyboard connection and disconnection on Windows | I'm working on an application that uses Window's window and raw input APIs.
I can get input without too much difficulty and right now I'm trying to detect when devices are connected or disconnected from the application. To do so I'm listening to WM_INPUT_DEVICE_CHANGE and using GetRawInputDeviceInfo() to fetch device i... | There is no such concept such as "main keyboard" in Windows API.
All keyboard button presses are posted to message queue as WM_KEYDOWN/WM_KEYUP and WM_INPUT.
With RawInput you can distinguish which keyboard sent particular input - but it is your decision which keyboard you want to hear (you can filter by keyboard handl... |
70,456,631 | 70,456,679 | error message of no suitable user-defined conversion | #include <iostream>
#include <string.h>
#include <strings.h>
#include <algorithm>
#include <bits/stdc++.h>
#include <string>
#include <algorithm>
#include <iterator>
#include <list>
int main(){
char buffer[32] = {0};
std::string temp;
std::string apend;
//memset(buffer, '\0', sizeof(buffer));
std::cout << ... | You need to use the correct type which is decltype(temp)::iterator ptr1 = temp.begin(); - that is, ptr1 is a std::string::iterator, not a std::vector<std::string>::iterator. So for your snippet to compile, change
std::vector<std::string>::iterator ptr1 = temp.begin();
to
auto ptr1 = temp.begin(); // ptr1 is a std::str... |
70,456,663 | 70,456,734 | Why is the for loop and the hard coded yielding different results? | I have created a program in C++ that doesn't work when the thread vectors' components are created with a for loop and does when they are created hard coded.
This is the hard coded example:
std::vector<std::thread> ThreadVector;
ThreadVector.emplace_back(std::move(std::thread([&](){cl.run(maxLast, vals[0], 0);})));
Thre... | std::thread([&]
[&] means that all objects captured by the closure get captured by reference.
cl.run(maxLast, vals[i],i)
i was captured by reference. i was the parent execution thread's loop variable, that gets incremented on every iteration of the loop.
C++ gives you no guarantees, whatsoever, when each execution th... |
70,456,755 | 70,458,681 | Using Gcov with CMake and Catch | I want to use Gcov to report coverage for my static library Catch test suite, compiled using CMake.
.
├── CMakeLists.txt
├── bin
├── CMakeModules
│ └── CodeCoverage.cmake
├── src
│ ├── some_function.cpp
│ ├── another_function.cpp
│ └── library_name.hpp
└── test
└── main.cpp
I followed the instructions here... | According to implementation of SETUP_TARGET_FOR_COVERAGE_LCOV command, it passes the whole content of EXECUTABLE clause to the COMMAND clause of the add_custom_target. The latter accepts a shell command line, so you may create a command line which runs your tests but always returns zero. E.g. that way:
EXECUTABLE bin/t... |
70,457,355 | 70,457,572 | Transfer ownership of a derived class unique_ptr to its abstract base class unique_ptr | I want to transfer ownership of a derived class unique_ptr to its abstract base class unique_ptr in a polymorphic situation. How to go about?
class Fruit {
public:
virtual void print() = 0;
};
class Apple: public Fruit {
public:
string name;
virtual void print() { cout << " Apple name is " << name << end... | To transfer ownership of a derived class managed by a derived class unique_ptr to a base class unique_ptr, you can (and should) use move semantics.
std::unique_ptr<Derived> foo = std::make_unique<Derived>();
std::unique_ptr<Base> bar = std::move(foo);
To return ownership to a derived unique_ptr, you need to ge... |
70,457,722 | 70,458,022 | VSCode C++ Intellisense can't discern C++20 features | I try to run codes like
#include <string>
#include <iostream>
int main() {
std::string str = "This is a string";
std::cout << str.starts_with("name");
}
But intellisense will give out an error
"std::__cxx11::basic_string<char, std::char_traits,
std::allocator>" has no member "starts_with" C/C++(135) [6,9]
A... | Assuming you are using Microsoft's C/C++ extension, you must configure the extension to use C++ 20 standard for intellisense.
The easiest way to do this is to add the line "C_Cpp.default.cppStandard": "c++20" to your settings.json file. You can also find the setting in the GUI under the name "Cpp Standard". Selecting c... |
70,457,804 | 70,458,053 | I have a problem wth a Codechef ATM question, my code works fine with custom inputs which are in the example, but fails when submitted | This is my code. It runs correctly with custom example inputs, but fails when I submit it.
Also I don't know how to add constraints as given in question.
The link to the question is : https://www.codechef.com/submit/HS08TEST.
#include <iostream>
#include<iomanip>
using namespace std;
int main() {
// your code goes... | The account should have enough balance for bank charges.
#include <iostream>
#include<iomanip>
using namespace std;
int main() {
// your code goes here
int r;
cin >> r;
float balance;
cin >> balance;
float amount;
if (r%5==0 && (r+0.5) <= balance ){
amount = float(balance ... |
70,458,373 | 70,458,478 | recursive function calling in c++ | Whats the difference between
return(checkBst(root->left, minvalue, root) && checkBst(root->right, root, maxvalue));
and
return(checkBst(root->left, minvalue, root));
return(checkBst(root->right, root, maxvalue));
My whole programme looks like this
bool checkBst(node *root, node * minvalue, node * maxvalue){
if(ro... | To be frank, you cannot have a return for each of the function calls. This is because return is the last statement executed in a function before the control is given back to the calling function.
In your case, the second function is NEVER called. So, if your first function returns true, it never calls the 2nd function.... |
70,458,730 | 70,458,872 | Read 0 and 1 text file as binary in Qt | I want to read a text file that contains 0 and 1 as binary, consider this example:
textfile.txt:
001001100101
010100011100
100000110001
001111110101
100010110101
111010100100
011011000110
I want to read this stream of 0 and 1 as binary or read then convert it. If we consider first line "001001100101", I want to conver... | If there are only 0 and 1 in your file,
you can use stl std::stoi(const string& str, [size_t* idx], [int base])
string bin_string = "001001100101";
int number = stoi(bin_string, nullptr, 2);
|
70,459,005 | 70,459,096 | accessing elements in 2D pointer pointing to an dynamic array C++ | #include <iostream>
using namespace std;
void create(int** map);
int main() {
int** map;
create(map);
cout << endl << "printing map in main" << endl;
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
map[i][j] = 1;
cout << map[i][j] << " ";
}
... | Your code with a bit of refactoring:
#include <iostream>
int** create2DArray( const std::size_t rowCount, const std::size_t colCount );
void delete2DArray( int** const array2D, const std::size_t rowCount );
void print2DArray( int** const array2D, const std::size_t rowCount, const std::size_t colCount );
int main( )
... |
70,459,235 | 70,459,458 | c++ std multidimensional array memory layout | What will be the memory layout when defining multidimensional std array?
will it be single continuous memory block or array of pointer?
for example -
const size_t M = 5;
const size_t N = 4;
int simple_2D_array[M][N];
std::array<std::array<int,N>,M> std_2D_array;
is it guarantee that both simple_2D_array and std_2D_arr... | int simple_2D_array[M][N];
This is guaranteed to be contiguous in memory. You can use pointer arithmetic to calculate the position of any index relative to the start.
std::array<std::array<int,N>,M> std_2D_array;
This, in general, does not have to be contiguous in memory. It is an array of objects, each of which happ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.