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 |
|---|---|---|---|---|
65,790,477 | 65,791,064 | How to use std::unordered_map with 'external' keys | My goal is to write a class that works like a unordered_map but keeps the insertion order of the elements while still allowing O(1) lookup by key.
My approach is as follows:
// like unordered_map but keeps the order of the elements for iteration
// implemented as a vector with a unordered_map for constant time lookups
... |
My goal is to write a class that works like a unordered_map but keeps the insertion order of the elements while still allowing O(1) lookup by key
... and without duplicating the key, in cases it's large and/or expensive.
So, you want two things:
a constant-time associative lookup with the same semantics as std::unor... |
65,790,920 | 65,791,202 | Append different types of data to a vector of bytes | I have a vector of byte which I wanted to store different types of data to it. I have defined that vector as packed_data which you can see it in the following member function of my class.
Now I wanted to get different type of data with the PackedData member function and then append those information to the raw_data vec... | If BYTE is an alias for char, signed char, unsigned char or std::byte, you can reinterpret_cast pointers to objects to pointers to BYTE, and use the InputIt overload of vector::insert.
This is only sensible if all your data are of trivial types.
std::vector<BYTE> PackedData()
{
std::vector<BYTE> packed_data;
/... |
65,790,921 | 65,791,114 | Nested string replace using C++ | I want to replace every single variables in a string with specified strings.
namespace math {
map<string,string> setVar;
string setVariable(string& str, const map<string,string>& variables) {
for(auto& m : variables) {
size_t pos;
while((pos=str.find(m.first)) != string::npos)
... | You need some kind of loop within makeToken:
while (isStillContainsVariables(...))
{ ... do the replacement ... }
|
65,791,363 | 65,791,498 | Typecasting uint8_t vector to ap_uint<128> openCL | I am working on a project on Xilinx Vitis that I created a arrayA with
std::vector<uint8_t,aligned_allocator<uint8_t>> arrayA(size);
Then I have filled it with some random values.
I need to pass it to a kernel that accepts ( ap_uint<128>* arrayA)
How do I link these properly?
I have tried creating a
ap_uint<128>* temp... | You can only reinterpret_cast arrays of char, signed char, unsigned char and std::byte, and uint8_t might not be an alias to one of those.
You also need to ensure that the data is properly aligned to treat it as ap_uint<128>.
using raw_vec_t = std::vector<unsigned char, boost::aligned_allocator<unsigned char, alignof(a... |
65,791,429 | 65,798,947 | Possibility to use GCC "--enable-frame-pointer" for 64bit targets | I'd like to ensure that a large set projects are build with the -fno-omit-frame-pointer flag for easier debugging with tools like ebpf.
One way of course would be to modify the build scripts of each of these projects, but that is a lot of work.
I've come across the possibility to configure gcc with --enable-frame-point... | I believe you are using an older version of GCC because support of this flag on x64 has been enabled some time ago (see e.g. this commit).
|
65,791,555 | 65,792,121 | List of CUDA runtime error codes doesn't match | I'm updating a Windows & MacOS C++ code base for a client of mine to use CUDA 10.1 instead of [8? something older], and there are 2 sections in a big internal error code list for recognized CUDA error codes; one for driver and one for runtime. Since newer error entries were missing on these lists I consulted the offic... | All the error codes in the CUDA runtime API, driver API, and application APIs (CUBLAS, for example) are documented and supplied as C/C++ enum types in header files. The design is intended for programmers to use these enumerations by name, not by value. Using them by value would leave the naïve or foolhardy programmer o... |
65,791,697 | 65,794,217 | Passing custom command-line arguments to a Rust test | I have a Rust test which delegates to a C++ test suite using doctest and wants to pass command-line parameters to it. My first attempt was
// in mod ffi
pub fn run_tests(cli_args: &mut [String]) -> bool;
#[test]
fn run_cpp_test_suite() {
let mut cli_args: Vec<String> = env::args().collect();
if !ffi::run_tests... | There are two pieces of Rust toolchain involved when you run cargo test.
cargo test itself looks for all testable targets in your package or workspace, builds them with cfg(test), and runs those binaries. cargo test processes the arguments to the left of the --, and the arguments to the right are passed to the binary.
... |
65,791,773 | 65,792,820 | After tokenizing string with hypen '-', hypen will get eliminated!! how to fix this in c++98 | below shell script saved file name as add.sh
#!/bin/sh
MY_EXEC="add";
add -Units 32 -raid 111 -log add.log
My code will read this file add.sh and store contents in vector. the vector[2] string content i,e "add -Units 32 -raid 111 -log add.log" will be tokenized using '-'.
after this o/p for this code will be like t... | If the only requirement is to get the expected output, you could use a space (' ') as the delimiter and modify the printing.
int main()
{
vector<string> vecOfStr;
vector <string> tokens;
// Get the contents of file in a vector
bool result = getFileContent("add.sh", vecOfStr);
string str = vecOfStr[2... |
65,792,236 | 65,805,361 | QT window not accessing another class object | I am trying to make a File Management System. I am new to QT and cannot understand what could be causing this problem. Any help would be appreciated.
I have a FileSystem class that i want to use in window2 (window2 is actually my main window)
//These are just some of methods of my FileSystem class
//Check if Folder ex... | So as per My understanding you are trying to create an object of FileSystem which is defined in mainwindow and when it goes out of scope it gets destroyed but if you want it FileSystem across you application you can make it a singleton class.
Secondly you are using std string and vector it will dispatch the container ... |
65,792,675 | 65,793,779 | how does assembler convert from assembly to machine code? | I know this has been asked many times, but I am looking for a simple interpretation.
Let's say I have some assembly code that C++ compiler generated.
Now assembler kicks in and it has to transform the assembly code into machine code.
Question 1). Will the C++ assembler compiler look at the table where each assembly ins... | Please try to limit your questions to one question per question. Neverthless, let me try and answer them.
Question 1
An “assembly compiler” is called an “assembler.” Assembly is assembled, not compiled. And the assembler is not specific to C++. It is specific to the architecture and can only be used to assemble ass... |
65,792,787 | 65,874,277 | The 'cppcoreguidelines-interfaces-global-init' goes wrong just in a specific scenario | Given the cppcoreguidelines-interfaces-global-init, specifically "initializing non-local variable with non-const expression depending on uninitialized non-local variable", which is exemplified here, I have the following scenario:
My team consists of 4 dev
We all have the same environment: VS2015
Everybody has the sam... | The issue that you are facing is caused by the static initialization order fiasco, which says in short that the order of construction and destruction of static and global variables across different compilation units is unspecified.
The fact that in your case the problem occurs (i.e. order of initialization causes a pro... |
65,793,797 | 65,796,079 | How do I copy the strings in a vector<pair<string, int>> to vector<string>? | I'm using GCC 9.2.0 and boost 1.55.
I have 2 vectors:
vector< pair< string, int > > source;
vector< string > dest;
I need to transform the source vector to the dest, such that it should contain only string elements of source vector.
Is it possible using boost::push_back and adaptors?
boost::range::push_back( dest, sou... | To continue the trend of posting mimimal improvements:
Live On Compiler Explorer
#include <boost/range/adaptor/map.hpp>
#include <fmt/ranges.h>
using namespace std::string_literals;
using namespace boost::adaptors;
template <typename R>
auto to_vector(R const& range) {
return std::vector(boost::begin(range), boos... |
65,793,885 | 65,794,317 | Convert errno to exit codes | I'm working on lib which uses a lot of file system functions.
What I want is that my function returns various of error codes (not just -1 as error) depending on errno in case file system function fails.
Although I could use errno values directly but I want to create some abstraction layer between my functions error cod... | I´d go for a std::map in a dedicated function. You don't have to care about gaps or anything as long as you use the provided error macros:
#include <iostream>
#include <errno.h>
#include <map>
namespace MyError
{
enum MyReturnCode: int
{
MY_INVALID_VAL = 0 , /* Invalid Mapping *... |
65,794,331 | 65,794,735 | Conan: Is there any way to manage profiles like a package | As far as I understand the Conan documentation, a Profile is something that must be managed manually by the user. Is this correct?
It would be neat if profiles and toolchains could be pushed/pulled like regular packages. I understand that the toolchain itself can be pushed as a tool-package (build_requires), but then y... | You are looking for Conan config command. Conan config is not only about conan.conf file.
With conan config install, you can import external profiles and install directly to your Conan cache folder.
As example, you can use Bincrafters' profiles available on Github. As you can see, it's a simple git repository with a fo... |
65,794,461 | 67,188,813 | DXR Descriptor Heap management for raytracing | After watching videos and reading the documentation on DXR and DX12, I'm still not sure how to manage resources for DX12 raytracing (DXR).
There is quite a difference between rasterizing and raytracing in terms of resource management, the main difference being that rasterizing has a lot of temporal resources that can b... | With DXR you need to start at shader model 6.2 where dynamic indexing started to have a much more official support than just "the last descriptor is free to leak in seemingly-looking overrun indices" that was the "secret" approach in 5.1
Now you have full "bindless" using a type var[] : register(t4, 1); declarative sy... |
65,794,668 | 65,794,849 | Decrease in performance when dividing by variable vs. dividing by const in C++ | I was solving a programming task and encountered the problem.
The task:
Consider a money system consisting of n coins. Each coin has a
positive integer value. Your task is to calculate the number of
distinct ways you can produce a money sum x using the available coins.
Print one integer: the number of ways modulo 10^... | The fact that the difference is that noticeable is.. surprising. Or lucky, that the difference was just enough to lower your run time enough to pass your arbitrary threshold of one second.
However what shouldn't be a surprise is the fact that a constant is faster to work with than constantly reading your random memory,... |
65,794,675 | 65,795,565 | Static polymorphism with virtual functions | This is a followup question of Static polymorphism with final or templates?. So it seems that the best solution for static-only polymorphism is to use CRTP. If you want runtime polymorphism, virtual functions are a good solution.
I find that not very elegant because the problems are actually very similar (and maybe you... | You are more likely to get something the other way around, runtime polymorphism that looks like static polymorphism, or that looks like something completely different.
The metaclass proposals floated for post-reflection C++ (maybe c++26) look powerful enough to do stuff like:
Interface IBob {
void foo();
};
and
Impl... |
65,794,722 | 65,794,953 | Lisp like C++ function calling with std::tuple and fold expressions | The most basic thing I can think about Lisp is how to call functions. To those who doesn't know how to do that in Lisp, is something like that:
(fun1 a b (fun2 c d))
; c and d are parameters to the function fun2,
; and a, b and the result of fun2 are parameters
; to the function fun 1
Well, I want to do something like... | You have to evaluate each argument recursively, something like:
template <typename T>
auto eval(T t)
{
return t;
}
template <typename ...Ts>
auto eval(std::tuple<Ts...> tuple)
{
return std::apply([](auto... args){ return std::invoke(eval(args)...); }, tuple);
}
Demo.
|
65,794,803 | 65,794,978 | C++ overloading * to multiply fractions of different types | I have a fraction class with private types N (numerator) and D (denominator). this is too allow the types to be of different number types. I have also made a operator function that overrides the asterisk so that I can do x*y where x and y represent fraction objects. However, unless both only use one type, it doesn't wo... | Your operator must have four template parameters:
template <typename N1, typename D1, typename N2, typename D2>
Fraction<N1, D1> operator*(Fraction<N1, D1>& f, Fraction<N2, D2>& g) {
N1 numerator;
D1 denominator;
numerator = f.getNumerator() * g.getNumerator();
denominator = f.getDenominator() * g.ge... |
65,794,883 | 65,795,031 | C++ Primer 5th Edition Chapter 16.5 Class-Template Specializations | I think the book contains an error on page 711:
In § 16.2.3 (p. 684) we introduced the library remove_reference
type. That template works through a series of specializations:
// original, most general template
template <class T> struct remove_reference {
typedef T type;
};
// partial specializations that will be u... | Yes, for unparenthesized id-expression, decltype yields the type of entity named by the id-expression, then decltype(i) yields the type int.
If the argument is an unparenthesized id-expression or an unparenthesized class member access expression, then decltype yields the type of the entity named by this expression.
... |
65,795,300 | 65,816,293 | How can i check in Vulkan code if extension is core extension? | I would want to know if is there any way to check if extension that is supported by hardware is core extension? Are core extensions always returned in supported extensions? I am asking because my code for checking if all extensions that I want are supported is copying array of these extensions to set, removing all exte... | You need to specify when you create an instance what version of Vulkan you are using in VkApplicationInfo::apiVersion. This API version specifies exactly the core API you get. In addition to that, there is functionality available in extensions, which are listed at runtime in "available extensions", and have to be req... |
65,795,607 | 65,795,827 | Class with an unordered set of itself | I simplified my question to this. Can I create a class that has an unordered set with template type itself? To be specific, for example a Square that has a pointer to an unordered set of neighbors. I got stuck trying to integrate a hash function with the class itself.
Here is my code:
#include <iostream>
#include <unor... | To solve the problem you're asking about, just declare std::hash<Square>::operator() before the Square definition, but don't implement it:
namespace std{
template<>
struct hash<Square> {
std::size_t operator() (Square const &) const;
};
}
Then after the Square definition, define the std::hash<Squar... |
65,795,659 | 65,796,633 | Unresolved externals when using libpng | VS beginner here!
I'm using the libpng library, which I installed via NuGet in VS 2019, for a C++ project. I have a function loadPng in renderer.h that reads a png along the lines of the manual.
png.h is included. The code itself has no errors. Error message is:
LNK2019 reference to an unresolved external symbole "png... | In MSVC, there are two main types of errors,
Errors starting with a C which states that its a compiler error.
Errors starting with a LNK with states that its a linking error.
Usually errors like LNK2019 happens when the linker cannot find a library or object file. So this means that your not including the library int... |
65,795,876 | 65,796,014 | Having class inherit all operators of template type | I created this class so I can have a value of any type which is either fixed or recalculated everytime it is used:
template <typename T>
class DynamicValue {
private:
std::variant<T, std::function<T()>> getter;
public:
DynamicValue(const T& constant) : getter(constant){};
template <typename F, type... |
The problem is, ideally, I'd be able to treat any DynamicValue<T> as if it were of type T. So if I were to create a new value (DynamicValue<A> a = A{1};), I'd be able to do a.b and get the attribute b of the value calculated by a.
That would require either operator. overloading or delegated inheritance. Both are not ... |
65,796,028 | 65,797,174 | Type 'string' could not be resolved | Im new to coding c++ and i am trying to call a function from another file to check if the string containing the text file is made up of alphabetic characters, but for some reason it is not working.
I am getting errors in my ap.cpp file saying
Invalid arguments '
Candidates are:
bool is_alpha(?)
'
and
‘is_alpha’ cannot ... | It'll be the best if you not use using namespace std; until you have a proper understanding about the language and its implications. If you were wondering what using namespace does is, it basically sets the content in the namespace and puts it to the global namespace (in which you don't need to specify where it comes f... |
65,796,231 | 65,796,679 | static_assert with SFINAE | The standard says in [temp.res]/8:
No diagnostic shall be issued for a template definition for which a valid specialization can be generated. If no valid specialization can be generated for a template definition, and that template is not instantiated, the template definition is ill-formed, no diagnostic required. ... ... | No, it's not meant to work. That is not a valid C++ program.
Per the very paragraph you cite, the template definition of your partial specialization is ill-formed NDR. There is no valid specialization that may be generated from it.
The standard typically designates something as ill-formed NDR because checking it reliab... |
65,796,556 | 65,796,674 | Is declaring variables as const redundant after constexpr was added to the language? | As the keyword constexpr implies const and it can also be calculated at compile time, does it mean that now declaring variables as const doesn't make sense and we should always declare them as constexpr?
|
and it can also be calculated at compile time, does it mean that now declaring variables as const doesn't make sense and we should always declare them as constexpr?
And must be calculated at compile time (ignoring the as-if rule).
So you can't declare constexpr a variable initialized with a run-time known value. But ... |
65,796,589 | 65,816,853 | How do you set annotation color for PoPieChartRep? | In short, how i set custom colors(different than slice) for labels of PoPieChartRep?
In more detail:
I'm trying to create a Pie chart with OIV's PoPieChartRep class, and i would like that the strings "Value1" and "Value2" have specific colors.
I saw a field in the online reference of PoPieChartRep, and setting isAnnoS... | Just for reference, setting all the labels to the same color is easy. PoPieChartRep contains an SoAppearanceKit named "annotationApp", so you just need:
auto appKit = (SoAppearanceKit*)pieChart->getPart("annotationApp", TRUE);
auto appMat = (SoMaterial*)appKit->getPart("material", TRUE);
appMat->diffuseColor.setValue(... |
65,796,600 | 65,797,024 | cpp exe file working on wsl but not working on windows10 cmd | I make an executable file with g++ in WSL with the command g++ main.cpp foo.cpp and is working fine in WSL environment.
But, In windows 10, command line, when I try to execute the file, it says The program cannot start or run due to incompatibility with 64-bit versions of Windows. [Unsupported 16-Bit Application]
So, t... | WSL is a Linux layer, its gcc will generate Linux executables. Running them through WSL will of course work, but if you try to run them in plain Windows will have Windows shrug its shoulders at you.
If you want to compile Windows executables from Linux you need to use gcc multi-targetting, essentially using the Windows... |
65,797,198 | 65,798,768 | C++ days passed from last check | I wanted to create a program that keeps track of the last time the user watered the plants (manual check). So basically... The user presses a button and the program set today's date as date1, then every day it updates date2. If the difference is bigger than a certain date, the program returns a string.
int main() {
i... | Here's an example that should do what i understood you want to achieve. Replace milliseconds with days (c++20) or with hours
#include <iostream>
#include <string>
#include <chrono>
#include <thread>
using namespace std::chrono;
using namespace std::chrono_literals;
template<typename DurationT>
bool time_elapsed(Durat... |
65,797,309 | 65,797,401 | Why my function creates a new object every time it is called? | I have a class "Room" which has a variable of type class "Hero". The problem I face is that whenever I call a method of type: RoomObject.GetHeroObject().MethodOfHero(), a new Hero object is created. What is even stranger is that RoomObject.GetHeroObject() alway returns the same object of type "Hero", however, MethodOfH... | The issue is that Room::getHero() returns a Hero, not a reference or a pointer to an existing Hero. This makes it so that a new copy of the Hero pointed to by Room::hero is made every time the function is called.
A solution for this would be to make getHero return either a pointer or a reference to Room::hero. Here is ... |
65,797,371 | 65,797,499 | Manual call of destructor | #include <iostream>
using namespace std;
namespace GB
{
class Test
{
public:
Test() { cout << "Constructor is executed\n"; }
~Test() {
cout << i << " " << "Destructor is executed\n";
this->i = 7;
}
int i = -1;
};
}
int main()
{
... |
Why destructor is called twice.
The first call is from the line i.~Test();.
The second call is the automatic call to the destructor when the variable i gets out of scope (before returning from main).
In first call of destructor memeber value is changed from 6 to 7 , still in second call it comes as 6.
That's caused... |
65,798,249 | 66,191,275 | How to filter out the result to get only file names in output result linux in c++98 | The current code snippet will match the pattern and list out all matching pattern files present in directory specified where in below example File is the pattern to be matched*, here the output will be listed with absolute path like below.
/home/downloads/File1
/home/downloads/File2
/home/downloads/File3
... | Kind of, you can filter out directories. Change GLOB_TILDE with GLOB_TILDE | GLOB_MARK like this:
vector<string> glob(const string& pattern) {
glob_t glob_result = {};
vector<string> filenames;
try {
int return_value = ::glob(pattern.c_str(), GLOB_TILDE | GLOB_MARK, NULL, &glob_result);
if (... |
65,798,255 | 65,798,729 | terminate called after throwing an instance of 'std::out_of_range' in C++ | I am new to C++ and learning data structures. In the below code I am getting an "out of range warning", and do not understand what I am doing wrong.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> numbers{100,-1,2,4,55,78,3};
int temp {};
int pass {};
pass = numbers... | It seems like you may not understand how std::vectors work.
You have only declared 7 elements in your vector which means you can only go up to the index 6. This is because std::vector's indices start at 0. This is true for std::array as well.
vector<int> numbers{100,-1,2,4,55,78,3};
However, in your code you have put t... |
65,798,262 | 65,873,863 | building for macOS-x86_64 but attempting to link with file built for macOS-arm64 | I wrote a code using c++ and OpenCV:
#include <iostream>
#include <time.h>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
using namespace std;
int main()
{
...
return 0;
}
then I trying to Running my code on the terminal and build using g++:
g++ $(pkg-config --cflags --libs opencv) -std=c++11 ... | I had the same problem, and the short answer is that Apple switched to using libc++ instead of libstdc++. If you want to compile it as you mention (via console g++) then the answer is here.
Also, you have mention g++ in tag, but be sure that you understand that gcc is alias of clang, and for using g++ compiler you have... |
65,798,318 | 65,798,728 | new-expression evaluation order in C++17 | By cppreference/eval_order rule 12 the call to the allocation function (operator new) is sequenced before (since C++17) the evaluation of the constructor arguments in a new-expression. Thus, I thought the following
Bar b;
Foo* f = new Foo(b.fun());
at runtime results in calling new first then fun() on b and lastly the... | Looking into the standard (version N4835.pdf):
7.6.2.7 New [expr.new]
23 The invocation of the allocation function is sequenced before the evaluations of expressions in the new-initializer. Initialization of the allocated object is sequenced before the value computation of the new-expression.
In your case b.fun() is ... |
65,798,686 | 65,798,859 | Applying std::min_element only on elments that satisfy a condition | Is there a way to find the minimum odd element of a vector of integers without basically reimplementing std::min_element and without doing additional work like computing the vector of odd integers first?
| While a custom comparison object suggested in another answer will be a simple solution for std::min_element (and similar) in particular, it won't work with all standard algorithms. A general approach that works with any standard algorithm is to define a custom iterator.
Customising, combining and extending standard alg... |
65,798,917 | 65,897,573 | Yaml_cpp in debug with visual studio 2019 and cmake | I'm trying to understand how to use my linux project on windows with visual studio 2019. So I write a simple test for yaml_cpp :
#include "yaml-cpp/yaml.h"
#include <iostream>
#include <string>
#include <cassert>
int main()
{
try
{
assert(1 == 2);
YAML::Node config = YAML::LoadFile("config.y... | It's definitely wierd that release file is found while debug is not. You should look at Visual Studio's test properties page (under "Editeur de liens", check "Dependances supplémentaires" in "entrée", and "Répertoire de bibliothèques supplémentaires" in "Général", then switch between "Debug" and "Release" config and se... |
65,800,392 | 65,800,443 | Polymorphism C++: Passing child object by value to function that accepts parent object | I am passing a child object by value to a function that accepts a parent object.
I did not expected to work because I thought that polymorphism involving upcasting applied only for pointers/references.
class A
{
public:
int x;
A() :x{ 5 } {}
};
class B : public A
{
public:
int y;
B() :y{ 5 } { x = 10; }
};
v... | Although passing b to foo will involve object slicing, that doesn't affect the value of b.x as seen by foo since that was set when the object was constructed. You just sliced away b.y, which has no effect in the code as written.
|
65,800,964 | 65,801,308 | Is constexpr the new inline? | To the best of my knowledge, the inline keyword in c++ can be traced back to old compilers (then known as "optimizing compilers") not being able to optimize as well as modern ones, so marking a function as inline told the compiler that this should be inlined, and as a side effect prevented ODR issues. As compilers got ... |
As I understand it, it tells the compiler that a certain function may be evaluated at compile time.
Not "may", but "can". The constexpr keyword does not tell the compiler what it is allowed to do (it may evaluate anything it wants at compile time). Rather the keyword tells the compiler a desired quality of the variab... |
65,801,243 | 65,801,434 | How do I make multiple if statements inside one another taking user input in C++? | so I am new to programming, especially with C++ and I am trying to write a bank program, where I am currently trying to make the person an "account" asking them if they want to make a Basic, Premium, or Elite account, and then confirming the account with a yes or no answer from the user. Here is my code:
#include <iost... | string mystr;
cout << "Hello there, which account would you like to start today? Basic, Premium or Elite? ";
cin >> mystr;
string yn_answer;
if (mystr == "Elite")
{
cout << "You have chosen the Elite account option. Is this correct? (y/n): ";
cin >> yn_answer;
if (yn_answer == "y")
{
cout << "G... |
65,801,269 | 65,801,590 | Is there something faster than a min heap for my use case? | My use case is as follows:
I need to get the minimum of a set of growing elements; I'll only need the minimum for any iteration
I will update the minimum value after which it is guaranteed to no longer be the minimum but its new position in the order is not in general calculable directly.
I push this new value back on... | Rather than removing the minimum element and reinserting the updated value, you could change the value in-place and down-bubble from the root. Removing the minimum element often replaces it with one of the worst elements to replace the root with, typically costing a long down-bubble, and then reinserting a relatively s... |
65,801,307 | 65,801,634 | accessing a member of a child object when it is in a base vector | Im currrently having issues accessing a member of a child object when it is in a base vector, I know it is an object slicing issue, im trying to use dynamic casting but im a beginner and am not really sure on the syntax or how to use it, any help would be appreciated
pseudocode:
class Base {}
Class Derived : public ba... | First technique is to rely on virtual functions:
class Base
{
public:
virtual int doStuff();
}
Class Derived : public base
{
public:
virtual int doStuff();
}
Then, items[0]->doStuff() will call the derived version.
Second technique is to downcast:
dynamic_cast<Derived*>(items[0]);
This will give yo... |
65,802,424 | 65,802,447 | Why do I get a heap error when using iter_swap this way? | Please view my code for Reverse String on LeetCode.
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
void printVector(vector<char>& s){
for(auto i: s){
cout << i << ", ";
}
}
void reverseString(vector<char>... | for(int pos = 0; pos <= s.size()/2; pos++){
iter_swap(s.begin() + pos - 1, s.end() - pos);
Here, when pos = 0, this accesses out of range and thus causes undefined behavior: s.begin() + pos - 1.
|
65,802,573 | 65,803,100 | What does this c++ syntax means? `inline const Color (&EnumValuesColor())[3] {...}` | What does the following c++ syntax means?
inline const Color (&EnumValuesColor())[3] {...}
Is it a function? I don't understand the syntax.
It is very different from the usual syntax type name(params){...}
It is generated from flatbuffers.
It is inside:
enum Color {
Color_Red = 0,
Color_Green = 1,
Color_Blue = 2,... |
Is it a function?
Yes.
Arrays have a bit wonky syntax in the C syntax that C++ inherited. The square brackets go to the very end of the declaration. Here is a variable example:
element_type variable_name [array_size];
Pointers and references also have wonky syntax especially when combined with arrays. The following ... |
65,802,874 | 65,802,959 | Why doesn't my code accept whitespace in getline(cin, *userInput)? | I'm trying to take a user input, encode or decode using the rot13 method and then display the user input with the text encoded/decoded.
I am not sure what to try as the algorithm for encoding/decoding using the rot13 method was provided by my professor. I think it's something related to it but I'm not sure where to sta... | else if(input[index] <= 78 && input[index] <= 90)
input[index] = input[index] - 13;
The condition is malformed as it's supposed to be checking for character between 78 and 90.
else if(input[index] >= 78 && input[index] <= 90)
input[index] = input[index] - 13;
This will give the desired output.
Also, you don't... |
65,802,971 | 65,803,384 | C++ return string by value with move semantics | I am trying to understand how move semantics work in particular with the standard string. My primary concern is how to expose a string member variable of a class through a method, for example a getter.
So I made this example program.
#include <iostream>
#include <string>
using namespace std;
class Object {
strin... | Phil1970 answered this in a comment above.
Move semantics work with rvalues. The _s member variable is apparently an lvalue and that is why get1() results in a copy instead of a move.
|
65,802,990 | 65,803,356 | Convert std::function<void ()> to void (*)() | So I have a member function in C++ that takes in an std::function<void> and I want to pass this into a wiringPi function:
void my_class::on_change(std::function<void()> func) const
{
wiringPiISR(
wiring_pi_pin_number_,
INT_EDGE_BOTH,
func);
}
I am getting the error cannot convert ‘std::func... |
Convert std::function<void ()> to void (*)()
You cannot.
Should I be using void (*)() all the way up the stack?
Yes.
Technically using std::function could work but you'd have to rely on global state and the benefits of using std::function may not be worth that cost.
This seems like the wrong approch.
It's not, gi... |
65,803,002 | 65,803,440 | Why Does getline() Doesn't Read anything from a file? | I have made a code which accepts a txt file as input, and parse, and put them in 2d array myarray[][2].
Input file structure looks like this:
aaa/bbb
bbb/ccc
ccc/ddd
And it should be parsed like this:
myarray[0][0] = "aaa"
myarray[0][1] = "bbb"
myarray[1][0] = "bbb"
myarray[1][1] = "ccc"
The code which I made to do t... | Your file had a few issues, but the major one was: You forgot to bring your file reading pointer back to the beginning of the text document. The count function took the said pointer to the end, so you needed to bring it back.
So you need to use the seekg() function to drag the pointer wherever you wish to.
See if the c... |
65,803,083 | 65,803,264 | Is it possible to reuse a smart pointer's memory for another object? | Let's say I have two unrelated types that are exactly the same size.
struct Foo { ... };
struct Bar { ... };
And now, let's say that I have a tree of Foo that I would like to convert to a tree of Bar.
template <typename Leaf>
struct Tree
{
Leaf data;
std::unique_ptr<Tree> lhs;
std::unique_ptr<Tree> rhs;
};... | For raw pointers it isn't difficult. One simply needs to trigger destructor of Foo manually and apply constructor manually via placement new. The enable_if is SFINAE that ensures that sizes and alignment match.
#include <iostream>
#include <vector>
template<typename U, typename V, typename... Args,
std::enabl... |
65,803,655 | 65,862,293 | Paint arrow with QML | I can paint a line with QML in Qt C++. Please consider the below code:
var trackComponent = Qt.createComponent("track_MapPolyline.qml");
var trackObj = trackComponent.createObject(parent);
trackObj.path = [{1,1}, {2,2}]
and file track_MapPolyline.qml
import QtQuick 2.12
import QtLocation 5.12
MapPolyline
{
id: tr... | To draw an arrow I'd recommend to use plain Canvas component, because the Context2D API implements the same W3C Canvas 2D Context API standard with some enhanced features. It means that:
you'll be available to draw any other shapes and figures you need,
there will be a lot of documentation available,
there are lot of ... |
65,804,642 | 65,804,820 | How to tell if a #define has a value or not | As I understand with the C preprocessor you can use #define in one of two ways:
#define SOME_VAL 3.4159f
#define SOME_FLAG
I am writing a library and I am using #defines to for the user to parse in settings to do with compilation. My problem is I need to know which of the two aforementioned cases has been used.
Examp... |
do I have to specify in documentation which to use?
Technically no, you don't. But you should.
You can easily normalise on checking for false by doing this:
#ifndef DISABLE_FEATURE
#define DISABLE_FEATURE false
#endif
// later
#if DISABLE_FEATURE == false
...
Normalising on checking for definedness is a bit trickie... |
65,804,750 | 65,804,999 | Can b&&0 be optimized | I know that C/C++ uses the short-circuit evaluation to evaluate the expression of boolean. For example, C/C++ will definitely evaluate the operand a before the operand b in the expression a && b, if a is false, b won't be evaluated.
Besides, I know that things like 5==6 may be totally ignored by the compiler because it... | There are two independent problems involved in your question. The first is that when a compiler "sees" that the if condition is always false (due to && 0), it can completely throw away the corresponding branch. Example translation unit:
bool f(int);
int main()
{
if (f(1) && 0)
return 1;
}
With enabled optimizat... |
65,805,045 | 65,815,882 | Saving breakpoints after re-sourcing binary | I have a small work environment related doubt. I am analyzing a binary in LLDB and sometimes, I need to make some changes in the code and re-compile it. And then re-source the new binary into LLDB for further analysis.
Currently, I am doing this
Inside LLDB, use shell <shell-command> to compile the code.
Use file <bin... | Couple of things.
First off, if you are recompiling the binary at the same path you used for your current lldb target, then you don't need to make a new target. lldb will notice the file has changed when you do run read in the new binary & debug information, reset the breakpoints, etc.
But if there are other reasons w... |
65,806,108 | 65,806,232 | Specifying enum size in C++0x | I have a doubt regarding non-scoped enums behavior in C++03. I have read multiple questions and articles on Stack overflow and other pages.
I am using C++0x standard and running on GCC 4.6.4
I am able to define the non-scoped enum with a size(like int). refer godbolt
#include<iostream>
enum Enum: int;
enum Enum: int
{... |
Isn't specifying the size of enum is C++11 feature?
You seem to refer to specifying the underlying type. Yes, it was introduced in C++11.
So can we define or not the size of enum in C++03?
No, we cannot.
Is the code(pasted above)is a valid C++03 code?
No, it isn't.
I am using C++0x standard
C++0x was the name o... |
65,806,247 | 65,806,305 | What is the difference between "using namespace Bar" and "using Bar::Foo"? | I have the code:
#include <iostream>
class Foo {
};
namespace Bar {
struct Foo {
};
}
namespace Baz
{
void baz(const Foo &)
{
std::cout << "Hello";
}
}
int main()
{
Baz::baz(Bar::Foo());
}
Compiler can't figure out which Foo want to use and produces the error:
main.cpp: In functi... | cppreference is your friend.
As regards using namespace ns_name; it reads
using-directive: From the point of view of unqualified name lookup of any name after a using-directive and until the end of the scope in which it appears, every name from ns_name is visible as if it were declared in the nearest enclosing namespa... |
65,806,335 | 65,806,380 | Clion : Process finished with exit code 139 | I'm writing a program for collage exercise in C++ but I don't know why I see this error
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
it's just for testing the class and it's not complete
in main if I remove the add('a'); program run successfully but any function call will make this error !
th... | Tree *root;
void add(char c)
{
root->data = c;
}
int main()
{
cout<<2;
add('a'); // <---
return 0;
}
add('a') invokes undefined behavior by accessing an uninitialized pointer root in root->data = c;. You should initialize it first:
root = new Tree();
|
65,807,143 | 65,808,631 | How to invoke a process sleeping on poll function by another thread in the same process with signal without killing it? | I want to manually wake up (by another thread in the same process) a thread sleeping on poll() function waiting for any input data available. Looks like I found a possible solution by sending signals, but I don't have any experience with them really. On this page I found a signal called SIGPOLL with codes like POLL_IN,... | I used pipe() to solve this problem.
void a(int invokefd){
...
write(invokefd, "c", 1);
...
}
void b(int invokefd){
vector<pollfd> readfds;
...
pollfd invfd;
invfd.fd = invokefd;
invfd.events = POLLIN;
invfd.revents = 0;
readfds.push_back(invfd);
...
poll(&re... |
65,807,684 | 65,810,029 | Long values between 0xff800001 and 0xffb00000 reinterpret to float with error | I encountered a problem when converting binary values to float, prompting me to research the issue further. I found out that the values between 0xff800001 and 0xffb00000 when are reinterpreted as float have their 15th 22nd LSB bit flipped. The test program I used for this:
unsigned long long ca = 0;
unsigned long long ... | This is due to your C++ implementation silencing signaling NaNs.
Note that the difference is in bit 22, not bit 15 as stated in the question. For example, in the case where the before and after values are ff8003cf16 and ffc003cf16, log2(ff8003cf16−ffc003cf16) = 22.
When your C++ implementation assigns a float value to ... |
65,807,982 | 65,808,604 | Compiler error on templated ctor (is this a compiler bug?) | When I try to compile the code from this post (see below) in Visual Studio 2019, I receive the following compiler errors at line of the templated copy ctor:
Error C2439 'PreAllocator<_Newfirst>::memory_ptr': member could not be initialized
Error C2440 'initializing': cannot convert from 'T *const ' to 'T *'
Err... | template<typename U>
PreAllocator(const PreAllocator<U>& other) throw() : memory_ptr(other.memory_ptr), memory_size(other.memory_size) {};
This constructor attempts to initialize memory_ptr of type T* from other.memory_ptr of type U*, which is different from T* (because otherwise a copy constructor would have been cal... |
65,808,437 | 65,809,211 | Why do we use the Java virtual machine? | I am trying to wrap my head around the Java Virtual Machine and why it uses bytecode. I know it has been asked so many times, but somehow I couldn't finally make the correct assumption, so I researched many things and decided to explain how I think it works and if it's correct.
I understand that in C++, compiler compi... |
When Java compiler compiles the source code into bytecode, It doesn't do the compilation depending on architecture or operating system. The source code will always be compiled to the same bytecode if it's compiled on Windows or Mac.
All correct.
Let's say we compiled and now, send the bytecode to another computer (x... |
65,808,739 | 65,810,591 | Meson doesn't link shared library | My project has following structure:
$ find ~/template
template/
template/meson.build
template/src
template/src/template
template/src/template/geometry.cc
template/src/template/geometry.hh
template/src/template/main.cc
template/src/template/meson.build
template/src/meson.build
Relevant files:
$ cat ~/template/src/templ... | You're forgetting #include "geometry.hh" in your main.cc file. That's the reason it can't find the Circle class declaration.
|
65,808,945 | 65,809,081 | Unable to understand the syntax errors in c++ | I am trying to make a tic tac toe game in c++, but I am getting the following errors in my code(Not completed yet). am I passing the arrays to the function correctly
[Error] invalid conversion from 'char(*)[3]'to 'char'
and
[Error] initializing argument 1 of 'void player_input(char)'
#include <iostream>
using namespace... | void player_input(char);
Your function definition doesn't match the one below void player_input(char size[][3]). Before execution, the compiler tries to match each function call with its appropriate definition. It fails as it only sees the one above (which takes a single character), being matched with player_input(... |
65,808,971 | 65,809,025 | why t.join cannot be called twice in this example? | For some time I have been trying to use std::thread, and in my project i wanted to make sure that the threads are not making one thing couple times at once, that's why i am trying to make a simple project that has something like "check" if thread is done, and then start again
#include <future>
#include <thread>
#includ... | As you can see https://en.cppreference.com/w/cpp/thread/thread/join
join has as post condition
joinable() is false
and in error condition
invalid_argument if joinable() is false
So you cannot call it twice as you do.
You probably want to break the loop once you call join or rewrite your loop such as:
while (future.... |
65,809,344 | 67,583,620 | find overlap and downsample scatter plot | I have huge data that consist of points(x,y) and need to present in a scatter plot.
To find overlap and remove invisible differences between the same point, I wrote bellow code :
void DownSampler::makeDownSample(QVector<double> keys,QVector<double> values, QVector<int> pixmapIdx, QSize resolution, sViewSize view)
{
m_c... | the point cloud library and Grid Voxel in 2D aspects can process and downsample point clouds perfectly.
|
65,809,400 | 65,809,952 | Wrong output when creating a lower diagonal triangle | I am trying to create a program that takes lower diagonal values and than it stores in a 1-D array and then just print it .
Input:
1 0 0
2 3 0
4 5 6
expected output
1 0 0
2 3 0
4 5 6
current output
2 0 0
2 4 0
4 5 6
note I have given dimension to 3 already.
code:
#include <bits/stdc++.h>
using namespace std;
class matr... | Your formula to find a matrix element i,j in a flattened array representation (that you call a in your code) of said matrix, a[((i * (i - 1)) / 2) + (j - 1)] is only correct in case indices i,j start counting from 1, as in Fortran, and not from 0, as in C++.
Also, the size of lower triangular matrix should include the ... |
65,809,841 | 65,809,921 | Is there a way of getting absolute or non time dependent random numbers in Python or C++ | I want random numbers so that I can advertise my app as, "Not giving anyone a disadvantage, fundamentally", I am making game about Quantum Uncertainty which is random, not just pseudo random, so I could do:
import random
rnd = random.randint(a, b)
But that is pseudo random, not random, it uses the time to generate the... | Try using this module https://github.com/lmacken/quantumrandom
It gives you tools for interacting with The ANU Quantum Random Number Generator (qrng.anu.edu.au). So it makes your random absolutely random.
|
65,810,008 | 65,811,398 | May boost::asio::ip::udp::socket::send_to even fail? | Please consider following code snippet.
It first resolves address of remote host, then opens socket and sends some data to it. Note, it throws immediately when error occurs.
No concurrency involved. Message fits to 1K. Basically the only difference between this code snippet and "real" code is following: message may be ... | ASIO implements this in terms of underlying operating system calls. On POSIX, that would be sendto. The possible error conditions are documented (see below).
However, first things first:
You could receive a segfault for addressing out of bounds into unknown address space. Depending on your platform it might manifest a... |
65,810,026 | 65,811,372 | Trompeloeil MAKE_MOCK0 with a template as a return type | When using Trompeloeil to mock unit tests in C++, how can use an unordered_map as a return type?
// This example works fine
// return type is void, my_function takes no arguments
MAKE_MOCK0(my_function, void(), override);
// This is what I'm trying to do but fails
MAKE_MOCK0(my_function, std::unordered_map<std::stri... | Templated return types need to be wrapped in (...). This is explained in: Q. Why can't I mock a function that returns a template?
// Bad
MAKE_MOCK0(my_function, std::unordered_map<std::string, int>(), override);
// Good
MAKE_MOCK0(my_function, (std::unordered_map<std::string, int>()), override);
The C++ preprocessor ... |
65,810,203 | 65,811,708 | C++20-ranges: reuse of a filter view | I do not understand the result of the following code (C++20 compiled with g++-10):
#include <iostream>
#include <vector>
#include <algorithm>
#include <ranges>
int main() {
using namespace std;
auto v = vector<int>{0,1,2,3,4,5,6,7};
auto r = v | views::filter([](int n) {return n % 3 == 0;});
range... | You are violating [range.filter.iterator]/1:
Modification of the element a filter_view::iterator denotes is permitted, but results in undefined behavior if the resulting value does not satisfy the filter predicate.
Your predicate here is elements divisible by 3, and you're modifying all of those to be 2 - which do... |
65,810,417 | 65,810,864 | Problem with cross #include across header files with classes | Working on a simple game in c++ but I keep stumbling on a cross #include problem. Essentially the problem is like this:
I have a Chunk class that depends on Tile and Entity but Entity also depends on Chunk.
Entity.hpp
#include "Chunk.hpp"
class Entity {
public:
Chunk in_chunk;
};
Chunk.hpp
#include "Entit... |
So, is the only solution by pointing to the class or is there another way to get around this?
Forward declarations do not require usage of pointers. See fixed example on wandbox.
(Since C++17 std::vector actually can hold incomplete (forward declared) types).
Never the less, your example is "strange". Entity is an ow... |
65,810,548 | 65,814,264 | What's the purpose and meaning of this declaration | I have this code, I am looking at the code below, and I cannot figure out why on earth class Node; would be written and then again but with implementation.
class Doubly_Linked_List
{
class Node; // <--- Why is this declared here??
class Node : public Link {
// Some Node code goes here.
}
Lin... | Declarations like class Node; are forward declarations. They are sometimes useful if you want to do some basic operations with your class, which don't require a full declaration.
One example of such a basic operation is declaration of methods. Suppose you have a bunch of very important methods in your Doubly_Linked_Li... |
65,810,673 | 65,813,391 | Format a double without losing precision but with a minimum number of digits | In our C++ codebase, we have a default formatting method to convert double floating point numbers into strings, that is used notably for JSON serialization and for debug logs. For that default number formatting, I have the following contradictory requirements:
Favor human readability. Prefer 1000 to 1e3 or 0.125 to 1.... | After Frodyne comment, I was able to figure out a very simple and fast solution.
The C++17 std::to_chars function, by default, formats the floating point numbers to fulfill shortest round trip requirement. That mean that all distinct floating point numbers remain distinct after serialization, and the number of characte... |
65,810,718 | 65,810,832 | c++ forward variadac function arguments to a class constructor | In C++, is there a way to define a function that takes N number of random arguments (number and parameter types could be anything) and in that function, instantiates a class who's constructor expects those arguments. In pseudo-code, something like:
class ClassType {
ClassType(int, string){}
};
void func(Args ...) {... | Yes it is possible. Output of this
#include <iostream>
#include <utility>
struct ClassType {
ClassType(int a, std::string b){
std::cout << a << b;
}
};
template <typename...Args>
void func(Args&& ... args) {
ClassType A(std::forward<Args>(args)...);
}
int main() {
func(12,std::string("foo"));
}
i... |
65,810,752 | 65,816,756 | std::wcout printing unicode characters but they are hidden | So, the following code:
#include <iostream>
#include <string>
#include <io.h>
#include <fcntl.h>
#include <codecvt>
int main()
{
setlocale(LC_ALL, "");
std::wstring a;
std::wcout << L"Type a string: " << std::endl;
std::getline(std::wcin, a);
std::wcout << a << std::endl;
getchar();
}
When I ... | Windows requires some OS-specific calls to set up the console for Unicode:
#include <iostream>
#include <string>
#include <io.h>
#include <fcntl.h>
// From fctrl.h:
// #define _O_U16TEXT 0x20000 // file mode is UTF16 no BOM (translated)
// #define _O_WTEXT 0x10000 // file mode is UTF16 (translated)
int ma... |
65,811,315 | 65,811,409 | do efficiently floor function on all item's in std::vector | i want to floor all the items in a std::vector and use bellow code :
for(const float &number : numbers)
number = floor(number);
but I need to use a parallel algorithm for this operation.is there any parallel algorithm in standard c++ for do efficiently an action like floor function on all items?
| If you can use C++17, you can use the ExecutionPolicy argument from std::for_each to parallelize your loop
#include <algorithm>
#include <cmath>
#include <execution>
std::for_each(std::execution::par_unseq,
numbers.begin(),
numbers.end(),
[](double& number){ number = std::floo... |
65,811,336 | 65,811,749 | Pass any function by parameter | Explication
Hello,
I want to create a function that can execute any type of function, indicating at the end of its execution the time it took.
The called function can have a return value or not and 0 or more parameters of any type.
The calling function must print something like this:
Running "myFunction" .....
Done !... | I'm pretty sure there's no single answer to what's best - but this is a small improvement i.m.o. since it's a bit more generic.
#include <chrono>
#include <iostream>
#include <string>
#include <type_traits>
// enable it for invocables with any type of arguments
template <class Func, class... Args,
std::enabl... |
65,811,562 | 65,820,123 | ERROR Windows headers require the default packing option on winnt.h | I have an old C++ program I recovered to update and re-use it with Visual Studio 2019.
When I try to compile winnt.h, it gives the error:
Windows headers require the default packing option. Changing this can lead to memory corruption. This diagnosis can be disabled by building with WINDOWS_IGNORE_PACKING_MISMATCH defi... |
Check if #pragma pack is used in the code. If you use #pragma pack, do not set Struct Member Alignment in the project configuration, because it will disturb the direct alignment of other code.
Check whether your project platform settings are consistent with the property page settings.
|
65,811,591 | 65,881,357 | How can I get the raw binary content from an arbitrary typed QVariant into a QBytearray? | Problem
I have an interface which gives me a QVariant of an arbitrary type. I need to convert the data content in this variant to a raw binary QByteArray:
QVariant result = myQVariantReturningMethod(type arg, type arg2);
QByteArray rawResult = ?;
Background
The resulting QByteArray is sent over Canbus. Depending on it... | It turns out, that QVariant has an undocumented method constData() which gives exactly the result I want to have: A pointer to the internally stored data of the QVariant. Together with QMetaType::sizeOf(), this is exactly what is needed to write all the data into a QByteArray.
I found that method documented in the docu... |
65,811,703 | 65,811,825 | Compound assignment in C++ | I would like to know the execution flow of compound assignments in C++. I came across a CodeChef question, where I am calculating NCR mod p values and adding them together to get the final answer:
// correct
for(int i=min1; i<=max1; i+=2){
ans = (ans+ncr_mod_p(n,i))%mod;
}
// incorrect
for(int i=min1; i<=max1; i+... | This statement
ans+=ncr_mod_p(n,i)%mod;
is equivalent to the statement
ans = ans + ( ncr_mod_p(n,i)%mod );
As you can see it differs from the statement
ans = (ans+ncr_mod_p(n,i))%mod;
From the C++ 14 Standard (5.18 Assignment and compound assignment operators)
7 The behavior of an expression of the form E1 op = E2 ... |
65,811,716 | 65,811,783 | Most terse and reusable way of wrapping template or overloaded functions in function objects | Scenario 1: a template function pred
template<typename T>
bool pred(T t) { /* return a bool based on t */ }
Scenario 2: a set of functions overloaded on the same name pred
bool pred(A t) { /* return a bool based on t */ }
bool pred(B t) { /* return a bool based on t */ }
bool pred(C t) { /* return a bool based on t */... | You can create a macro like
#define FUNCTORIZE(func) [](auto&&... val) \
noexcept(noexcept(func(std::forward<decltype(val)>(val)...))) -> decltype(auto) \
{return func(std::forward<decltype(val)>(val)...);}
which will let you wrap any callable into a closure object. You would use it like
auto constexpr predObj = FUNC... |
65,811,832 | 65,837,840 | Simple std::any implementation based on function pointers | I've read answers to this question, peeked at gcc implementation for std::any, and didn't quite understand the implementation. However, I thought to try out the idea of using function pointers to deduce types.
In debug I get expected results, but in release my template specializations are optimized away... I've tried t... | You can work around this non-conformance by using a variable template (or a static local variable—in which case you call the function in the constructor—or a static data member of a class template):
template<class T>
constexpr decltype(nullptr) tag{};
class any {
void *p;
const decltype(nullptr) *t;
public:
tem... |
65,811,986 | 65,812,083 | Make a loop run in background C++ | I am trying to make a loop to check for a debugger every 3 seconds or so and I know I need multithreading but I need an example or something since I'm really new to C++
I can't just loop it normally because then the rest of my code wont run.
void loop() {
for (;;) {
if (IsDebuggerPresent())
{
... |
the rest of my code wont run.
See below.
int main()
{
std::thread t1(loop); // activates loop
// PUT YOUR CODE HERE.
if (t1.joinable()) { // shuts down loop
t1.join(); // join OR detach. Not both.
}
}
|
65,812,046 | 65,812,626 | Disambiguate non-const and const access methods (Pybind11) | I am trying to wrap some C++ class using Pybind11.
The class (Alpha) two getters, one returning a const reference to a member force_ the other one returning a non-const reference.
struct Dummy {
double x{3.3};
};
class Alpha {
const Dummy& force() const {return force_;}
Dummy& force() {return force_;}
private:... | I don't know pybind, but I suppose Func is the type that def tries to deduce from its second parameter. The issue is that you cannot get a function pointer to an overload set. You can only get a function pointer to a single function.
The documentation states that Func can be a plain C++ function, a function pointer, o... |
65,812,523 | 65,816,979 | Unforgettable Factory: Doesn't work with default constructible objects | I am referring to this excellent blog post regarding the "Unforgettable Factory Registration Pattern": http://www.nirfriedman.com/2018/04/29/unforgettable-factory/
I've noticed that this stops working when the self-registering types are default constructible. In the example provided by the code, the self-registering ty... | The int argument is a red herring. When changing the argument list you modified
Dog(int x) : m_x(x) {}
to be
Dog() = default;
From a user-provided constructor, to a defaulted one.
In effect, this means the compiler (I checked Clang and GCC) doesn't emit a function definition for Dog::Dog(), so it doesn't odr-use Anim... |
65,812,603 | 65,812,739 | I want to create a C++ program to generate random numbers into a file | I'm making a C++ program to generate a million random numbers (I've generated them as just cout output once so I have the processing power) and I want to write them into a file.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <fstream>
using namespace std;
int main() {
srand(t... | Don't reopen the same file:
...
ofstream file ("numbers.txt");
file.open ("numbers.txt", ios::out | ios::app ); // Remove this line
int i = 0;
...
That will make it work. However, the program won't ever stop, since you forgot to increment i too!
|
65,812,651 | 65,822,764 | Displaying temp reading on an Arduino with more than 1 decimal digit | I have a code sample which helps me to display temperature:
#include <OneWire.h>
#include <DallasTemperature.h>
#include <OLED_I2C.h>
#define ONE_WIRE_BUS 10
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
OLED myOLED(8, 9, 8); // 8pin - SDA , 9pin - SCL
extern uint8_t RusFont[];
extern uint8_t M... | Try changing the , 1 to a , 2.
This will tell the Arduino that you want to print it with a two decimal place.
eg:
myOLED.print(String(sensors.getTempCByIndex(0), 2), CENTER, 9);
|
65,813,516 | 65,813,920 | Undefined reference using namespace C++ | When I want to run the code the compiler says undefined reference to math::calc
I read questions and answers about this problem at StackOverflow and it do not help me solve my problem.
Comp.h
#include <utility>
namespace math {
typedef std::pair<double,double> Comp;
double getFirst(Comp a);
...
}
Comp.cpp... | You have to compile all your project's *.cpp files and then link them (results of compilation) properly - the linking process depends on the environment/IDE you're using, just look it up. If you're not linking it properly the final executable wont have all the functions definitions that requires, hence getting undefine... |
65,813,523 | 65,813,716 | Why is extern required for const int but not for const char* | I'm confused about why I need extern or not for int vs char* in the definition in my extern.cpp file. I have the following test program:
// extern.cpp
extern const int my_int = 1;
const char* my_str = "FOO";
// main.cpp
#include <iostream>
extern const int my_int;
extern const char* my_str;
int main() {
std::cout ... | This is caused by different linkage of my_int and my_str variables.
my_int is a const-qualified variable in namespace scope, which means it has internal linkage by default. In other words, its visibility is limited to the current translation unit, unless you mark it extern. Additionally, internal linkage constants must... |
65,813,915 | 65,814,155 | Why does std::reverse used in consteval function does compile though not constexpr | Using this little code snippet on CompilerExplorer with std=c++20 for x86-64 clang 11.0.0 compiles and runs.
#include <algorithm>
#include <array>
consteval std::array<double,2> gof()
{
std::array<double,2> x{ 3., 2.};
std::reverse(begin(x),end(x));
return x;
}
int
main(int argc, char *argv[])
{
retur... | std::reverse is constexpr in C++20 (the question title suggests otherwise?), so nothing in gof() prevents it from being a valid constant expression.
libstdc++ implements that constexpr change, while libc++ does not yet. So if you use libstdc++ (as clang does by default on Compiler Explorer), it'll work fine. But if you... |
65,814,996 | 65,815,353 | Array sorting even and odd accepting n values, with functions | i am practicing C++ as a beginner and i cant seem to get this program to work, the aim is to display even and odd numbers after accepting the values from the user.. and it has counter to display the amount of even and odd values in the end.
but it just displays the Even values on both the even and odd arrays.
#include ... | int num[n],even[EC],odd[OC]; are variable-length arrays and not allowed in standard C++. n is uninitialized. You can't first use n and then initialize it. The arrays even and odd can hold 0 items. Arrays don't grow.
You need std::vector, dynamic memory allocation or arrays that can hold enough items.
Here is a solution... |
65,815,332 | 65,817,254 | Flipping a surface vertically in SDL2 | The closest i've gotten is this:
void Engine::flipSurfaceVertically(SDL_Surface* surface)
{
SDL_LockSurface(surface);
Uint8* pixels = reinterpret_cast<Uint8*>(surface->pixels);
for (int k = 0; k < sizeof(Uint32); ++k)
{
for (int i = 0; i < surface->w; ++i)
{
for (int j = 0; ... | I don't know where is the error exactly, I tried your code on my machine and it works well on the image I used. I suspect that your code indeed preserves transparency, but it is removed later in your implementation.
Anyway, if I may suggest an improvement for your code: you don't need such complicated operations to ver... |
65,815,956 | 65,815,981 | Necessity of filter in GNU makefile | I have the following directory structure.
/home/user/
├── Makefile
│
├── easy/
│ └── a.cpp
├── medium/
│ └── b.cpp
└── build/
My goal is to compile all .cpp files in easy and medium and create separate executables in build. The Makefile ... | patsubst doesn't delete the words that don't match the pattern.
$(patsubst easy/%.cpp,build/%.out,easy/a.cpp medium/b.cpp) is not build/a.out, it's build/a.out medium/b.cpp
|
65,816,180 | 65,816,455 | How to measure code coverage of the part of execution in C++ | I have two C++ binaries (A and B) with socket connections between two binaries.
Binary A is listening for B. And, B connects to the A.
A accepts B's message and executes some functions depending on message contents.
We created a kind of unit-test to test various message types.
From these tests, I would like to measure... | Call __gcov_reset before your testcases to discard the data collected from initialization.
|
65,816,297 | 65,816,540 | system("PAUSE") or keep_window_open()? | I'm reading through Programming Principles and Practice 2ed. and in the Hello World program, they use a line, keep_window_open().
Before finding this book, I learned the same Hello World program, but instead using system("PAUSE").
My questions are as follows:
Are keep_window_open() and system("PAUSE") effectively the ... |
Are keep_window_open() and system("PAUSE") effectively the same thing, or are they different?
They have an equivalent use-case (block the calling process until user input is entered), but they approach it in different ways.
system("PAUSE") spawns a separate process to run the OS's command-line processor and have it e... |
65,816,395 | 65,994,686 | Unable to connect using QML Remote Object with Error: "connectionToSource is null" | I am trying to use Qt Remote Objects for creating client server application.
But encountered an issue that says "connectionToSource is null". How do I set the source connection ?
I am creating the server using the .rep file. The code I had used is as follows:
Data Model
// Rep File (DataModel.rep)
class DataModel {
... | I was able to find the problem. In the Server Code main function, the while loop is used which never exits because of which the "exec()" function was never called and Qt event loop never started because of which the Qt Remote object didn't share data. So I changed the following code using the Signal and Slot mechanism ... |
65,816,670 | 65,907,394 | File modification time gets overwritten by background cache flushing | I have code that performs following steps:
open file
write data
set file timestamps (via SetFileInformationByHandle(FileBasicInfo))
close file
When file is stored on certain NAS devices (and accessed via share) it's modification time ends up being set to current time.
According to Process Monitor Close() in step 4 re... | You can't really do anything -- I guess Isilon's SMB implementation doesn't support certain things (that would've preserved timestamps).
I simply added FlushFileBuffers() before SetFileInformationByHandle() and made sure there are no related race conditions in my code.
|
65,816,891 | 65,819,167 | Polymorphism and reference class member - wrong virtual method called | I was trying to understand how to apply polymorphism in C++ by creating a base class Document from which the two classes Book and Newspaper are derived. Note how the virtual method get_content() is overridden inside the derived classes.
class Document {
public:
virtual std::string get_content() const { return ""; }
}... | Printer p1(Book{});
Printer p2(Newspaper{});
Here, you are using temporary objects. These objects are destroyed at the end of the statement they are created in.
So, you have dangling references. Calling methods on a dangling reference is undefined behaviour.
In C++, you are in charge of object lifetime.
(Reference li... |
65,817,897 | 65,817,976 | Why "if (unsigned int == string::npos )" CAN be true? | Let me start by saying: I'm sorry if this was explained, I tried reading about it and searching for answer but I didn't find one that answered this specific question.
So I'm writing beginner's level code in C++ and I wrote a very simple function that returns index of the next found character that isn't space. It was in... | string::npos is a large positive number .
To avoid these issues, your function's return type should match the type of the value you are returning, e.g.:
return string::size_type instead of int, or:
return some other failure sentinel such as -1 in the first code.
The way you have it now, there can always be a clash wh... |
65,818,009 | 66,069,160 | Intermittent "file not found" errors when compiling c++ under multipass Ubuntu 20.10 | I am trying to use multipass to spawn a build environment, the source code being on the host machine. The idea is that I would mount the source code from the host into the VM and then run the build from inside the VM. (multipass mount src ubuntu:/home/ubuntu/src).
What I am trying to build is a relatively large c++ pr... | I ended up opening a PR to the multipass team. After some debugging, we uncovered two problems:
macOS Catalina has a default maxfiles limit of 256, which can be hit when compiling large projects.
There is a limit in libssh, which is used by multipass to do the mounts.
To workaround this, you need to:
Increase the ma... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.