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 |
|---|---|---|---|---|
74,012,082 | 74,012,573 | Can you help me debug this c++ program which is supposed to add a node at the end in circular single linked list and print the list? | Can you help me debug this c++ program which is supposed to add a node at the end in circular single linked list and print the list?
using namespace std;
class Node
{
public:
int data;
Node* next;
Node(int x)
{
data = x;
next = NULL;
}
};
class Lfun
{
public:
virtual void add... | Your main problem is this line in List:
tmp->next = head;
With that line, you ensure that the last Node's next will never be NULL, but point back at head, giving you a circular list.
In your while-loop you loop until you find a next member that is NULL, but due to the above problem, this will loop forever.
Your displ... |
74,012,130 | 74,020,777 | Why does std::vector copy-construct instead of move-construct when the destructor may throw? | Consider the following program:
#include <vector>
#include <iostream>
class A {
int x;
public:
A(int n) noexcept : x(n) { std::cout << "ctor with value\n"; }
A(const A& other) noexcept : x(other.x) { std::cout << "copy ctor\n"; }
A(A&& other) noexcept : x(other.x) { std::cout << "mo... | tl;dr: Because std::vector prefers to offer you a "strong exception guarantee".
(Thanks goes to Jonathan Wakely, @davidbak, @Caleth for links & explanations)
Suppose std::vector were to use move construction in your case; and suppose that an exception were to be thrown during vector-resizing, by one of the A::~A calls... |
74,012,149 | 74,012,265 | Why Do We Need asio::co_spawn? | Usually when working with coroutines, I can think of the way they execute by dividing the coroutine to the part before the first co_await and the part that comes after it.
The part before can usually execute directly on the stack of the calling thread whereas the part after it is scheduled for execution by some executo... |
I can simply call it directly from a regular function (in a 'detached' manner)
Yes, but if you don't provide an executor, it never continues.
asio::co_spawn is a simple way of tying an awaitable to an executor, and simple is what you want in an example.
|
74,013,707 | 74,030,966 | Namespace resolution inside preprocessor | I have a .h header shared among a C executable and a large C++ codebase.
#ifdef __cplusplus
namespace my {
#endif
typedef int my_t;
#define MY_OH_MY sizeof(my_t)
typedef my_t alias_t;
// plenty of other typedefs which push me to keep only
// these two bracing #ifdef __cplusplus ...
#ifdef __cplusplus
} // namespac... | You cannot use namespaces (as it is not a feature of C language) in C identifiers that must be accessed from C. Indeed, you must declare those specially in order for the compiler not to mangle the names. You can only use them in C++, but be carefull as to share code with C, you must inform the C++ compiler which rou... |
74,013,824 | 74,024,421 | BCG Virtual Grid how to display from a specific row | I have a CBCGPGridCtrl with virtual rows enabled (EnableVirtualMode).
No problem with data display.
On some event (right click from another window) I want to move the current visible part of the grid to a specific row.
I couldn't find any specific method to do that.
I tried a couple of different options:
1.
I saw that ... | After a day of different attempts, the only solution I was able to get to work is to have a child of CBCGPGridCtrl and intervene explicitly on the value of m_nVertScrollOffset.
So, it was something like this:
class CChildGrid : public CBCGPGridCtrl
{
public:
void SetScrollPos(int gotoPosition)
{
m_nVert... |
74,014,063 | 74,014,254 | How do I copy a class with a std::vector as a member variable? | I have made a simple Matrix class with a std::vector as the underlying container.
My problem is when i use the copy constructor on the Matrix class, the std::vector does not get copied.
My matrix.h:
#ifndef MATRIX_H
#define MATRIX_H
#include <vector>
#include <iostream>
template <typename T>
class Matrix
{
private:
... | After this constructor has been used
Matrix(int rows, int cols) : m_rows{rows}, m_cols{cols} {
m_vector.reserve(rows * cols);
}
there are exactly zero elements in the vector and trying to access elements in the vector will have undefined behavior. The proper constructor should actually create the elements instead:... |
74,014,725 | 74,045,171 | How to get unique sequence of types c++: (A, B, A, B, C) =>(A, B, C) | I need to exclude double instantiation, therefore I need to exclude the same types from the sequence of types.
#define ENTITY_SEQ (A)(B)(C)(A)(C)
||
\/
#define UNIQUE_ENTITY_SEQ (A)(B)(C)
I want to process it using a boost preprocessor. Is it possible to do that?
| There is, to my knowledge, no way to check the equality of two unknown identifiers.
But, if you know the list of identifiers ahead of time, then it is certainly is possible.
I had some time to implement the trivial O(n^2) algorithm today, although you could probably do better. I hope the order isn't important to you, b... |
74,015,245 | 74,015,413 | Boost async_read reads zero bytes from pipe | I'm trying to asynchrosouly read from a pipe using boost::asio::async_read, but it reads zero bytes everytime.
However, I can succussfuly read from the pipe using the read function(unistd.h);
here's my code:
auto io = make_shared<boost::asio::io_service>();
auto work = make_shared<boost::asio::io_service::work>... | Given a
std::string message;
then asio::buffer(message) has size 0 (because the string is empty).
The overload taking a size asio::buffer(message, 5) can only limit the size, but doesn't provide it. So it is still size 0.
This explains your symptoms. Instead,
std::string message(5, '\0');
auto b = asio::buffer(message... |
74,015,435 | 74,016,157 | How do I sort students ID, name, and marks of students while using for bubble sorting? | I got these going which only sort the student's mark on an ascending order, but I can't sort the name and the ID of the students by their marks.
#include <iostream>
using namespace std;
int main()
{
int total;
cin >> total; // How much data you want to input
string ID[100];
string name[100];
int g... | As mentioned by my comment, another alternative is to not sort the arrays themselves, but to sort an index array.
This allows you to keep the arrays separate, and without having to write n sets of "swap code" if you have n arrays to handle.
Below is mostly your code, but with what has been mentioned being applied:
#inc... |
74,016,474 | 74,016,955 | Allocator object type conversion | Is there a way, having one allocator object for type T, to use the SAME object to allocate memory for any other type. Maybe some magic with static_cast or rebind can help? Because right now I only have an idea of how to use rebind to derive the allocator type for the desired object type from the original allocator, but... | An allocator a of type A for value type T conforming to the standard requirements can be rebound to an allocator for type U via e.g.
std::allocator_traits<A>::rebind_alloc<U> b(a);
(although an allocator may support only a subset of all possible types U and fail to instantiate with others)
Then b can be used to alloca... |
74,016,909 | 74,021,667 | How do I make swig aware of c++ namespaces? | Hi I am trying to create a python binding for a little stack machine I wrote and chose to try swig for it.
The problem is that the generated code wont compile because some classes are unknown. The reasons for that is, that my classes are all inside a namespace.
The class I want to create a wrapper for looks like this:
... | Any class/function/global in the public interface may need a %include to generated wrapper code. SWIG does not recursively include without -includeall but that's not desirable as that would try to wrap system headers.
Order matters as well. SWIG needs to generate wrapper code for instruction before stack_machine sinc... |
74,017,073 | 74,017,291 | Following error when trying to use std::sort: In template: called object type 'bool' is not a function or function pointer | I want to reverse sort a custom container with custom objects, so when sorting this way:
(this is part of the .cpp)
bool PictureContainer::isGreater(const Picture& i, const Picture& j) {
return (i.getId() > j.getId());
}
void PictureContainer::sortRev() {
sort(picture, picture + tam, isGreater());
//< If I t... | It's impossible to use a non-static member function directly as the comparator for std::sort(). There are a few options:
Mark PictureContainer::isGreater as static, and pass PictureContainer::isGreater to std::sort().
Since the implementation of isGreater does not access anything that's only available from the Pictur... |
74,017,637 | 74,017,799 | Multithreading with function in other class | I'm new to c++ so sorry if obvious answer. I'm trying to get a thread to run a function from another class with an argument.
Here's how my code is laid out:
int main(){
Engine engine;
Sounds sounds;
std::thread t(&Sounds::ManageSounds, &sounds, &engine)
/*some stuff*/
t.join();
}
class Sou... | Your thread method ManageSounds requires an Engine parameter by value, and you pass it a pointer to Engine (&engine).
To fix it you should do one of the following:
Pass the engine object iteslf (if it is copyable, and it makes sense in your case).
If you actually need pointer/reference semantics (which is quite reason... |
74,017,739 | 74,018,212 | C++20 concepts as Interfaces | Hey I'm trying to design some Interfaces without any runtime overhead using c++20 concepts.
I came up with the following (simplified) concept
/**
* @brief This concept defines an OSA Interface
*/
template<typename T, typename Task_T>
concept OSA_Layer_T = requires (T a) {
{T::getName(a)} -> std::same_as<std::strin... |
Since every OS has it's own internal Task Handle Type (and I do not want to use void*) I need to pass the actual Task Handle as a template parameter to my concept
The second part of this doesn't actually follow from the first. If every OS has its own internal task handle type, the approach should be to have that be p... |
74,017,772 | 74,017,980 | CMake Linking library with full path and with target_include_directories | I came to a problem that I do not understand why this works in such a ways.
I am linking static libraries, specially libgmp-10 and libmpfr-4. These are static libraries from CGAL.
This does not work:
list(APPEND petras_include_paths
#cgal
"${CMAKE_BINARY_DIR}/install/cgal/include"
"${CMAKE_BINARY_DIR}/install... | target_include_directories adds #include directories, not library search paths. target_link_directories adds link directories.
Before proceeding, you might want to read https://doc.cgal.org/latest/Manual/devman_create_and_use_a_cmakelist.html
|
74,017,783 | 74,017,880 | Defining method with additional template parameters out of line | Given a templated class, how do I define a (further templated) method out of line? The syntax
template<class T> class C {
public:
template<class S> void f();
};
template<class S, class T> void C<T>::f<S>(){}
or any variant I have tried does not do the job:
error: use 'template' keyword to treat 'f' as a depen... | You need to write two template headers:
template<class T>
template<class S>
void C<T>::f(){}
|
74,017,855 | 74,019,447 | My code for computing large sums fails this very specific test case and I'm not sure why | The point of this exercise was to create code that can compute very large sums by using an algorithm close to how you would do it by hand. My code seems to work just fine, except for one specific test case, which is 9223372036854775808 + 486127654835486515383218192. I'm not sure what is special about this specific test... | After a lot of experimentation, what made the difference for me was replacing n1 and n2 entirely with strA.length() and strB.length() respectively in the for loop declarations. I'm not entirely sure why this happens, so if anyone has an explanation- please forward it.
Anyway, here's my version of the code:
//Basic mech... |
74,018,366 | 74,019,249 | I used an object in my main file (?) despite having transferred ownership before? | I used move semantics a la
class MyC {
public:
Eigen::MatrixXd f_bar_mat;
MyC::MyC(Eigen::MatrixXd f_bar_mat):f_bar_mat(std::move(f_bar_mat))
}
In the main I have:
Eigen::MatrixXd f_bar_mat = Eigen::MatrixXd::Random(10000,200);
MyC MyInst(f_bar_mat);
MyC MyNewInst(MyInst.f_bar_mat); //tra... | You are not moving main's f_bar_mat anywhere. Nowhere did you call std::move(f_bar_mat) in main.
You are moving only the parameter of the constructor which is also called f_bar_mat but is not the same object as the one in main (since it was not declared as a reference).
Since you are passing f_bar_mat from main as a lv... |
74,018,367 | 74,068,988 | C++ SFML texture wont load from class | I am working on a simple little game in c++ (SFML).
It involves the need to create objects of the Ghost class and store them in an array, each ghost must also be assigned a texture based one their type, something I have as input to the class init function. Overall my class looks like this:
class Ghost{
public:
... | Textures dont mix well with arrays/vectors. The copy operator needs to specified as the default one is not enough to maintain the same functionality in arrays/vectors. Pointers/dynamic textures or a different method needs to be implemented for this to work. I suggest doing the latter and instead of sending a number as ... |
74,019,463 | 74,019,727 | Is it possible to have a variadic argument list for a template or automatically generated specifications based on supplied argument list | Let's say I have the following tuple:
std::tuple<int, int, int> setVals(int val)
{
return std::make_tuple(val, val, val);
}
It is really nice to have structured bindings with this: auto [x, y, z] = setVals(42);
Would it be possible to have some kind of variadic signature for setVals, so I could do structured bindin... | You can create a function like what you want but you have to specify the number of elements the tuple will have as a template parameter. That would give you code like:
// does the actual creation
template <typename T, std::size_t... Is>
auto create_tuple_helper(const T& initial_value, std::index_sequence<Is...>)
{
... |
74,019,895 | 74,025,501 | Valgrind - many allocated bytes | Installed valgrind on my WSL and I was a bit confused.
Problem: I get a lot of allocated bytes even though my program doesn't do anything.
main.cpp:
#include <iostream>
using namespace std;
int main() {
cout << "I'm testing valgrind!" << endl;
return 0;
}
The result of calling valgrind:
==435== Memcheck, ... | If you are curious and want to see what these allocations are, run with
--run-libc-freeres=no --run-cxx-freeres=no -s --leak-check=full --show-reachable=yes
As said in the comments, don't worry about this. All that matters are the errors.
|
74,020,792 | 74,020,924 | Why does c++(and most other languages) have both 'for' and 'while' loops?/What can you do with one type that you can't with the other? | Why do most programming languages have two or more types of loops with almost no difference? In c++, is one of the two better for specific tasks? What about switches and if's; is there any difference there?
If not, then an answer about why they were implemented would be appreciated.
| There is nothing that you can do with one type that you can't do with the other, because mechanical transformations exist between them:
while (X) { body; }
can be written as
for (;X;) { body; }
and
for (A;B;C) { body; }
can be written as
{ A; while (B) { body; C; } }
The only difference is readability. The for loo... |
74,020,875 | 74,021,128 | Converting floating point value to string using gcvt(), but when there are no decimals the whole number printed out ends in a dot | Just hopefully a simple question about the gcvt() function.
Printing out buffer as a result of gcvt(32.000,10,buffer), results in "32."
Any way I can get rid of that annoying dot after the 32?
| I don't think you can get gcvt to not do that - you can remove it afterward with
if ((p=strchr(buffer,'.'))
*p='\0';
|
74,020,898 | 74,020,934 | Is it possible to "overload" an alias template depending on a constraint? | Can we have an alias template that points to a type if a constraint is false, or to another type if that constraint is true ?
template < class T >
using MyType = SomeType;
template < class T >
requires SomeConstraint
using MyType = SomeOtherType;
I know doing it this way doesn't compile but is there a workaround ? ... | Yes, either by moving the alias into a class and partially specializing the class (and then aliasing the alias in the class from the outside), or for the case you are showing simpler:
template<typename T>
using MyType = std::conditional_t<requires{ requires SomeConstraint; },
SomeOthe... |
74,021,054 | 74,021,112 | Converting json file to json object jumbles up the order of objects | I am trying to parse a json file into a json object using nlohmann json library.
This is the json file:
{
"n":1,
"data":
{
"name":"Chrome",
"description":"Browse the internet.",
"isEnabled":true
}
}
This is my code:
#include <nlohmann/json.hpp>
#include <iostream>
#include <fstr... | JSON is normally not ordered, but the library provides nlohmann::ordered_json that keeps the insertion order:
auto data = nlohmann::ordered_json::parse(f);
Parsing the file like above and printing it like you do produces this output:
{"n":1,"data":{"name":"Chrome","description":"Browse the internet.","isEnabled":true}... |
74,021,121 | 74,021,223 | Namespaces and C++ library | Is a namespace contained in a library or a library is contained in a namespace?
How many namespaces are there in the C++ standard library ?
| They are orthogonal. A library can use multiple namespaces and a namespace can be split between multiple libraries. However it is a good practice to scope the contents of a library to a (usually single) namespace (+ namespaces nested therein) specific to that library to avoid name clash between multiple libraries and f... |
74,021,902 | 74,022,136 | CMake: add a directory prefix to `target_include_directories(...)` file #includes | I am using the Crypto++ library in my C++ project, and have installed it with the following (minimised) CMake code:
cmake_minimum_required(VERSION 3.24)
project(CMakeAddLibraryPrefixIncludes)
set(CMAKE_CXX_STANDARD 23)
include(FetchContent)
FetchContent_Declare(CryptoPP
GIT_REPOSITORY https://github.com/weida... | You can specify the folder for downloading sources by providing SOURCE_DIR to FetchContent_Declare. You can then use the parent folder of cryptopp_SOURCE_DIR as your include path.
FetchContent_Declare(CryptoPP
SOURCE_DIR ${FETCHCONTENT_BASE_DIR}/cryptopp-src/cryptopp
GIT_REPOSITORY https://github.com/we... |
74,022,244 | 74,022,512 | Regex match all except first instance | I am struggling to find a working regex pattern to match all instances of a string except the first.
I am using std::regex_replace to add a new line before each instance of a substring with a new line. however none of the googling I have found so far has produced a working regex pattern for this.
outputString = std::re... | In this case, I'd advise being the anti-Nike: "Just don't do it!"
The pattern you're searching for is trivial. So is the replacement. There's simply no need to use a regex at all. Under the circumstances, I'd just use std::string::find in a loop, skipping replacement of the first instance you find.
std::string s = "a =... |
74,022,353 | 74,026,871 | Move mainwindow while clicking on button | I have subclassed a button and I'm trying to move her parent window around while this button is being hold down.
I'm having difficulty in how to proper calculate the new window position in this line:
MoveWindow(hWnd, pt.x, pt.y, width, height, TRUE);
// hWnd represent the button parent window.
switch (message)
{
case... | Your calculation seems incorrect to me. When you down the mouse button, you should calculate the difference between the desktop mouse position and the location of the parent window and when you move the mouse, you can add the difference to the desktop mouse position back.
POINT g_deltaXY;
switch (message)
{
case WM_L... |
74,023,284 | 74,023,407 | PyInit already defined - PyBind | I want to build a module for python, and it compiled fine when I had 1 header, 1 cpp file, but I wanted to extend it to 1 header, 2 cpp files, and now I get errors I don't really understand.
My Header (fast_qs_module.h):
#ifndef FASTCOSINE_MODULE_INCLUDE_H
#define FASTCOSINE_MODULE_INCLUDE_H
#include <pybind11/pybind1... | Include guard only protects a header to be included more than once in a single translation unit. It does not help if a header contains something that needs not be placed in the header.
In your case, it looks like PYBIND11_MODULE expands to something like a definition rather than a declaration, which should not be in a ... |
74,023,308 | 74,062,004 | Debugging (breakpoints / etc) in VSCode with different makefiles for parts of the codebase | I'm working on an ESP-IDF based project that runs on ESP32 microcontrollers.
The project has a bunch of different C++ libraries (ESP-IDF calls them components) I've written. Normally I compile the whole project and it gets installed on the ESP32, and everything works great.
I've been writing tests, and how I make the t... | I was able to work this out. Here's what I did...
Firstly, I ran my tests. Now when I look in unit_tests/build/ I see sub
folders for each make file. And in those subfolders there are executables. For instance, unit_tests/build/data/data_tests
I made a .vscode/launch.json file in my repo. It's looks like this...
{
//... |
74,023,865 | 74,023,934 | Run-time vs link-time linking of dynamic libraries | tl;dr
When the main application makes use of a dynamic library via dlopen and dlsym, does it need to be linked against it in any way?
Say I have a library like this,
header
#pragma once
void foo();
implementation
#include "MyLib.hpp"
#include <iostream>
void foo() {
std::cout << "Hello world, dynamic library spea... | If you use dlopen and dlsym you don't need the header file or the foo function prototype. You don't need it because the name in the library will not be plain foo.
The C++ compiler uses name mangling to be able to handle things like function overloads, and it's the mangled name you need to pass to dlsym to get a pointer... |
74,023,996 | 74,038,567 | OpenMP atomic on return values | I have some trouble understanding the definition of scalar expression in OpenMP.
In particular, I thought that calling a function and using its return value in an atomic expression is not allowed.
Looking at Compiler Explorer asm code, it seems to me as it is atomic, though.
Maybe someone can clarify this.
#include <cm... | @paleonix comment is a good answer, so I'm expanding it a little here.
The important point is that the atomicity is an issue only for the read/modify/write operation expressed by the += operator.
How you generate the value to be added is irrelevant, and what happens during generating that value is unaffected by the ato... |
74,024,032 | 74,029,906 | emscripten -O3 optimization gives "Import #0 module="a" error" when instantiated | When I am using -O2 or -O1 optimization with em++ I have no problems, but when I am using -O3 as follows:
em++ -s WASM=1 -O3 .\testFunct.c++
I got the following error when I use "instantiateStreaming" in the Javascript.
App.js:95 Uncaught (in promise) TypeError: WebAssembly.instantiate():
Import #0 module="a" error:... | The module is looking for an module called "a".. so in your example "a" would live alongside "env" and not within it. However, the problem here is that emscripten is performing minifcation of the strings at -O3 which makes writing the loading code by hand tricky.
Are you using the emscripten-generated JS code for load... |
74,024,368 | 74,024,419 | GCC compiles use of noexcept operator but clang and msvc rejects it | While writing code involving noexcept I made a typo and was surprised to see that the program compiled in gcc but not in clang and msvc. Demo
struct C
{
void func() noexcept
{
}
void f() noexcept(noexcept(C::func)) //gcc compiles this but clang and msvc rejects this
{
}
};
So my question is wh... | The program is ill-formed and gcc is wrong in accepting the code because we cannot name a non-static member function in an unevaluated-context like decltype or sizeof or noexcept operator.
This can be seen from expr.prim.id:
An id-expression that denotes a non-static data member or `non-static member function of a cla... |
74,024,532 | 74,024,826 | Is it possible to deduce the value type of a range from the range argument? | If you look at standard algorithms like std::ranges::fill and std::ranges::generate, they both seem to use additional parameters to deduce the range value type for their output ranges. E.g. ranges::fill(v, 10) is able to deduce the value type T because of its second argument.
However, when you try to define a similar f... | It sounds like you want:
template <typename T> requires std::output_range<T, std::ranges::range_value_t<T>>
Or, perhaps:
template <typename T> requires std::output_range<T, const std::ranges::range_value_t<T> &>
The former expects the element to be moved, and latter expects it to be copied. If you want to support bot... |
74,025,489 | 74,025,536 | Template Argument Deduction with different typename | I have defined a generic function like this:
template <typename T1, typename T2>
T2 Calculation(T1 arg_one, T1 arg_two)
{
return arg_one + arg_two * 3.14;
}
When I try to use this generic function as follow:
auto sum = Calculation(2, 3.2);
Compiler told me: no matching overloaded function found. However, when I t... | The problem is that T2 cannot be deduced from any of the function parameters and T2 also doesn't have any default argument, and template parameters can't be deduced from return type.
To solve this either you can either explicitly specify the template argument for T2 when calling the function or change T1 arg_two to T2... |
74,025,596 | 74,055,490 | Boost.Locale translation - Preventing user modifications to dictionaries / embed dictionaries in executable | I use Boost.Locale with ICU backend (internally using GNU gettext) to do the translations. This translation uses dictionaries stored on disk. Search paths are provided through boost's generator class like so:
boost::locale:generator gen;
gen.add_messages_path("path");
By inspecting the boost's source code, this intern... | You can use the callback field on gnu_gettext::messages_info to provide a function that will be called instead of loading messages files from disk. From Custom Filesystem Support:
namespace blg = boost::locale::gnu_gettext;
blg::messages_info info;
info.language = "he";
info.country = "IL";
info.encoding="UTF-8";
info.... |
74,025,986 | 74,026,072 | pybind11: convert py::list to std::vector<std::string> | I have the following sample code which obtains a py::list as the output of evaluating some python code.
I would like to convert it to a std::vector<std::string>, but am getting an error:
conversion from 'pybind11::list' to non-scalar type
'std::vector<std::__cxx11::basic_string<char> >' requested
Per the docum... | You need to call .cast<>:
auto vec = list.cast<std::vector<std::string>>();
<pybind11/stl.h> simply brings specializations of the conversion templates that allow such cast, and that also allow implicit conversion when you bind function with vector arguments or returning vectors (or other standard containers).
|
74,026,045 | 74,026,218 | std::ostringstream::str() outputs a string with '\0' | Here's a code snippet from CppRestSDK How to POST multipart data
std::stringstream bodyContent;
std::ostringstream imgContent;
bodyContent << ... << imgContent.str();
imgContent is the binary file content in which there's inevitably a '\0'.
I checked std::ostringstream::str() first,
std::ostringstream oss;
oss <<... | oss << "abc\0""123";
There will be slicing up to the \0 here, because the overload of operator<< for std::ostream which will be chosen here expects a const char* pointer to a null-terminated character string and will interpret it as such. There is no overload of operator<< for std::ostream taking a reference to a cons... |
74,026,051 | 74,029,071 | Drake-Ros2: Multibody Plant returns wrong values or node dies in subscriber | I am trying to use Drake in Ros2. The problem is that after defining my robot plant in my class constructor, some weird behavior occurs in the subscriber callback and I can't call any plant functions without the node dying. Here's what I have
class Foo : public rclcpp::Node{
public:
Foo() : Node("foo_node"... | First off, have you been able to briefly peruse drake-ros?
https://github.com/RobotLocomotion/drake-ros/tree/develop
It's still under development, but may have useful tidbits / utilities. It is mentioned at the bottom of Drake's website: https://drake.mit.edu/
Second off, I believe your plant is going out of scope.
P... |
74,026,068 | 74,027,779 | ld.exe: cannot find src: Permission denied | Basically im trying to build a game engine with OpenGl and SDL. Im using a makefile to compile it but I get an error. The error started appearing after I reorganized my folder structure and I included the src folder to the include path so i can access them with the absolute path. For example Renderer/Camera.h instead o... | This is not valid:
SOURCES := $(wildcard $(SRC)/***/*.cpp) $(wildcard $(INCLUDE)/***/*.cpp) $(wildcard $(SRC))
I don't know where you got that wildcard syntax from but it doesn't do what you think it does. *** is identical to * in standard glob syntax which is what GNU make uses. Also do you really expect to find .... |
74,026,860 | 74,027,027 | What is a disadvantage of initializing a smart pointer data member in a member initializer list? | Let's say there is a class B which has a smart pointer member for a pointer to object of class A. Then, what is a disadvantage of initializing the smart pointer member in a member initializer list? I know that initializing is faster than assignment (would be resetting here), but I have no idea about disadvantages. What... | There is no disadvantage and you should initialize it in the member initializer list. However I doubt it will make any performance difference at all. (Your test doesn't work. It is either done without optimizations enabled or measuring random noise.)
However usually it is recommended to not use new directly, but std::m... |
74,026,892 | 74,027,412 | cmake - add .so library with it's .h headers | I have a project with structure like this:
project/
├─ src/
│ ├─ main.cpp
│ ├─ CMakeLists.txt
├─ lib/
│ ├─ libapi.so
├─ CMakeLists.txt
├─ dep/
│ ├─ api/
│ │ ├─ api_types.h
In the main CMakeLists I have:
add_subdirectory(dep)
add_executable("my_${PROJECT_NAME}")
add_subdirectory(src)
And in CMakeLists inside src... |
First - add_subdirectory in fact just looks for CMakeLists.txt in
the specified directory to apply the sub-set of the rules to the
parent project. If the specified folder doesn't contain any
CMakeLists.txt this command does nothing (i.e. the command
add_subdirectory(dep)).
Second - target_include_directories expects ... |
74,027,016 | 74,027,110 | std::filesystem::weakly_canonical() does not seem to work with drive letters | The following code:
#include <iostream>
#include <filesystem>
int main()
{
std::filesystem::path path("C:");
std::filesystem::path canonicalPath = std::filesystem::weakly_canonical(path);
std::cout << canonicalPath.string() << std::endl;
}
produces the output:
C:\Users\andy\source\repos\ConsoleApplication... | Windows and Linux have different rules when it comes to paths.
For example, on Windows using the drive-letter and colon only means the current directory on the specified drive. This behavior is inherited from DOS.
When you build using GCC on the compiler explorer, it uses a virtual Linux environment, and Linux doesn't ... |
74,027,618 | 74,027,999 | Is there a way to pass a &CustomType or *CustomType into the "Stream Insertion" Operator? |
Spoiler-Alert: I forgot the * in the header file, it compiled but ignored my operator overload, and just printed the adress.
Leading to this confused mess of a question, i'm so sorry! Thank you all!
I've included a simple example of what i want to do.
I have a pointer to a class, and i need to output it using <<,
WIT... |
I have a pointer to a class, and i need to output it using <<, WITHOUT copying the value first.
You wrote
std::ostream& operator<<(std::ostream& out, TEST &m)
which takes a reference to a TEST object and doesn't copy anything. Why did you think it would copy something?
Anyway, that stream insertion operation probabl... |
74,027,730 | 74,029,807 | cin checking input only numbers in range from 0 to 255 | cin >> red_rgb;
How to check the red_rgb, green_rgb, blue_rgb variable when entering it, so that only values in the range from 0 to 255 are allowed, while only integers {0,1,2...254,255} are counted, otherwise, you will need to enter the correct value.
int red_rgb = 0;
int green_rgb = 0;
int blue_rgb = 0;
std::co... | Try something like that:
int inprgb(const string& hint){
int a=-1;
while (true){
cout << hint;
cin>>a;
if (cin.fail() || cin.peek()!=10 ||!(a >= 0 && a <= 255) ) {
cin.clear();
cout << "Error\n";
cin.ignore(numeric_limits<streamsize>::max(), '\n');
conti... |
74,028,163 | 74,031,170 | What will std::sort do if the comparison is inconsistent? (A<B, B<C, C<A) | I need to sort a file list by date. There's this answer how to do it. It worries me though: it operates on a live filesystem that can change during operation.
The comparison function uses:
struct FileNameModificationDateComparator{
//Returns true if and only if lhs < rhs
bool operator() (const std::string& lhs,... | As other answers have already said, handing std::sort a comparator that doesn't satisfy the weak strict ordering requirement and is preserved when called multiple times with the same value will cause undefined behavior.
That doesn't only mean that the range may end up not correctly sorted, it may actually cause more se... |
74,028,371 | 74,028,530 | C++: Is there a simple way of using a namespace as template? | Is there a way to use a namespace as a template?
I need to call the same function but from a different namespaces.
Something like that:
There are two namespaces here myNamespace1, myNamespace2 that contain a function with the same name - func()
#include <iostream>
using namespace std;
namespace myNamespace1 {
voi... | A namespace may not be used as a template parameter. But you can use for example a non-type template parameter that denotes a function like for example
#include <iostream>
namespace myNamespace1 {
void func()
{
std::cout << "myNamespace1" << std::endl;
}
}
namespace myNamespace2 {
void func()
... |
74,028,481 | 74,029,541 | Mult-output files with Makefile | I am a cuda programmer and new in vscode and Makefile environment.
For a better programming, I use multiple .cu files for my functions. Thus, for the pull_model and build_meshgrid functions, the makefile becomes:
# Target rules
all: build
build: kernel
check.deps:
ifeq ($(SAMPLE_ENABLED),0)
@echo "Launch file wil... | Well, you can't use Engine/*.o because when you run your makefile, no object files exist and so this wildcard will expand to nothing, then nothing will be built (except kernel.o).
It's a catch-22 because you can't just tell make "build all the object files that you would build if you knew which objects to build!"
If wh... |
74,029,014 | 74,029,278 | Using an atomic enum class in C++11 switch statement | Not sure this is possible, but if so, how do you use an atomic enum class for a switch statement in C++11? For example,
#include <atomic>
#include <iostream>
enum class A {RED, FRUIT, APPLE};
int main(){
std::atomic<A> myAtomicEnum;
myAtomicEnum = A::RED;
switch (myAtomicEnum){
case A::RED:
... | In C++ 11, you may explicitly cast atomic type variable to enum type, this will call std::atomic<T>::operator T() casting operator of the object:
switch ((A)myAtomicEnum){
case A::RED:
...
Btw, starting from C++ 14 this explicit cast is not needed, and cast to switch type will be done implicitly (cpprefere... |
74,029,772 | 74,032,137 | Is there any point in using __attribute__((noinline)) in a source file (not header file)? | Some programmers at my company have started sprinkling __attribute__((noinline)) in methods all over our code, in both header and source files. We do not use whole-program optimization. And in the vast majority of the cases I'm seeing, these methods are not calling other methods in the same source file ("translation un... |
Is there any benefit to marking a method "noinline" if its definition
(code body) is...
in a source (.c or .cpp) file
not called by any other methods in that source file
and whole program optimization is not being used
...?
The position of the attribute on the function / method definition instead of on a non-defini... |
74,030,006 | 74,030,608 | Where to put member variables in my interface? | The c++ guidelines say not to put any data in the base class and also not to use trivial getter and setter methods, but rather just member variables, but where do I put the member variables in my data base access implementation? If I put it in one of the derived classes, I get the compiler error that my class db_interf... | It's worth pointing out the guidelines are just that. Some of them even contradict each other. It's up to you to be the engineer and decide what guidelines make sense for you and your project.
However, these guidelines do not really contradict each other.
The first one you linked to is: C.133: Avoid protected data
The ... |
74,031,183 | 74,034,022 | Cleanest way to handle both quoted and unquoted strings in Spirit.X3 | Buon giorno,
I have to parse something such as:
foo: 123
"bar": 456
The quotes should be removed if they are here. I tried:
((+x3::alnum) | ('"' >> (+x3::alnum) >> '"'))
But the parser actions for this are of type variant<string, string> ; is there a way to make it so that the parser understands that those two are eq... | I too consider this a kind of defect. X3 is definitely less "friendly" in terms of the synthesized attribute types. I guess it's just a tacit side-effect of being more core-language oriented, where attribute assignment is effectively done via default "visitor" actions.
Although I understand the value of keeping the mag... |
74,031,210 | 74,032,845 | c++ - deterministic alternative to std::uniform_XXX_distribution with mt19937? | I need a way to get deterministic sequences of ints and doubles.
template <class U>
constexpr auto get_random_value (std::mt19937 &gen, U min_value, U max_value)->U
{
if constexpr ( std::is_same_v <U, double> or std::is_same_v <U, float> ){
std::uniform_real_distribution <U> distrib( min_value, max_value );... | The distributions in the C++ standard are not portable ("seed-stable"), in the sense that the result can change between different implementations (e.g. Microsoft STL vs gcc libstdc++ vs clang libc++) or even different versions (e.g. Microsoft changed their implementation before). The standard simply does not prescribe ... |
74,031,454 | 74,031,652 | Subset algorithm behaves differently in Python than C++ | The algorithm follows recursive approach, dividing the array in two parts:
In first recursion the first part is neglected
In second part the first part is added
Code for C++ (Works Fine)
class Solution {
public:
vector<vector<int>> result;
void get_set(vector<int>& nums, vector<int> res, int index=0... | In the C++ version, res is a by-value parameter, so a copy of the vector is made in each call. Python passes references to the list, so you keep modifying the same temp list throughout the algorithm. Pass a copy when you make the recursive calls.
There's also no need for an empty nested list in the initial value of sel... |
74,031,476 | 74,031,581 | how to initializes a collection (list) by copying the parameters from a constructor? | I've a class PokemonCollection which has a private list which accepts a pair.
Now what I've to do is, when I make an object"collection" of that class PokemonCollection in main() function, I pass some pairs to the constructor, and in the constructor I've to initialize the private list of the class.
PokemonCollection col... |
how to initializes a collection (list) by copying the parameters from a constructor?
Just like you would initialize any other data member in the member initializer list:
class PokemonCollection{
public:
void print();
PokemonCollection(const std::list<std::pair<std::string,
//---------------------... |
74,031,918 | 74,035,458 | C++ Single linked list problem deleting node | I have written this code for deleting all nodes which are divisible
by 9.
But when I try to input two consecutive numbers that are
divisible by 9 only of them is deleted.
void deletebydivisable(){
Node *currentNode = head;
while (currentNode!=NULL){
if(currentNode->nextNodeAddress->data % 9 == 0){
... | Your logic is wrong, for several reasons:
you not taking into account that the currentNode->nextNodeAddress field will be NULL when currentNode is pointing at the last node in the list. You should be deleting the currentNode, not its nextNodeAddress.
you are not taking into account the possibility that the 1st node ... |
74,032,725 | 74,045,827 | Yocto SDK Missing Files | I have a Yocto project that requires boost. I have added boost and I can confirm that the boost libraries are placed into my SDK.
To create my SDK I run the command
DISTRO=fsl-imx-fb MACHINE=imx6ull14x14evk bitbake mainapplication-dev -c populate_sdk
This builds my image without my main application installed, the main... | I made a mistake in my testing. I would export the new SDK but never installed it. The steps to solve this issue for me are
Add TOOLCHAIN_TARGET_TASK_append = " boost-staticdev" to my recipe bitbake file
Run DISTRO=fsl-imx-fb MACHINE=imx6ull14x14evk bitbake mainapplication-dev -c populate_sdk
cd tmp/deploy/sdk/
./fsl-... |
74,033,251 | 74,033,361 | How to deal with "non-const reference cannot bind to bit-field" error? | I encounter this error while using emplace_back to construct a bit field structure in a vector:
struct Foo
{
Foo(uint32_t foo1): foo1(foo1) {}
uint32_t foo1 : 4;
};
int main()
{
vector<Foo> fooVector;
Foo foo = Foo(10);
fooVector.emplace_back(foo.foo1); // Error: non-const reference cannot bind to bit-fiel... | This is the definition of std::vector::emplace_back:
template< class... Args >
reference emplace_back( Args&&... args );
Args&& in this case gets deduced to uint32_t&, and, as the error says, a bit-field (Foo::foo1) cannot be bound to this type since it is a non-const reference.
In general, you cannot have a reference... |
74,033,533 | 74,033,671 | C++ List of member callback functions | I am going from C development to C++ on the STM32 platform and simply cant find a suitable solution for my problem.
Please have a look at the simplified example code attached to this post.
#include <iostream>
#include <functional>
#include <list>
using namespace std;
class Pipeline {
public:
std::list<std::functi... | Perhaps you could attach an ID to each handler. Very crude variant would just use this address as an ID if you have at most one callback per instance.
#include <functional>
#include <iostream>
#include <list>
using namespace std;
class Pipeline {
public:
using ID_t = void *; // Or use integer-based one...
... |
74,033,685 | 74,033,793 | How does this default template struct assignment work? | I have been digging into some embedded C++ firmware used by DaveJone's (eevblog) uSupply project
https://gitlab.com/eevblog/usupply-firmware.
There is common pattern of code that I just can't quite wrap my head around what is happening.
For example:
In the file "RegistersRCC.hpp" there is a template struct:
template <s... | This is called class template argument deduction(CTAD) which allows writing deduction guides to the compiler about how to deduce the template arguments from constructor calls.
It is a handy C++17 addition that saves on typing:
std::vector x{1.,2.,3.} //deduces std::vector<double>
C++14 and older requires to explicitly... |
74,033,813 | 74,102,466 | Refactoring switch statement with template function using the type | I am trying to refactor several switch-case statements littered across the code base that have the following structure:
enum Model {
a = 1, b = 2, c = 3, d = 4, e = 5
};
function computeVal(Model m, int param1, int param2, int param3){
Eigen::MatrixXd val, val2;
swtich(m) {
case Model::a:
val = someFu... | After talking with a co-worker and doing some more research - the consensus was:
The switch statement itself isn't refactorable
The logic inside each case can be refactored into a function as it is exactly the same
e.g.
template<class LL>
function commonLogic(int param1, int param2, int param3){
LL someClass();
v... |
74,034,601 | 74,035,364 | What is wrong with the default installation of Qt6 on Ubuntu 22.04 | I am trying to install Qt (this time 6.4), the online version, on Ubuntu 22.04.
The installation was apparently smooth; I used the default options.
However, when attempting to create a desktop project, I receive the message
/opt/Qt/Tools/CMake/share/cmake-3.23/Modules/CMakeFindDependencyMacro.cmake:47: warning: Found p... | Install the OpenGL development packages like the following.
$ sudo apt install libglx-dev
|
74,034,964 | 74,035,008 | C++ can't return nth element of string only nth element onwards | I am trying to get the nth element of a string, which I know generally works with a method such as
char current_letter = input_string[j];
However when using the code below I get an output of
0 current_letter: ABC
1 current_letter: BC
2 current_letter: C
ABC BC 9ekNc5GlorW1PkaBQlYCuXMBljdSQClygl00XwKxoVzYsf8FrCs3qUZV85... | std::string current_letter = &input_string[j];
input_string[j] is a single character, not a null-terminated string. If you construct a std::string with a char* pointer to a character, it will read from that character onward until it encounters a null terminator '\0', which doesn't exist in this case, so the result... |
74,035,009 | 74,035,103 | Why is cin apparently skipping input in this C++ code? | I have a simple C++ test code. The way it should work is for a user to enter a sequence of integers through cin, followed by some character to terminate the cin input, then the code should output the integers. Next, the user should enter an integer other than zero to input another sequence. If that's what the user d... | Using cin.clear() and cin.ignore() can help:
#include <iostream>
#include <vector>
#include <limits>
int main(int argc, char **argv) {
std::vector<int> data;
int goahead = 1;
int nextval;
while (goahead) {
data.clear();
while (std::cin >> nextval) {
data.push_back(nextval);
... |
74,035,109 | 74,035,143 | Can you Iterate through member variables using a for loop, if a vector is of a class | for (std::string& request : recData.getReqest()) //recData is a vector
{
}
recData is a vector which stores objects of an X type, X class has a member variable which is "std::string request;" and as I iterate through the for loop I want all objects within recData to have their request member variable processe... | It's certainly possible, by changing the for loop and using one extra statement:
for (auto &r: recData)
{
std::string &request = r.request;
// Here's your request, for your loop.
}
|
74,035,291 | 74,063,401 | CMake Errors including IXWebSocket in Ubuntu 22 (works on MacOS 12.6) | Context:
I have a cpp program built on MacOS 12.6 with the following CMakeLists.txt file.
cmake_minimum_required(VERSION 3.19.0)
project(cpp-test VERSION 0.1.0)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED True)
add_executable(cpp-test main.cpp)
add_library(test-helpers main.cpp ${PROJECT_SOURCE_DIR}/he... | This is not a great answer to the issue, but I ended up resolving it by building ixwebsocket via CMake instead.
It seems that vcpkg was not compatible with the linux distro in my VM.
|
74,036,132 | 74,036,442 | Problem converting member function pointer to std::function with CRTP | I am trying to pass a bound member function as an std::function while hiding the std::bind_front invocation in a base class. Minimal example:
#include <functional>
static void runIt(std::function<void()> f) { f(); }
template<typename T>
struct Base {
using PFn = void (T::*)();
void run(PFn fun) { runIt(std::... | You can't std::invoke(fun, this) since this is of type Base<Derived>* and the function pointer is of type void (Derived::*)() (And Derived is not a base of Base<Derived>, but the other way around).
Either upcast the pointer to member function or the pointer to the object. Preferably the object pointer:
runIt(std::bind_... |
74,036,695 | 74,038,011 | What is the working mechanism under the hood for ReadDirectoryChangesW()? | I understand ReadDirectoryChangesW can be implemented synchronously or asynchronously. The general consideration being asynchronous is good for slow I/O operations, vice-versa.
Currently, I am trying to do monitoring and get the paths of all new files created on the drive. This would involve watching many subdirectorie... | ReadDirectoryChanges is implemented by issuing IRP_MJ_DIRECTORY_CONTROL to the appropriate file system driver, with a minor function code of IRP_MN_NOTIFY_CHANGE_DIRECTORY.
At the file system level the implementation will likely always be asynchronous unless change data is already available to return. The general synch... |
74,036,969 | 74,037,410 | Lazy type constraint (implement Rust `Default` trait in c++) | In Rust you can implement traits for structs and each implementation has own type constraint. (for who may does not familiar with rust, you can consider a "trait" as a "base class" and "implementation" as "inheritance").
look at this example:
// our struct has an item of type mutable T pointer
struct Box<T> {
inner... | I am not sure I follow exactly what you want (I don't really know Rust), but you can constrain member functions individually:
template<typename T>
concept Default = requires {
{ T::default_() } -> std::same_as<T>;
};
template<typename T>
struct Box {
static Box default_()
requires Default<T> {
//..... |
74,037,170 | 74,037,254 | Empty characters in C/ C++ | Are there any empty characters available in C or C++? And by empty character I mean, no white-space, no null character, just to skip that place of the particular character. I don't want to replace that character with the above mentioned ones, but to just disappear that character and it's place.
For example, I have a st... | The actual charset in use is not defined by the C++ standard itself, but by the particular implementation. That being said, I'm not aware of anything like that in common text encodings, and ultimately it's not clear how would that work: say that × was such a character: thisIsAma×zing$ and thisIsAmazing$ would still be ... |
74,037,422 | 74,038,021 | C++ class instances which reference to each other | It is possible to make circular references from class A to class B and vica-versa using forward declarations
class class_a;
class class_b;
class class_a {
class_a(class_b& arg) : ref_to_b(arg){}; // constructor
class_b& ref_to_b;
};
class class_b {
class_b(class_a& arg) : ref_to_a(arg){}; // constructor
... | At global scope you can declare the classes before initializing them to obtain references:
extern class_a a;
extern class_b b;
class_a a{b};
class_b b{a};
And now that we have those we can use placement new to create more such pairs:
auto a2 = new class_a(a);
auto b2 = new class_b{a2};
a2 = new(a2) class_a{b2};
Now ... |
74,037,589 | 74,037,677 | Wrong result when using double data type | The following code gets wrong result when using double data type for the result y, why is this? How do I get the correct one when using double?
You can run this code using https://godbolt.org/z/hYvxjW8xT
#include <cstdio>
#include <iostream>
int main()
{
double MYR = 153.6;
double MIYR = -153.6;
double p... | Floating point math is an approximation. So you get a number that is close to 3072 (3071.999 for example) and then you truncate it and get 3071. Instead, round the number:
printf("double res: %.0f\n", std::round(y));
And you don't even need the explicit std::round call, since %.0f format specifier implies the roundi... |
74,038,003 | 74,039,702 | Convert unsigned char* to std::shared_ptr<std::vector<unsigned char>> | I'm trying to change a variable of type unsigned char* to std::shared_ptr<std::vector<unsigned char>> for memory management. The thing is, this code was written by a coworker who left several years ago, and I'm not so sure how to manage the change in some methods since I'm not familiar with them. Currently, I'm stuck w... | If you really need the callers of this function to share ownership of the return value, then you can use std::shared_ptr<unsigned char[]>. Much more likely, callers only get to observe the pointed to data, and don't need to own it. In that case, you can use std::vector<unsigned char> as the data member, and return a sp... |
74,038,077 | 74,038,125 | Accessing structure array attributes without using pointers | Is it possible to make a structure array variable and access structure attributes without using pointers? I tried doing it without a pointer and it is giving me an error.
#include<iostream>
#include<string>
using namespace std;
struct Student
{
string name;
string rollNo;
float GPA;
string department;
... | s1 is an array of structs and needs to be accessed with an index: s1[i].name etc.
|
74,038,118 | 74,038,267 | Unable to call my operator<T t>() if it doesn't receives arguments | I'm trying to create a State class that will be used like an enum.
template <class ApplicationType>
class State
{
public:
template<class T>
requires requires(){ std::is_base_of<ApplicationType, T>::value; }
unsigned int operator()() //broken operator
{
static unsigned int localCounter =... | Just use the explicit notation for the call:
myState.operator()<Derived>();
|
74,038,168 | 74,038,227 | How to draw 1 isosceles triangle with vertex facing left side of screen using C++ | I am a student and am looking for a way to solve a problem online with content like the image below
Please solve it for me with C++ code
| If you want to solve such a problem, then you need split the big problem in to smaller problems. Then the solution is easier.
So, let's first strip of the '*'. They are always starting a row and ending it. This is not needed in the beginning.
Next. You see some sequences, like
1
121
12321
1234321
123454321
1234321
1232... |
74,038,339 | 74,038,588 | (C++) How to imagine working of nested loops? | I have no idea what's going on how to imagine that, one more thing like in 3rd for loop there's a condition that k<j but its upper loop j is set to 0 and i is also 0 then as I think k=0 if this is right than 0<0 how's that can be valid????
void printing_subarrays(int *arr,int n){
for(int i=0; i<n; i++){
for(int j=0... | I don't think it makes much sense for us to explain what's happening, you need to see it for yourself.
Therefore I've added some output lines, which will show you how the values of the variables i, j and k evolve through the loops:
for(int i=0; i<n; i++){
cout<<"i=["<<i<<"]"<<endl;
for(int j=0; j<n; j++){
... |
74,039,493 | 74,039,768 | Truncate on first non-printable character | I am trying to use std::regex to truncate on the first non-printable character.
I tried
std::string ExtractPrintableString(const std::string& message) {
std::regex trim_nonprintable_regex("([[:print:]]+).*")
std::smatch matched_message;
std::regex_search(message, matched_message, trim_nonprintable_regex)... | You need to 1) match at the start of string by adding a ^ at the start and 2) by replacing the ([[:print:]]+).* pattern with just [[:print:]]*:
std::string ExtractPrintableString(const std::string& message) {
std::regex trim_nonprintable_regex("^[[:print:]]*");
std::smatch matched_message;
std::regex_search... |
74,039,907 | 74,040,149 | What are the differences between char** and char*& in CPP | For an assignment I came across this question.
What is the result of the statement following the definitions given below?
char c='a';
char *pc=&c;
char *&rc=pc ;
(*rc)++;
after printing all the different variables it shows that now variable c stores 'b'.
I didn't understand why.
Can anyone please expla... | Both char** (pointer-to-pointer) and char*& (reference-to-pointer) are second level abstractions of a value. (There's no pointer-to-reference type btw.)
The differences are really the same as they are for regular pointers vs. references: nullable vs. non-nullable etc. See here for more: https://www.geeksforgeeks.org/po... |
74,040,122 | 74,045,096 | remove a pair from a list of pairs c++ | I'm doing this all in classes, I've a simple question, I've a private list of pairs:
std::list<std::pair<std::string, size_t>> pokemons_;
to which I've passed certain values as:
{("Pikachu", 25),
("Raticate", 20),
("Raticate", 20),
("Bulbasaur", 1),
("Pikachu", 25),
("Diglett", 50)};
Now I wa... | It can be done even simpler than Armin Montigny's solution. std::pair<> comes with comparison operators, so you don't need a custom function to check if an element of the list is equal to a given pair:
void remove(const std::string& s, size_t i) {
poke.remove({s, i});
}
Since C++20, std::list's remove() and remove... |
74,040,167 | 74,040,426 | How can I set up debugging C++ programs with command-line arguments in VS Code? | I am having a problem setting up my debugger in VSCode for C++. I wrote some code, then ran into some errors while running it so I decided to debug. I think thats when VSCode created the task.json file. Then I realized I wanted to use command line arguments and google/stackoverflow said to create a launch.json file whi... | Here is a sample from a project I currently use:
{
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch Test",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceRoot}/build_amd64/bin/tester_config",
"args": [],
"... |
74,040,516 | 74,044,374 | QDialogButtonBox::accepted() is protected | I want to write my custom input dialog. I wrote following lines to handle click on OK/Cancel:
connect(buttonBox, &QDialogButtonBox::accepted,this, &MyCustomDialog::accept);
I got this error on compile:
/usr/include/qt4/QtGui/qdialogbuttonbox.h:147:10: error: 'void QDialogButtonBox::accepted()' is protected
void a... | This is not about QDialogButtonBox. It is about your Qt version. You are using Qt5 syntax for singal-slot while you have Qt4. Use this:
connect(buttonBox, SIGNAL(accepted()),this, SLOT(accept()));
accepted is a Q_SIGNALS which is protected in Qt4, so you can't use that syntax.
|
74,040,896 | 74,048,203 | Opening file only once before writing to it in an async loop using boost::asio | Based on one of the previous questions I posted, I have implemented a separate async thread that dumps the contents of a container every 10 seconds using the steady_timer from the boost::asio library. It looks as follows:
m_outfile.open("numbers.bin", std::ios::out | std::ios::trunc | std::ios::binary);
fo... | What you're looking for is a class member. It's not global, each object instance will have its own copy.
Because it's also not local to the function, it will stay around across member function calls on the same object.
I'd argue that you don't need a flag, because you can ask the stream whether it was already open:
if ... |
74,041,078 | 74,041,179 | Function pointers initialized by lambda and their scope | I have written the following code, which shall do element-wise transformation on arrays of the type x=a op b. T is numeric type (float, double, int, uint8_t, uint32_t, ...)
template <typename T>
void processFrame(Args ARG, T* a_array, T* b_array, T* x_array, uint32_t elmcount)
{
if(ARG.multiply)
{
... | The code is safe.
Function pointers are valid throughout the length of the program (with exception of dlopen stuff...).
Lambdas without capture are implicitly convertible to function pointers through magic. Each lambda expression creates a distinct type and returns a new object of that type.
Yes, the object goes out of... |
74,041,539 | 74,093,441 | Disabling USB storage device in windows during transferring data to PC | I had used the following code to disable the USB drive in Windows but it does not work while transferring the data from USB to PC. I am requesting suggestion from you for any other alternative to disable the device during this scenario.
if (SetupDiSetClassInstallParams(m_hDevInfo, &spdd, (SP_CLASSINSTALL_HEADER*)&spPro... | Just try to enable Edit group policy in Administrative Template/System/Removable Storage Access/Removable Disks: Deny read Access manually.
Or you can use Group API using program (https://learn.microsoft.com/en-us/windows/win32/api/_policy/).
you can refer the below code for disabling the read access.
int denyRead(DWOR... |
74,041,553 | 74,041,679 | Passing Arrays as Parameters and Returning Them in C++ | // createArray_1 returns the array as a return value
double* createArray_1( ) {
return new double [ 10 ];
}
// createArray_2 returns the array from the parameter list
// (using a reference parameter)
void createArray_2( double*& arr ) {
arr = new double [ 10 ];
}
// createArray_3 returns the array from the pa... | void incorrectCreateArray_1( double* arr )
{
arr = new double [ 10 ];
}
is incorrect because you receive a pointer (uninitialized) and you make it point somewhere else. But only the arr pointer, local to this function, gets changed. The calling code still keeps its (uninitialized) pointer.
double* incorrectCreate... |
74,041,830 | 74,041,873 | C++ overload std::abs for custom (template) class? | Wrote my own numeric class. Overloaded std::numeric_limit::max() fine. However, I'm trying to overload std::abs() but the compiler doesn't like my attempt. I've tried this:
namespace std
{
template<uint8_t T>
MyType<T> abs(const MyType<T>& mt)
{
MyType<T> copy = mt;
copy.val = std::abs(md.... | Adding function or function template declarations into the std namespace is not allowed.
You should put the overloads into the namespace where your custom type is declared and then call the function with an unqualified name, so that argument-dependent lookup can find your overload.
If you are not sure at the call site ... |
74,042,287 | 74,043,148 | Does calling GetDC directly create memory leaks? | I am listening to the ON_WM_ERASEBKGND() msg, inside the fired function relative to that event called OnEraseBackground(CDC* pDC). I am changing a background color like the following:
if (pDC)
{
pDC->SetBkColor(BlackColor);
}
else if (GetDC())
{
GetDC()->SetBkColor(BlackColor);
}
My questio... | A device context returned from GetDC or CWnd::GetDC should always be released by passing it either to ReleaseDC or CWnd::ReleaseDC (doesn't matter which one). The documentation is a fair bit lenient towards situations where this isn't strictly necessary, though establishing those preconditions is complex in itself.
If ... |
74,042,325 | 74,043,027 | listing all intermediate recurrence results | I have a function
int f(int);
I want to get
[0, f(0), f(f(0)), f(f(f(0))), ...]
until f return -1.
I was wondering if there is a name for this in functional programming. It looks like recursion.
| The closest thing in range-v3 to do this views::partial_sum1. This takes a binary function, applying it to the result of the previous element in the destination range and the next element in the source range.
But here, we can simply ignore the next element in the source range, since we don't care about it - just the pr... |
74,042,810 | 74,043,589 | How to reduce recursive variadic inheritance code bloat? | Let's say I want to create a variadic interface with different overloads for the structs A,B,C:
struct A{};
struct B{};
struct C{};
template <typename ... Ts>
class Base;
template <typename T>
class Base<T>{
public:
virtual void visit(const T& t) const
{
// default implementation
}
};
template<ty... | Base<A, B, C> instantiates Base<A>, Base<B, C>, Base<B>, Base<C>
and
Base<A, C, B> instantiates Base<A>, Base<C, B>, Base<B>, Base<C>
Whereas final nodes are needed, intermediate nodes increase the bloat.
You can mitigate that issue with:
template <typename T>
class BaseLeaf
{
public:
virtual ~BaseLeaf() = default;... |
74,043,619 | 74,044,000 | What is the default probability of [[likely]]? Is it possible to change it? | What is the default probability of [[likely]]? Is it possible to change it?
Backgound: GCC has the following built-in functions:
long __builtin_expect(long exp, long c): the probability that a __builtin_expect expression is true is controlled by GCC's builtin-expect-probability parameter, which defaults to 90%.
long _... | There is no "probability" for these things. They tell the compiler to rearrange code and tests around branches to optimize for the case where one path is more often taken than another. But that's all.
These are not everyday tools you should be tossing into every loop and if statement. These are micro-optimization tools... |
74,043,623 | 74,044,848 | How can I get the logging directory of a RollingFileAppender from log4cxx? | I'm using XML to configure log4cxx. The appender is a RollingFileAppender that outputs to a folder like yyyy/MM/dd/HHmm, and I need to know what that folder is at the end of the program.
I can't get the current yyyy/MM/dd/HHmm at runtime because that value will likely be different than it was when the log directory was... | There is currently no(easy) way to get the name of the file that the RollingFileAppender is using.
Using Logger::getAppender() is the best way to get the correct appender that you are looking for. Since the appenders should all have unique names, there shouldn't be any issue with casting to the correct type. If you w... |
74,043,745 | 74,046,260 | Using macros to define forward declarations | I am writing a pretty huge program with lots of templated functions. Naturally, the program has a long compile-time, which is why I wanted to use forward declaration. Now there are a lot of functions and I do not want to write the forward declaration for each single one of them. Even more so, I want to be able to add s... | I'm not the right one to ask if what you want to do is possible in a better way, but this is definitely solvable using the preprocessor.
I'll use file iteration, although other methods are also possible:
// slot.h
#ifndef A_0
# include "a.h"
#else
# include "b.h"
#endif
// a.h
#if (SLOT) & 1
# define A_0 1
#else
# de... |
74,043,973 | 74,044,142 | How can I delete specific parts of the console in c++ ? ( not a file ) | I'm already familiar with system ("cls") but it deletes all of the text above it and I just need to delete some of the text not all.
| [Based on the reference to cls, I'm assuming this is code running under Windows.]
It depends on whether you need portability.
If you want (reasonably) portable code, you can use curses, an old text-mode Windowing library, originally written for terminals under Unix, but now implemented on most other systems (Linux, Win... |
74,044,010 | 74,046,228 | Detecting from within a process whether it is running as an HTCondor job | Could you please let me know if there is a way to detect from within a process whether it is running as an HTCondor job?
I am especially interested in how to do it from python code but a C++ way to do it would be also very helpful.
Example of what I hope to do in python:
if current_process_is_running_as_an_HTCondor_job... | HTCondor sets a number of environment variables: https://htcondor.readthedocs.io/en/latest/users-manual/services-for-jobs.html
_CONDOR_SCRATCH_DIR
_CONDOR_SLOT
_CONDOR_JOB_AD
_CONDOR_MACHINE_AD
_CONDOR_JOB_IWD
_CONDOR_WRAPPER_ERROR_FILE
The existence of any of them would be a good indicator that you are running under... |
74,044,260 | 74,045,438 | trying to figure out std::count_if | So I've been stuck with yet another issue and can't figure it out. I'm tryin to write a programm that will count vowels in a txt file. And I'm using different methods to do that. Now I'm stuck with a std::count_if method. Here is the code:
std::string vowels = "aeiouyAEIOUY";
bool findVowel()
{
... | Start by checking the documentation of std::count_if.
As you can see in (3), it requires a UnaryPredicate, which is some function (or function object) that takes a single parameter and returns true or false. The count_if function goes over each char in the input and uses your predicate to check if it counts. Therefore ... |
74,044,278 | 74,044,393 | static variables in a template class c++ | So, I'm pretty new in the generic programmation and I started the following :
template<class T>
class A
{
public:
static int m;
}
template<class T>
int A<T>::m;
int main()
{
A::m = 3; //Cannot compile of course !!
return 1
}
The idea being to have a member variable that could be shared by all the instances of ... | Members of class templates are never shared between specializations of the class template. You should consider a class template to be just that: A template to create classes of similar structure based on different types. For each type T the specialization A<T> is an independent class. The resulting classes are not othe... |
74,044,404 | 74,044,577 | save result of for_each algorithm inside a vector | I have a functor and the overloaded operator() of it returns a double. In an easy way I can write:
int main(){
auto f=[](double t){return 1.0/(pow(7.0*t,2.0)+1.0);};
std::vector<double> nodes(n);
bestpolchevnod(f,nodes); //calculate nodes = f_i(cheby_point(i))
ChebyPoly c_p = ChebyPoly(nodes);//call th... | std::for_each is the wrong algorithm, you want std::transform
std::vector<double> resvec(xpoints.size());
std::transform(xpoints.begin(), xpoints.end(), resvec.begin(), ChebyPoly(nodes));
Or without zero-initialising the elements of resvec
std::vector<double> resvec;
resvec.reserve(xpoints.size());
std::transform(xpoi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.