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 |
|---|---|---|---|---|
73,825,946 | 73,826,643 | Passing `this` to a function as a shared_ptr | I am writing some example code that hopefully captures my current struggle.
Let's assume I have a class for some general shapes Shape
and a nice Function that doubles the perimeter of any shape
float DoublePerimeter (shared_ptr<Shape> shape)
return 2*shape->GetPerimeter();
};
Is it possible to use such a function in... | If you don't want to use enable_shared_from_this, perhaps because your objects are not always owned by a shared pointer, you can always work around it by using a no-op deleter:
void nodelete(void*) {}
void Square::Computation() { DoublePerimeter({this, nodelete}); }
but it's a hack (and a fairly expensive one at that... |
73,826,266 | 73,864,153 | CMake can not find SFML lib | I have a project depends on SFML lib on C++. I trying to make it with CMake.
CMakeLists.txt is:
cmake_minimum_required(VERSION 3.16.3)
project(3D_Renderer_from_scratch)
set(CMAKE_CXX_STANDARD 17)
include_directories(headers source)
set(SFML_STATIC_LIBRARIES TRUE)
find_package(SFML COMPONENTS window graphics system)... | As already mentioned in the comments (why not write it as an answer?), CMake was looking for static SFML libraries and it most likely just found shared libraries.
Either make sure that static libraries (the ones with the -s suffix) are provided.
Or don't request static libraries, which you can achieve be not setting SF... |
73,827,170 | 73,827,423 | How to change a brush's color | Ok suppose I have a brush,
HBRUSH brush = CreateSolidBrush(RGB(0, 0, 0));
And I want to change it's color.
Not calling CreateSolidBrush and DeleteObject on it over and over again.
Like in this example,
#define INFINITY UINT64_MAX // You get the point. I am just calling it many times.
RECT rect = { 0 };
HBRUSH brush =... | Actually, I am so sorry for asking this question. I found the answer.
Here it is:
HBRUSH dcbrush = (HBRUSH)::GetStockObject(DC_BRUSH); // Returns the DC brush.
COLORREF randomColor = RGB(69, 69, 69);
SetDCBrushColor(hdc, randomColor); // Changing the DC brush's color.
In the above snippet;
Calling GetStockObject(DC_B... |
73,827,276 | 73,827,842 | Using std::map or std::unordered_map when storing consecutive indices | I'm storing some data in a vector for various filepaths scanned, e.g. std::vector<CustomData> mDataVector. A search routine yields multiple indices in this vector where that CustomData matched some criterion, i.e. it spits another vector of indices (e.g. 0, 8, 1 for three items at indices 0, 8 and 1 in that vector that... | Choosing between std::map and std::unordered_map comes down to if you care about ordering or lookup.
If you need ordering, then you want std::map, at the cost of slower lookup (logarithmic).
If you need fast lookup, they you want std::unordered_map, at the cost of no guaranteed ordering when looping.
However, in your c... |
73,827,992 | 73,865,559 | g++: error unrecognized command-line option -municode using Cygwin | I am trying to build GetDP (finite-element sofware) from source using the 64-bit GNU compilers in Cygwin, namely gcc.exe, g++.exe and gfortran.exe, with their toolchain x86_64-pc-cygwin. I have the same error while linking the executable getdp.exe (in my case raised by the g++ compiler):
g++: error: unrecognized comman... | The problem was not in Cygwin compiler toolchains, but in the CMakeList.txt file of the software I was trying to compile (GetDP).
Now the issue is fixed and the executable can be built without any errors using both gcc and mingw-x64 within Cygwin.
|
73,828,316 | 73,992,835 | How to add ImageMagick/Magick++ to my c++ project with CMake? | I am new to CMake. I was trying to use ImageMagick's c++ api Magick++ in my code.
This is my whole directory structure:
external/image_magick just contains the result of cloning the image magick library using: git submodule add https://github.com/ImageMagick/ImageMagick.git external/image_magick.
This is the top-level... | According to this answer, the solution was to add the following to CMakeLists.txt:
#ImageMagick
add_definitions( -DMAGICKCORE_QUANTUM_DEPTH=16 )
add_definitions( -DMAGICKCORE_HDRI_ENABLE=0 )
find_package(ImageMagick COMPONENTS Magick++)
include_directories(${ImageMagick_INCLUDE_DIRS})
target_link_libraries(demo ${Image... |
73,828,961 | 73,829,148 | Code ends before it actually should, I'm using std::time() | I'm writing a code that tries to paint all dots in graph correctly by randomly giving colors (according to some simple algorithm) while I still have time left. Correctly means that no two dots with same color are adjacent. Also every dot must have color distinct from the initial.
I noticed that in a simple test it give... | Use difftime() to calculate the number of seconds between two time_t variables. The time_t is opaque and can contain different values on different systems according to the doc.
|
73,829,448 | 73,832,318 | How to get the convex hull of a binary image using DIPlib in C++? | I have a stack of binary images of an open porous structure and I want to get a binary mask which covers the whole volume of the structure (the structure itself and the void contained in the structure). I think a good way to achieve my goal would be to calculate the convex hull of the image. This works fine in Python u... | You'd want to use the function dip::MakeRegionsConvex2D(). For example:
dip::Image img = dip.ImageRead('yIFuP.jpg');
dip::Image bin = img > 128; // assuming img is scalar
dip::MakeRegionsConvex2D(bin, bin);
This function is explicitly written for 2D images, and will not work for 3D images.
For a 3D image, I would get... |
73,830,456 | 73,830,921 | Static variables and different namespaces in c++ | I have read on static variables and know what they are, how they function when define in a .cpp file, function, and class.
But I have slight confusion when define in different namespaces in the same cpp file.
One of these voted answers here says:
When you declare a variable as static inside a .h file (within or withou... | That's not what the passage you quoted is talking about. It is referring to the fact that static variable names have internal-linkage. What that means is that you can't access a static variable a that is defined in "a.cpp" from "b.cpp", even if you include a declaration of a in "b.cpp". That declaration will refer t... |
73,830,696 | 73,830,803 | Why segmentation fault when using built-in array instead of vector or new | I'm initializing an array n-size with all zeros. Using the vector class or allocating with "new" works but with built-in array, i get segmentation fault in hackerrank c++.
long long arr[n];
for(int a = 0;a < n;a++) {
arr[n] = 0;
}
//segmentation fault in some cases.
long long arr = new long long[n]; // doesn't fai... | The question has been subtly answered in the question itself. Allocating memory from stack is okay, but only for small numbers. Hackerrank problems may have large input n. As a thumb rule, 10^6 ints can be kept on stack since that's about 4 MB considering 4 bytes per integer. For anything larger, please use dynamic mem... |
73,831,400 | 73,831,477 | std:vector<T> of arbitrary size and arbitrary starting point | Say I want a std:vector<T>, and say I have 1000 elements of T. The index into T has an arbitrary starting point, say 15000 to 16000 (1000 elements).
Without allocating 16000 elements, how do I create the vector<T> so that 15000 is index, 1, 15001 is index 2, etc.
I know I can do this with a Hash, but my indices are nat... | AFAIK, std::vector's index is not variable, it always starts at 0. You could either manually substract 15000 from your index like so:
for(int i = 15000; i < 16000; i++) {
std::cout < vector[i - 15000] << std::endl;
}
or create a class that does it for you:
#include <vector>
#include <iostream>
template<typename T... |
73,831,908 | 73,920,787 | Convert raw YUV422 image to RGB | I have a raw image in a yuv422 encoding that I extracted from a csi_camera on my Jetson Nano and I want to convert it to RGB encoding to use for machine learning. How would I go about it? I've tried using different cvtColor codes in OpenCV but resulting images were still a mess. Is there a way to turn this image to a "... | So I finally figured out how to convert the image with the following code:
for (rosbag::MessageInstance const m : rosbag::View(bag)) {
// Read only the input topic
if(m.getTopic() == topic) {
// Create an image pointer to the bag file image messages
sensor_msgs::ImageConstPtr imgPtr = m.instantiate<sensor_msgs::Ima... |
73,832,210 | 73,837,576 | undefined reference to '__atomic_*' in SCons but similar questions' solution won't work | I'm trying to build Godot with SCons. Everything was working fine until I've used std::atomic in my library my custom module uses (the library is working fine with a Qt application I've created to test it). Then this error happened:
[100%] Linking Program ==> bin/godot.x11.tools.64
/usr/bin/ld: /home/sms/Code/_B... | To help you debug, try temporarily commenting out the setting of LINKCOMSTR (should be in methods.py) so that SCons can show you the whole link line - normally Godot tries to be "helpful" and emit shorter messages, but it doesn't help when you're getting something like a link failure. You'll probably notice that it's ... |
73,832,281 | 73,833,507 | C++ Template queue with template class | My template queue is below
template <typename T>
class LockingQueue
{
private:
std::queue<T> s_queue;
public:
void push(T const& value)
{}
T pop()
{}
};
And my template class is below
template <typename TaskData, typename TaskName>
class CommonMsg
{
public:
TaskData dataType;
TaskName tas... | As far as I am aware, you can do this in two ways. In both ways you need to specialize your original class template so that it gets instantiated when you pass a smart pointer. The simplest way is option 1 (see code below), but you must specify the type in the main function. A bit dirtier approach is option 2 (see code ... |
73,833,602 | 73,833,817 | Remove __attribute__((...)) from a function pointer or reference | #include <utility>
#include <iostream>
int main()
{
using std_type = std::remove_reference<void (__attribute__((stdcall)) &)(int) noexcept>::type;
using cdecl_type = std::remove_reference<void (__attribute__((cdecl)) &)(int) noexcept>::type;
using type = std::remove_reference<void (&)(int) noexcept>::type;... | You can still create a traits remove_stdcall, something like:
template <typename Func>
struct remove_stdcall
{
using type = Func;
};
template <typename Ret, typename ... Args>
struct remove_stdcall<Ret __attribute__((stdcall)) (Args...) noexcept>
{
using type = Ret(Args...) noexcept;
};
template <typename Ret... |
73,834,170 | 73,834,212 | Should I be using std::array for very large arrays? What is the idiomatic alternative? | I'm doing a college assignment with C++. I mostly have been instructed in C, so I'm putting in some effort to practice more "idiomatic" C++.
In C, I had no issues working with a large dynamically allocated array:
int* board = (int*) malloc(2048 * 2048 * sizeof(int));
In C++, as I understood, malloc shouldn't be used, ... | In general, coming from C:
int foo[10] -> std::array<int, 10> foo
int* foo = malloc(10 * sizeof(int)) -> std::vector<int> foo(10)
std::array directly contains all of its elements, just like a C array. In fact, it's essentially just simple structure like this:
template <typename T, size_t N>
struct array
{
T __un... |
73,834,248 | 73,836,300 | Does multi-threaded code increase real-time memory usage? | Recently, I'm learning about multithreading. There is some confusion about the memory usage of multiple threads. Does multi-threaded code increase real-time memory usage? I wrote the following two pieces of code.
First, single-thread implementation of code is as follows:
for (int i = 0; i < 1000; i++)
{
A* pA = new... | I test the code for single thread and multiread. And the result shows the multi-threaded code increase real-time memory usage. And the amount of memory added depends on how much memory is being consumed simultaneously in multiple threads.
For example, single-thread implementation of code is as follows:
#include <omp.h>... |
73,834,280 | 73,834,417 | c++11 timed_mutex behaves different from mutex when calling "try_lock_for" | I was expecting that if timed_mutex.try_lock_for could success for all calling threads, like this:
timed_mutex tm;
atomic<int> atTm(0);
void tTMutex(int i) {
this_thread::sleep_for(chrono::microseconds(200 * i));
if (tm.try_lock_for(chrono::milliseconds(200 * i))) {
atTm.fetch_add(1);
}
}
int main(... | You are not unlocking the mutex after acquiring the lock in the first version:
if (tm.try_lock_for(chrono::milliseconds(200 * i))) {
atTm.fetch_add(1);
tm.unlock(); // missing
}
so only the first thread will be able to ever acquire it. That's why std::unique_lock should be preferred. It unlocks in its destruct... |
73,834,480 | 73,837,020 | How to connect sections of an array or organize an array the same as another? | I am not sure how to connect a part of an array or if it is even possible.
My code is as follows:
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
string name;
string date[3];
double height[3];
double enter;
cout << "Enter name of a pole vaulter: ";
cin >> name;
cout << "Enter date of first ... | Group of data, data sorting, multiple data points that should be aligned/connected to their respective other data points. I think the best solution here would be the use of a struct or class with vectors:
Let's say you want a variable that contains both your date and number. We can construct a class or structure for t... |
73,834,500 | 73,834,591 | std::thread constructor: passing a value by reference needs to call ref(), why? | (1) I've this code snippet:
void tByRef(int& i) {
++i;
}
int main() {
int i = 0;
tByRef(i); // ok
thread t1(tByRef, i); // fail to compile
thread t2(tByRef, (int&)i); // fail to compile
thread t3(tByRef, ref(i)); // ok
return 0;
}
As you could see, function tByRef accepts a lvalue referenc... | Threads execute asynchronously from the code that started them. That's kind of the point. This means that, when a thread function actually gets called, the code that started the thread may well have left that callstack. If the user passed a reference to a local variable, that variable may be off the stack by the time t... |
73,834,589 | 73,834,604 | c++11 thread: sub-thread throws exception leads to main thread crash | I was expecting that the status of sub-thread, whether they succeed or not, should not crash main thread.
So I had a quick test:
#include <thread>
#include <iostream>
#include <exception>
using namespace std;
using namespace std::chrono;
void th_function() {
this_thread::sleep_for(chrono::seconds(2));
throw 1; ... | It is true that exceptions handling is localized to a single thread, but as always, not catching an exception at all causes a call to std::terminate, which in turn terminates the whole program. The same applies to other conditions resulting in a call to std::terminate, e.g. throwing from a destructor during stack unwin... |
73,834,634 | 73,834,690 | C++ setw() function does not cater for character output width on screen | IDE used Eclipse
It is said to use setw() and setfill() function to format your text using cout . I tried that but if you see the text does not align on the screen because lets say in first line what compiler does is
type Reg No. and fill rest with - characters
but if you see image attached link, width of R character ... | That's correct. std::setw does not actually adjust the visible width of a conversion; it adjusts the character count, on the assumption that the output is being viewed with a monospace font (that is, a font in which all characters are the same width).
So you need to configure Eclipse's console to use a monospaced font.... |
73,834,727 | 73,834,903 | How to find year using mod function? | I want to know the mod function. It's like we've been searching for years after using the mod function in Excel. Can we do the same in c++?
For example, when mod in Excel,
Id = 199734902138
= mod(id,100000000)
As the answer,
34902138
Then id - 34902138
As the answer,
199700000000
Then 199700000000/100000000
Then we c... | Modulo doesn't find year, it returns the remainder after a division.
The modulo operator is %.
For example:
#include <iostream>
int main() {
int x;
x = 10 % 8;
std::cout << x << std::endl; // output is 2
return 0;
}
Given your example, the following code would perform the same order of operations a... |
73,834,971 | 73,839,293 | Dynamic dispatch based on Enum value | Lets say I'm trying to write multiple handlers for multiple message types.
enum MESSAGE_TYPE { TYPE_ZERO, TYPE_ONE, TYPE_TWO, TYPE_THREE, TYPE_FOUR };
One solution might be
void handler_for_type_one(...){ ... }
void handler_for_type_two(...){ ... }
...
switch(message_type){
case TYPE_ONE: handler_for_type_one(); br... | One way I'd get rid of the manual switch statements is to use template recursion, as follows. First, we create an integer sequence of your enum class, like so:
enum MESSAGE_TYPE { TYPE_ZERO, TYPE_ONE, TYPE_TWO, TYPE_THREE, TYPE_FOUR };
using message_types = std::integer_sequence<MESSAGE_TYPE, TYPE_ZERO, TYPE_ONE, TYPE... |
73,834,983 | 73,854,427 | How to getBlob data from sql and display in gridview using pixmap in C++ 98? | I am new in C++ .I am trying to load blob image which is stored in .bin file from sql Database. That .bin file store blob image in form of string like BM6ect(each .bin have 3 to 4 char).
Here is code that save the blob image(.bmp) in db
QPixmap p;
p.load(filename);
string a = "/root/QtApplic... | Try this code
driver = get_driver_instance();
con = driver->connect("localhost","","");
con->setSchema("BitmapImagesSchema");
stmt = con-> createStatement();
std::istream *blobData;
res = stmt->executeQuery("select `ImagesBitMap` from bitmapImagesTable where `ID`='"+boost::lexical_cast<std::s... |
73,835,215 | 73,835,446 | Escaping newline character when writing to stdout in C++ | I have a string in my program containing a newline character:
char const *str = "Hello\nWorld";
Normally when printing such a string to stdout the \n creates a new line, so the output is:
Hello
World
But I would like to print the string to stdout with the newline character escaped, so the output looks like:
Hello\nWo... | The solution I opted for (thanks @RemyLebeau) is to create a copy of the string and escape the desired escape sequences ("\n" becomes "\\n").
Here is the function which does this escaping:
void escape_escape_sequences(std::string &str) {
std::pair<char, char> const sequences[] {
{ '\a', 'a' },
{ '\b', 'b' },
... |
73,835,444 | 73,835,675 | When do we need std::shared_future instead of std::future for inter-thread synchronization? | I tried to test how std::shared_future is shared between different threads as these threads all calls its wait() function, and wake up after its signal is called. As below:
#include <iostream>
#include <future>
using namespace std;
int main() {
promise<void> p, p1, p2;
auto sf = p.get_future().share(); // This ... | The "shared" part of shared_future is not about the waiting but getting.
I expected that for the non-shared version, only 1 thread will successfully wait and return while other threads will hang.
No, this is completely safe, you can wait on a future from as many threads as you want (it is a const member, hence thread... |
73,835,462 | 73,835,571 | How do I print const char? | #include <iostream>
using namespace std;
int main() {
int age = 20;
const char* pDept = "electronics";
cout << age << " " << pDept;
}
The above code is normal.
Why shouldn't I use cout << *pDept instead of cout << pDept above?
| Both of them are legal in C++. Which one to use depends on what you want to print.
In your case, pDept is a pointer that points to a char in memory. It also can be used as a char[] terminated with \0. So std::cout << pDept; prints the string the pointer is pointing to.
*pDept is the content that pDept points to, which ... |
73,835,763 | 73,835,792 | Why I can't provide an in-class initializer for std::vector data member | I'm trying to initialize the member vec within the class scope, but the compiler throws a more cryptic error.
class A {
public:
static const size_t sz = 10;
static const std::vector<double> vec{ sz }; // error
};
The compiler (gcc) gives the following error(s):
error: in-class initialization of static data mem... | Ordinarily, static data members may not be initialized in the class body. However, we can provide in-class initializers for static members that are only of const-qualified integral type. If non-integral static members are used, and you need to provide an in-class initializer, the data member shall be constexpr literal ... |
73,835,826 | 73,835,916 | Why does a single-threaded example of std::promise-std::future throw? | The following code throws std::system_error on recent g++, clang++ compilers and I do not know why. MSVC seems to work.
I was under the impression multi-threaded context is not necessary for promise and future to work.
#include <future>
int main() {
std::promise<int> p;
std::future<int> f = p.get_future();
... | If I remember correctly, std::future depends on thread. So, you would need to link against -pthread.
Godbolt (with -pthread compiler option)
https://godbolt.org/z/hPTMKqMjr
|
73,836,099 | 73,836,200 | c++11 atomic<int>++ much slower than std::mutex protected int++, why? | To compare the performance difference between std::atomic<int>++ and std::mutex protected int++, I have this test program:
#include <iostream>
#include <atomic>
#include <mutex>
#include <thread>
#include <chrono>
#include <limits>
using namespace std;
#ifndef INT_MAX
const int INT_MAX = numeric_limits<std::int32_t>::m... | Your test does not really compare the performance of mutex vs atomic:
Your mutex version locks the mutex once, then does 12500000 iterations without paying any additional cost for thread synchronization mechanisms.
In your atomic version you pay the cost of the atomic synchronization for every increment, and every de... |
73,836,540 | 73,836,766 | Pass non-dynamic memory allocation to CreateThread() function | I pass a address of USB_INSTACE_DATA variable to function CreateThread() like this. Is it safe to use, or I must use dynamic memory allocation for USB_INSTACE_DATA data?
DWORD WINAPI MyThreadFunction(LPVOID lpParam);
void GetUSBInfo(PDEV_BROADCAST_DEVICEINTERFACE pDevInf, WPARAM wParam) {
USB_INSTACE_DATA data{ pD... | This isn't safe. USB_INSTACE_DATA data{ pDevInf, wParam }; has automatic storage duration. Once the enclosing scope ends (i.e. when the function returns), the memory is cleaned up.
The thread launched through CreateThread, however, holds a pointer &data beyond the function's scope. This is an instance of the classical ... |
73,836,564 | 73,836,627 | How to auto deduct argument and return type of lambda with std::function? | This code:
template<typename Arg, typename Ret>
Ret fun(std::function<Ret(Arg)> fun){
Arg x=0;
return fun(x);
};
auto f=[](int x){return x;};
fun(f); //compilation failed.
doesn't work. I want to get the argument and return type of lambda in fun.
I think the argument type has already known at comile time, w... | The problem here is that the lambda is not an std::function, so you're asking the compiler to do a deduction (find the type of Arg AND Ret) and a convertion i.e. convert the lambda to an std::function. The combination causes a conflict.
If you want to still use std::function as argument type for fun, then the easier th... |
73,836,838 | 73,836,960 | C++ Input space separated integers and store inside an int array | I am trying to input int array size and then get N space-separated integers as shown below:
int main()
{
int N;
cin>>N;
int *arr = new int(N);
for(int i=0; i<N; i++) {
cin>>arr[i];
}
for(int i=0; i<N; i++) {
cout<<arr[i]<<endl;
}
if (isSpiralSorted(arr, N))
cout <... | You are creating a single scalar with new int(N) and not an array. If you change it to new int[N] then it runs fine.
Also you forgot to delete the array in the end.
#include <iostream>
int main()
{
int N;
std::cin >> N;
int *arr = new int[N];
for(int i=0; i<N; i++) {
std::cin>>arr[i];
}
... |
73,836,999 | 73,837,579 | What's the actual reasoning behind iterator categorization in STL? |
For reasons of efficiency it's not possible to have every container work with every generic algorithm -- STL Tutorial and Reference Guide.
So i'm learning about STL and i was reading the mentioned book and trying simultaneously to see the justification behind this categorization of iterators, the book doesn't actu... | The justification for the categorization of iterators is that they are useful. The categories are not restrictions or "safety", not limitations on what can be. They are descriptions and an organization of what exists. Algorithms first, iterator categories second.
If someone creates a new container, the iterator of that... |
73,837,203 | 73,838,589 | OpenGL Creating texture coordinates on the fly with a vec4 | I'm following this site to learn OpenGL. In core profile mode to render a quad along with texture coordinates, I'm defining data like this:
float vertices[] = {
// positions // texture coords
0.5f, 0.5f, 0.0f, s0, t1, // top right
0.5f, -0.5f, 0.0f, s1, t1, // bottom right
-0.5f, -0.... | I suggest to specify the texture coordinate attribute in range [0.0, 1.0]. Map the texture coordinates from the range [0.0, 1.0] to the range [s0, s1] and [t0, t1] in the vertex or fragment shader. e.g:
out vec4 frag_color;
in vec2 tex_coord; // 0.0 .. 1.0
uniform vec4 texcoord; // s0, t0, s1, t1
uniform sampler2D ... |
73,837,306 | 73,846,269 | Does lvalue-to-rvalue conversion is applied to non-type lvalue template argument? | struct S{
constexpr S() {};
};
template <auto x> void f();
int main() {
S s{};
f<s>();
}
First off, per [temp.arg.nontype]/1
If the type T of a template-parameter (13.2) contains a placeholder
type (9.2.9.6) or a placeholder for a deduced class type (9.2.9.7),
the type of the parameter is the type deduce... | The meaning of [expr.const]/10 is that whenever an expression appears in a context that requires a "converted constant expression of type T", that expression is "implicitly converted to type T" and the additional restrictions in [expr.const]/10 shall apply.
So s is not "converted to a prvalue before any implicit conver... |
73,838,196 | 73,838,263 | (C2352) C++ Return value as function default parameter | I'm making a linked list class and I want a convenient default argument for my 'remove()' function.
int size() { return size_; }
int remove(int index = size() - 1);
^[C2352]
This gives me an error a call of a non-static member function requires an object, so I tried
int remove(int index = thi... | Default arguments must be bound at compile time, so this is not allowed since it's a runtime value. You could use a free/static function but I don't see how the design is going to work as it wouldn't refer to any specific list instance.
In my opinion the best solution is to use a special value for what you need, eg:
cl... |
73,838,329 | 73,838,408 | Not able to solve a specific C++ pattern problem | I tried to make this problem but not getting solution . I want to print the pattern using c++ - This is pattern -
I tried this code but it is printing in reverse order .
using namespace std;
int main() {
int n;
cin>>n;
int i = 1;
while(i<=n){
int j =1;
while(j<=n){
... | your problem is easy, in the inner loop where you are saying
int j = 1;
while(j<=n){
cout<<j;
j=j+1;
}
here you are ascending from 1 till n, that's what made your problem, instead, you can write :
int j = n;
while (j >= 1) {
cout << j << " ";
j = j - 1;
}
where here in this code, y... |
73,838,972 | 73,839,132 | C++: Why does cin allow ints for inputs of strings? | I'm working on a school project that requires the verification of a string for the input, and NOTHING ELSE. However, whenever I pass an int for bug testing (I.E. 0), the program doesn't trigger cin.fail(). For example:
#include <iostream>
#include <string>
using namespace std;
int main() {
string lastName;
c... | A string is a sequence of characters. Therefore, 1999 is a valid string.
If you want to verify that the string consists only of alphabetical characters and does not contain any digits, you can use the function std::isalpha on every single character in the string:
#include <iostream>
#include <string>
#include <cctype>
... |
73,839,248 | 73,839,390 | Cleaner if statement sequence in C++ | I am a bit of a newbie so please go easy on me. I wanted to know if there was a way to shorten these if statement chains like the one shown below in C++.
int offset;
string S;
cin >> S;
if(S == "mon")
{ offset = 0; }
else if(S == "tues")
{ offset = 1; }
else if(S == "wed")
{ offset = 2; }
else if(S == "thurs")
{ ... | I would suggest using std::map.
std::map<std::string, int> m {
{"mon", 0}, {"tues", 1}, {"wed", 2}, {"thurs", 3},
{"fri", 4}, {"sat", 5}, {"sun", 6}
};
std::string s;
std::cin >> s;
int offset = m.at(s);
If s is not a valid key, the std::out_of_range exception will be thrown. You might handle that by putting a ... |
73,839,561 | 73,839,742 | 2D vector with aligned allocator syntax problem | I am completely stuck when I am trying to put the value of 2D vector into another 2D vector. The code execution just exit. Putting a little extra code to make things more clear.
int data_size_val= 8;
int n_qubits_val = ceil(log2(data_size_val));
int n_states_val = pow(2, n_qubits_val);
vector<vector<float, aligned_allo... | Your source_phi is an empty vector of empty vectors. So, the source_phi[i][j]= phi_val[i][j] assignment is attempting to assign a value to a non-existent element of a non-existent vector.
There are several ways you can handle this. One is to use the push_back and temp approach that you used when initialising the phi_va... |
73,839,949 | 73,841,055 | Compile C++ Windows exe standalone files with MSYS2 | I've recently started using Msys2 to install gcc compiler to make some exe for Windows. It works very well, but there's a problem when passing my exe to my brother. His laptop has not msys2 installed and when he tries to run my exe some errors occur. Seems like few dll files are necessary to use my exe (like msys-2.0.d... | My version of MinGW is a bit old ...
C:\example>where g++
C:\misc\mingw810_64\bin\g++.exe
C:\example>g++ --version
g++ (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not e... |
73,840,395 | 73,840,426 | why atoi() function from #include<cstdlib> is not working | I created a program to convert a number into its binary format using a string(r), now I want to convert it into integer data type, I found atoi() function(import from cstdlib) on google for conversion from string to integer but its not working.
Here is my code- it shows error click here to see it
#include <iostream>
#i... | atoi() expects a const char * (an array of char), where r is a std::string object. You can convert a string to const char * with it's c_str() method.
atoi(r.c_str())
|
73,841,367 | 73,874,445 | boost::serialization of boost::optional of type with private default constructor | I'm upgrading from boost 1.54 to the latest 1.80 and have a compilation problem with boost serialization.
I have a class A with private default constructor. Another class B has a boost::optional<A> field and also is boost::serializable.
To allow boost::serialization to create an empty instance of A during boost::serial... | I have not found any better solution than to add the following friendship declaration to my class A, in addition to the existing friend class boost::serialization::access declaration:
template<class Archive, class T>
friend void boost::serialization::load(
Archive & ar, boost::optional<T> & t, const unsigned int ver... |
73,841,522 | 73,841,590 | Can't print a custom struct, 'error: no match for operator<<' | I am making a program that asks the user how many robots they want to create. They then need to name those robots, and it is then stored in an array of structs.
The struct userRobot will have other values like x-y coordinated but since I'm just starting on the project I just want to start with names first.
Everything w... |
You can't just print out the structs themselves. Trying to print out structs causes this error in your case. You can instead print out their individual members, in your case names.
for (int j = 0; j < NumberOfRobots; j++){
cout << RobotArray[j].name << endl;
}
In the first for loop , why do you subtract... |
73,842,212 | 73,848,003 | Wrong answer due to precision issues? | I am implementing Greedy Approach to TSP:
Start from first node.
Go to nearest node not visited yet. (If multiple, go to the one with the lowest index.)
Don't forget to include distance from node 1 to last node visited.
However, my code gives the wrong answer. I implemented the same code in Python and the python c... | Yes, the difference is due to round-off error, with the C++ code producing the more accurate result because of your use of long double. If you change your C++ code, such that it uses the same precision as Python (IEEE-754, meaning double precision) you get the exact same round-off errors in both codes. Here is a demons... |
73,842,421 | 73,842,571 | bad_function_call thrown and segmentation fault caused when passing avx variables to std::function | This problem is found when writing some code related to computer graphics, a simplified version of the code is shown below:
#include <bits/stdc++.h>
#define __AVX__ 1
#define __AVX2__ 1
#pragma GCC target("avx,avx2,popcnt,tune=native")
#include <immintrin.h>
namespace with_avx {
class vec {
public:
vec(double ... | Changing the target architecture half way through the file is causing your issue. Presumably parts of std::function's implementation changes with the target architecture. Moving your pragma to the start of the file fixes the problem: https://godbolt.org/z/WP5ah38WP
It'll be safer in general if you set your architecture... |
73,842,477 | 73,843,311 | CTest output and log file with words cut off | I run the following command:
$> ctest -V -R path_unittest
and get the following failure message:
2: /path_to_spec/path_unittest.cpp:80: ERROR: CHECK( lines[0] == "test,test1,test2" ) is NOT correct!
== test,test1,test2 )st,test1,test2
2:
2: /path_to_spec/path_unittest.cpp:81: ERROR: CHECK( lines[1] == "1,2,3" ) is N... | I'm guessing that your input file has line endings of "\r\n". You split at "\n" so you end up with strings ending in "\r". When these strings are printed they cause the strange output you see, because "\r" causes the output to continue from the beginning of the current line, thus overwriting previous output.
|
73,842,687 | 73,842,852 | Does SSL_free also close the the object's file descriptors? C++ OpenSSL | Does SSL_free also close the the object's file descriptors? C++ OpenSSL
I could not find this information on https://www.openssl.org/docs/man1.1.1/man3/SSL_free.html.
In case openssl does not close the file descriptor: Should you close the file descriptor(s) like in example 1 or 2? Or even example 3 (unlikely)?
Example... | You should not close the file descriptors you get from SSL_get_fd() (or SSL_get_rfd()/SSL_get_wfd():
SSL_free() also calls the free()ing procedures for indirectly affected items, if applicable: the buffering BIO, the read and write BIOs, cipher lists specially created for this ssl, the SSL_SESSION. Do not explicitly f... |
73,842,869 | 73,842,958 | Can't find the problem in the string fuction | So the problem was this
error: invalid operands of types ‘const char [20]’ and ‘float’ to binary ‘operator<<’
that came out on my string fuction. I tried searching up in google but nothing came up.
#include <iostream>
#include <string>
using namespace std;
class Rectangle
{
public:
Rectangle () : length(1.0),... | You're probably mixing printing to an output stream via << with concatenating strings.
To concatenate 2 std::strings, you use the + operator instead. The operator also can work with things similar to a string like char const*, but only if one of the operands already is a std::string.
Use std::to_string for converting t... |
73,843,430 | 73,843,458 | Clang 14 and 15 apparently optimizing away code that compiles as expected under Clang 13, ICC, GCC, MSVC | I have the following sample code:
inline float successor(float f, bool const check)
{
const unsigned long int mask = 0x7f800000U;
unsigned long int i = *(unsigned long int*)&f;
if (check)
{
if ((i & mask) == mask)
return f;
}
i++;
return *(float*)&i;
}
float next1(flo... | *(unsigned long int*)&f is an immediate aliasing violation. f is a float. You are not allowed to access it through a pointer to unsigned long int. (And the same applies to *(float*)&i.)
So the code has undefined behavior and Clang likes to assume that code with undefined behavior is unreachable.
Compile with -fno-stric... |
73,843,592 | 73,843,648 | C++: static member of template singleton class doesn't get compiled/linked | I implemented a singleton class in c++ using double checked lock(with safe locks), it works. Then I try to convert it into template version, like this:
// singleton.h
#include <atomic>
#include <mutex>
template<typename T>
struct singleton {
~singleton() {}
static singleton<T>* getInstance(std::mutex& m);
s... | Don't try to explicitly specialize the static data member, just define it for the primary template itself (in the header file):
template<typename T>
std::atomic<singleton<T>*> singleton<T>::m_instance{nullptr};
Alternatively mark m_instance in the class template definition as inline (since C++17) and add the {nullptr}... |
73,843,748 | 73,843,774 | C++ Call of overloaded function is ambiguous | I am trying to make a code applying function overload.
The two functions are supposed to be distinguished by the type of input and output variables. (The user either inputs an element symbol (std::string) and gets the atomic number (int) or vice-versa).
I tried to apply this to my code, but I get the error message that... | Your problem is that you declare the functions in the namespace excercises, then you add using namespace exercises;, after that you declare them again in the default namespace. Due to the using-directive, the compiler does not know, which version of the declaration to refer to, the ones declared inside the namespace or... |
73,844,329 | 73,844,375 | c++ using static member as singleton instance leads to different object | I expected that, when we define a static member as singleton's instance, the getInstance() should always return the same object address, so I tried:
struct singleton {
static auto& getInstance() {
static auto instance = std::make_unique<singleton>();
return *instance;
}
};
int main() {
auto ... | The class has implicitly synthesized copy constructor singleton::singleton(const singleton&) that is used when creating inst2.
//this is copy initialization
auto inst2 = singleton::getInstance(); //works because of accessible copy ctor
Same goes for inst1.
You can use auto& to create an lvalue reference(alias) or make... |
73,844,762 | 73,844,953 | Move sematics in functions could have a lot of options | Is there a cleaner way? C++ | Move sematics in functions could have a lot of options | Is there a cleaner way? C++
Say we have a function append with key and value as parameters. Then I currently would have to define 4 functions to enable move sematics. So for two parameters this is still doable. Though sometimes a function that requires move semat... | Yes, there are forwarding references that can accept both lvalues and rvalues. Something like this:
#include <concepts>
#include <utility>
template <typename K, typename V>
struct A
{
template <std::convertible_to<K> A, std::convertible_to<V> B>
void append(A &&a, B &&b)
{
K key = std::forward<A>(a... |
73,845,721 | 73,845,749 | Is conversion function returning an rvalue considered during initializing const lvalue references? | struct A {
};
struct B{
operator A() {};
};
int main(){
B b;
const A& a = b; // OK
}
The rules governing reference initialization can be found in [dcl.init.ref]/5:
A reference to type “cv1 T1” is initialized by an expression of type
“cv2 T2” as follows:
(5.3) Otherwise, if the initializer expression
(... |
Assuming I am correct at this point, I will continue.
Don't continue. You can't know that the initializer expression is convertible to cv3 T3 via a conversion function before knowing what cv3 T3 is. In other words, to check to see if the initializer expression is convertible to cv3 T3, you have to invoke [over.match.... |
73,846,064 | 73,846,244 | Is there a simple way of refactoring this code? | I have a function that have very similar repeating code. I like to refactor it, but don't want any complex mapping code.
The code basically filter out columns in a table. I made this example simple by having the comparison statement having a simple type, but the real comparison can be more complex.
I am hoping there m... |
Is there a simple way of refactoring this code?
As far as I understood your algorithm/ intention, using std::erase_if (c++20) you can replace the entire while loops as follows (Demo code):
#include <vector> // std::erase_if
std::vector<MyRecord*> // return by copy as filterList_ is local to function scope
Find(bool*... |
73,846,400 | 73,846,574 | Function that worked before has stopped working | Essentially, the code is meant to validate, find the manufacture origin, and manufacture date of a vehicle using the VIN number. I had written the "valid" function first and after it worked I moved onto the "origin" and "year" functions. Once they worked, I tested everything together and suddenly the "valid" function w... | As people have commented, you are mixing styles of fail checks with pass checks. It's good to pick one style, and then you can simplify the logic. Here is an example of all fail checks.
bool valid(char vin[])
{
bool result = false;
long long length = strlen(vin);
if (length != 17)
{
return f... |
73,846,494 | 73,846,606 | yaml-cpp error while converting Node to a std::string | I want to convert a Node object from yaml-cpp to a std::string. I keep getting an error that says it cannot find the right overloaded operator <<.
Here's my code:
#include <iostream>
#include <string>
#include <yaml-cpp/yaml.h>
using namespace std;
int main(int argc, char* argv[]) {
YAML::Node myNode;
myNode[... | Actually needed to create an stringstream and then convert it to an normal string:
#include <iostream>
#include <string>
#include <yaml-cpp/yaml.h>
using namespace std;
int main(int argc, char* argv[]) {
YAML::Node myNode;
myNode["hello"] = "world";
stringstream myStringStream;
myStringStream << myNo... |
73,846,836 | 73,847,760 | How to access inherited class attribute from a third class? | The goal of the code structure below is to be able to store pointers to objects of any class inherited from 'A'.
When I run this code, I get 0 written out, but what I'm trying to access is the 'B' object's 'num' value, which is 1. How can I do that?
As far as I know, when you create an inherited class's object, you cre... | Your array is a red herring. You are only using one pointer. Might just as well have it as a member for the sake of the example.
I suppose you might need something like this (note, untested code).
#include <memory>
#include <iostream>
class A {
public:
A() : m_num(0) {} // use this instead of assignment in the c... |
73,847,928 | 73,848,193 | VS Code Error when compiling C++ Program: 'cmd' is not recognized as an internal or external command | I attempted to follow through on VS Code's method on making C++ code work on their editor. I did this successfully on my laptop but when I tried compiling it, I was met with the error:
* Executing task: C/C++: g++.exe build active file
Starting build...
C:\msys64\mingw64\bin\g++.exe -fdiagnostics-color=always -g "C... | I am not sure what I poked into place or if I just was too incompetent to realize something, however adding %SystemRoot%\system32 to my PSModulePath environment variables somehow fixed the issue, and since that action I have yet to replicate the compile error.
I don't know if adding that variable to my environments per... |
73,848,166 | 73,848,187 | Calculate amount of coins | I have the assignment from ZyLab
Given six values representing counts of silver dollars, half dollars, quarters, dimes, nickels, and pennies, output the total amount as dollars and cents. The variable totalAmount is used to represent the total amount of money.
Output each floating-point value with two digits after the... | Your variables should be of type float.
Rewrite your code as following:
float dollars;
float halfDollars;
float quarters;
float dimes;
float nickels;
float pennies;
When you are converting for example half dollars, 3 half dollars * 0.5 is 1.5, but it can't be stored inside integer variable, so you need the variable to... |
73,848,318 | 73,864,137 | Gstreamer webrtcbin not connecting with appsrc | I am trying to establish a webrtc videostream with Webrtc. My code works well with videotestsrc. The webrtc handshake is stablished and the video is displayed.
pipeline = gst_parse_launch
("videotestsrc ! queue ! "
"vp8enc ! rtpvp8pay ! "
"application/x-rtp,media=video,payload=96,encoding-name=VP... | Pushing an initial empty frame after the pipeline setup solved the problem and the handshake was performed afterwards
GstBuffer* buffer = gst_buffer_new_and_alloc(1280 * 960 * 3);
GstFlowReturn flow_return = gst_app_src_push_buffer((GstAppSrc*)appsrc, buffer);
|
73,849,120 | 73,849,408 | How do I remove the extra space on the output from this method | I'm trying to solve this question below:
Write code to read a list of song durations and song names from input. For each line of input, set the duration and name of newSong. Then add newSong to playlist. Input first receives a song duration, then the name of that song (which you can assume is only one word long).
Inpu... | On this statement:
cin >> songDuration;
Reading stops when a non-digit character is encountered, such as the whitespace following the number. The whitespace is left in the input buffer for subsequent reading.
Then this statement:
getline(cin, songName);
Reads from the input buffer until a line break is encountered. A... |
73,849,524 | 73,849,566 | template function specialization using variadic arguments | I have a class that takes a variable number of arguments (including no arguments) but when I try to pass a struct as argument for its constructor, I get a compile time error:
error: converting to 'const ioPin' from initializer list would use explicit constructor 'ioPin::ioPin(Args ...) [with Args = {gpioPort, gpioMode,... | {.port = gpioPort::A, .mode = gpioMode::output, .state = pinState::high }
This is a braced initialization list, of some unspecified type. It needs to be bound to a specified type. This needs to specify, in some way: "Hello, I'm class X, or class Y".
If this gets passed in as a parameter to some function that's declare... |
73,850,916 | 73,851,136 | Obtaining 17 digits precision of Julian datetime in C++ | I am trying to convert some JavaScript code to C++ for obtaining Julian datetime with 17 digits precision. The JS code is able to give me this precision, but its similar code in C++ is not giving value more than 7 digits. This 17 digit precision is absolutely needed because it helps to find Altitude and Azimuth of cele... | At first look, I see three issues here:
Your Julian Date is a floating point number, so the result of your function should be double, not uint64_t which is an unsigned integer;
You want t / 86400000 to be a floating point division, not an euclidian one which discards the fractional part. There are several ways to do ... |
73,851,075 | 73,851,372 | Reading an array of bytes into UTF-16 characters on a machine with a specific UTF-16 character size | I have a question about utf16_t character interaction and SHA-256 generation with OpenSSL.
The thing is, I'm currently writing code that should deal with password hashing. I've generated a 256-bit hash, and I want to throw it into the database in a UTF-16 encoded character field. In my C++ code, I use char16_t to store... | SHA256 generates 256 essentially random bits (32 bytes) of data. It will not always generate valid UTF-16 data.
You need to somehow encode the 32 bytes into more-than-32 utf-16 bytes to store in your database. Or you can convert the database field to a proper 256-bit binary type
One of the easier-to-implement ways to s... |
73,851,461 | 73,851,662 | How does std::weak_ptr store its "use_count" information? | I tried to understand the principle behind weak_ptr's implementation, especially about ref-counting.
The cppreference https://en.cppreference.com/w/cpp/memory/weak_ptr says weak_ptr works as an observer of shared_ptr, declaring weak_ptr doesn't change the use_count of original shared_ptr. Then my question is, how is we... |
I tried to understand the principle behind weak_ptr's implementation
Take one implementation and observe it. For example on libstdc++ the class __weak_ptr contains https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/bits/shared_ptr_base.h#L1974 the pointer to memory and the counter:
template<typena... |
73,852,076 | 73,852,128 | Convert .txt file from CRLF to LF and back | I want to write a little function that takes a file as input, and writes to an output file with the following changes:
If the input file uses CRLF (\r\n) as EndOfLine, it should be replaced with only LF (\n).
If it uses LF (\n), those should be replaced with CRLF (\r\n)
See this post for a bit more info on this.
Here... | When you open a file in text mode, the input stream will already convert line endings. Open the file in binary mode if you want full control.
input.open(location, std::ios::binary);
output.open(location, std::ios::binary);
|
73,852,118 | 73,852,252 | Define object and pass by reference inside function parameter | Lets say we have a function called foo that gets a pointer to some object.
void foo(int *i){
// Some code
}
We can call this function the following way:
int i;
foo(&i);
Is there a way we can make the above snippet in one line in c++? Something like
foo(&int(4)) // This is invalid.
Two limitations:
Changing foo ... | "Doing all in one line" is usually not something desirable, because it does not make code more clean or more readable. If you have to declare an int and take its address, your code better expresses that explicitly.
However, the usual way to encapsulate common tasks is functions:
void foo_wrapper() {
int i = 0;
... |
73,852,755 | 73,859,708 | Accessing members of structs using dot or arrow notation | I was wondering what the pros and cons were or accessing members of a struct using the notation mystruct.element1 rather than mystruct->element1.
Or rather is it better or worse to define structs as pointers or not, i.e.
structtype * mystruct; or structtype mystruct;
In my code, I would be wanting to pass various str... | it depends on the case , creating a pointer of type structtype will come good in some cases where the memory space is critical.
look as for example in the next code:
#include <iostream>
using namespace std;
struct structtype {
double element0;
int element1;
int element2;
};
structtype mystruct;
void func... |
73,852,792 | 73,913,152 | send and format image data form node.js to node c++ addon problem? | how to convert info[0] to uchar array??
js "uint8clampedarray"
->
info Nan::FunctionCallbackInfo<v8::Value>
info[0] class v8::Local<class v8::Value>
->
uchar data[]
->
cv::Mat or ZXing::ImageView
need use image uchar data[];
->
DecodeBarcodes(cv::Mat)
or
ZXing::ReadBarcodes(ZXing::ImageView, {})
get qrcode detect resu... | Nan::TypedArrayContents<uchar> contents(info[0]);
if (contents.length() < min_length) printf("not good\n");
uchar *data = *contents;
And of course you will need to protect it from the garbage collector if you are going to be using this data after you have returned to your JS caller.
|
73,854,336 | 73,855,550 | Template resolution with template template parameter | I'm trying to implement a "decoder" which can treat input data differently depending on the expected return type.
The following code seemed to work in https://cppinsights.io/:
#include <cstring>
#include <vector>
template<template <class, class> class V, typename T>
void Bar(V<T, std::allocator<T>> &v, char** c) {
... | I believe the issue is inside Foo. You're calling Bar<T> which is explicitly saying use the Bar that takes a single template argument. IE, you're making sure the template template specialization never gets selected. Instead, let it auto-deduce.
This worked for me: https://godbolt.org/z/14h1fdTMT
template<typename T>
T ... |
73,854,659 | 73,869,422 | std::source_location - filename only, not full path - compile-time substring? | Is there any way to make a substring at compile time, and NOT store the original string in the binary ?
I'm using std::experimental::source_location, and really only need the filename, and not the full path, which ends up taking lots of space in the binary
Here's an example:
#include <iostream>
#include <experimental/s... | Based on this, I ended up using the __FILE__ macro combined with the -fmacro-prefix-map compiler option, instead of source_location.
So I essentially use the following code
#include <cstdio>
#include <cstdint>
#define ERROR_LOG(s) log_impl(s, __FILE__, __LINE__);
void log_impl(const char* s, const char* file_name, uin... |
73,854,795 | 73,857,201 | Catch2: Test all permutations of two lists of types | I need to write some unit tests in Catch2 where each test case should be executed for each possible permutation of two lists of types. I'd love something like
// Some types defined in my project
class A;
class B;
PERMUTATION_TEST_CASE ("Foo", (A, B), (float, double))
{
TestTypeX x;
TestTypeY y;
}
Where the test... | You can create the Cartesian product of type list, and then:
using MyTypes = cross_product<type_list<A, B>, type_list<float, double>>::type;
// using MyTypes = type_list<std::pair<A, float>, std::pair<A, double>,
// std::pair<B, float>, std::pair<B, double>>;
TEMPLATE_LIST_TEST_CASE("some_name... |
73,854,824 | 73,868,691 | CreatePKCS10CSR soap message in c++ | I should give a signing request to a device with soap message. I included in my soap the following messages:
http://www.onvif.org/ver10/advancedsecurity/wsdl/advancedsecurity.wsdl
and I built my c++ project with VS2019 in Windows x64.
Now I'm trying to send a CreatePKCS10CSR with no success.
#include "soapKeystoreB... | This code solve my question. In my previous code I forgot to declare the soap endpoint of remote device service. I also use a different authentication method.
deviceKeyStoreBindingProxy = new KeystoreBindingProxy();
soap_register_plugin(deviceKeyStoreBindingProxy, soap_wsse); //NOTE THIS LINE
deviceKeyStoreBindingPro... |
73,856,707 | 73,857,303 | When would you use optional<not_null<T*>> | I was reading References, simply and got to the part talking about using optional references. One of the reasons Herb gives to avoid optional<T&> is because those situations can be "represented about equally well by optional<not_null<T*>>"
I'm confused about when you would ever want optional<not_null<T*>>. In my mind, ... | T* doesn't have any member functions, whereas optional<not_null<T*>> has a bunch.
What I'd like is to be able to compose functions like
auto result = maybe_A()
.transform(A_to_B)
.and_then(B_to_opt_C)
.or_else({});
which should be equivalent to
optional<A&> first = maybe_A();
optional<B&> second = first.tr... |
73,857,103 | 73,857,239 | ssh_connect: Library not initialized (LibSSH) | I have the following piece of code which I am trying to build statically, so I end up with a single executable.
#define LIBSSH_STATIC 1
#include <libssh/libssh.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <errno.h>
#include <string.h>
#pragma comment(lib, "mbedcrypto.lib")
#pragma comm... | 3 days spent on guessing instead of reading the manual - it's unbelievable. Almost on the top:
If libssh is statically linked, threading must be initialized by calling
ssh_init() before using any of libssh provided functions. This initialization
must be done outside of any threading context. Don't forget to call
ssh_... |
73,857,682 | 73,857,785 | Member method calls virtual method with same name but different signature | I have the following Header/Source files:
// foo.h
#ifndef __FOO_H
#define __FOO_H
#include <map>
#include <stdexcept>
template <typename T>
class FooBase {
public:
std::map<float,T> a;
FooBase(std::map<float,T> a_) : a(a_) {};
T func(float x1, T fallback) const;
virtual T func(float x1) const = 0;
}... | Foo::func hides FooBase::func. You can use using to pull FooBase::func into Foos scope:
class Foo: public FooBase<float> {
public:
Foo() : FooBase<float>({}) {};
float func(float x1) const;
using FooBase<float>::func;
};
Live Demo
Alternatively you can explicitly pick FooBase::func to be called:
void test_... |
73,858,200 | 73,859,841 | STM SPI receive syntax | I have done some searching and found many questions, but am not coming to a correct conclusion. To start with the hardware design:
the STM32 is a host MCU for a SI4362 RX only radio that uses spi for communication. i have hard coded all the radio power up commands, and as written in the API for the SI4362:
To apply a... | Double checking a few datasheets it would seem that i wasnt getting the first SPI command input within the time recommended. here is updated code. now i need to verify what im sending and receiving, so i will have to figure out the USART now to make that work. i feel that it will require a different question altogeth... |
73,859,871 | 73,911,057 | cmake add an optional dependency to a static library without forcing consumers to depend on its depencdencies | I have a static library built using cmake and I'm trying to integrate it to vcpkg. The library has some wrappers for things like ssl using openssl and sqlite databases but they are optional and not required to used other parts of the library. The source files looks like this:
include:
core.h
ssl.h
sql.h
src:
core.cpp
... | The way I got around this problem is by dividing the library into several libraries and link the required components per application demand.
I am not an expert in cmake so I used the template from this repo to get it: https://github.com/ClausKlein/cmake-example-component-lib
|
73,859,947 | 73,860,030 | Is there a way to initialize members of a function to a none value to class member without default constructors? | I have some classes, having some members:
#include <variant>
class A {
public:
A() {};
private:
B b;
std::variant<B, C> var;
};
class B {
public:
B(C c) : c(c) {};
private:
C c;
};
class C {
public:
C(int val) val(val) {};
private:
int val;
};
Now, this does of course n... | You can use std::monostate in your variant until you've selected what type to store in it.
std::monostate:
Unit type intended for use as a well-behaved empty alternative in std::variant. In particular, a variant of non-default-constructible types may list std::monostate as its first alternative: this makes the variant... |
73,860,081 | 73,860,324 | C++ Command Line Arguments | I'm learning C++ for school and I'm confused on how to integrate command line arguments into my code
int n = 1;
int c = 0;
n = argv[1];
c = int(argv[2]);
findPrimes(n, c);
return 0;
}
That's my main function so far, but n = argv[1]; is a type error, and c = int(argv[2]); is a loss of data erro... | To convert a char* string into an int, you can use the C library atoi(), sscanf() or other equivalent function:
#include <cstdlib>
int n = std::atoi(argv[1]);
#include <cstdio>
int n;
std::sprintf(argv[1], "%d", &n);
Or, you can use the C++ std:stoi() function:
#include <string>
int n = std::stoi(argv[1]);
Or, th... |
73,860,201 | 73,860,590 | Why in this simple math problem in c++ the result is different depending on the place of the float? I want to know the logic behind it | #include <iostream>;
using namespace std;
/* this one works out when the float of the pi & area are in the end, but when it's in the top it does not work? */
int main()
{
float a, b;
/* float pi = 3.14 ;
float area = (pi*b*b/4) * ((2*a-b) / (2*a+b)); if it's in here it doesn't work */
cout << "please int... | The area gets set depending on the values currently in the variables used in the expression.
With the expression at the top, neither a nor b have been set to your input values. Instead they will have some arbitrary value, meaning your area will also have some arbitrary value. With the expression after the input of a an... |
73,860,553 | 73,864,382 | Problem with RHEL 5.5 compilation on Windows Host (Docker) | I have a 64 bit Windows host machine, I have installed WSL (Debian), then docker, and then I'm trying to compile a Qt project on a Red Hat Linux 5.5 32 bit container(sharing a host directory with the code), but... doing the QMake...
/usr/local/Trolltech/Qt-4.8.3/bin/qmake MYFILE.pro -spec linux-g++ -r CONFIG+=debug
I... | I found a solution.
It's a filesystem problem. I moved "E:\codeRepo" to "\\wsl$\Debian\codeRepo" (WSL filesystem as a network drive in windows) and it works.
Now i'm sharing with the docker an ext4 folder and there is no problem with QMake.
So, this doesn't works:
docker run -it -v E:\codeRepo:/root/codeRepo rhl55 sh /... |
73,860,625 | 73,860,683 | Iterate tuple with "break" or "return" in loop | I have a tuple of Args generated from a function signature.
I want to iterate the tuple and check if the argument is a specific type, and return a string if it isn't.
So I came up with the following code:
std::tuple<Args...> arguments;
Object* runtime_arguments = new Object[N];
fill_args(runtime_arguments, N);
auto is... | Fold over a short circuiting operator (In this case, &&):
bool is_valid_arguments = std::apply([&runtime_arguments](auto... arguments) {
std::size_t i = 0;
return ([&]{
std::string error;
return is_valid_type<decltype(arguments)>(runtime_arguments[i++], error);
}() && ...);
}, arguments);
Y... |
73,861,040 | 73,861,380 | Does boost.asio's ssl::stream encrypt messages? | I'm connecting a server and client using boost.asio's ssl facilities. I create a boost::asio::ssl::stream, load up a self-signed certificate on the server and client, load the certificate's private key on the server, and successfully perform the handshake().
I believe now that boost::asio::ssl::stream::write_some() (an... | Yes. It encrypts the messages but only in transit. That's what transport encryption means.
It wouldn't be in the documentation, because it's a property of SSL/TLS which does document it.
In fact the stream's read/write operations are invalid to use before handshake or after shutdown.
To learn more about SSL: https://e... |
73,861,742 | 73,861,934 | C++ Input Validation for Whole Number. The input for num should not be a char/string, a decimal value, or a negative number | for some reason this only gets validation for char/string.
How to make it validate negative and decimal values?
cout << "Please enter a whole number: ";
while (!(cin >> num || num < 0)){
cin.clear();
cin.ignore(10000, '\n');
cout << "Invalid! A whole number is positive and an integer. \n";
cout << ... | there are some problems with your code :
no need to write cin >> num 2 times , it's only enough to get the input only once in the condition of the while loop
it's not !(cin >> num || num < 0) , it's !(cin >> num) || num < 0 as !(cin >> num) will report the input of string while num < 0 will report the input of negativ... |
73,861,961 | 73,876,515 | All elements in a struct pointer vector seem to be the same as the last element C++ | Why is every element in my struct* vector exactly the same as the last element that is pushed. Everything works its just when I go to push_back the struct object* but when I iterate through it after it always comes out as the last element that was pushed.
(Each Entity* Name Element Before Push)bot 0 bot 1 bot 2 bot 3 b... | Make the Name member of the Entity struct non static.
Section $9.4.2/1 from the C++ Standard (2003) says,
A static data member is not part of
the subobjects of a class. There is
only one copy of a static data member
shared by all the objects of the
class.
|
73,862,289 | 73,862,372 | Removing lowest grade and averaging. C++, VS | I'm not sure what I'm doing wrong, I have been working on this code for some time, I need to remove the lowest grade (64) and then take the average and output the grade. My code works but my average isn't correct. it is supposed to be 90.09 and not 92.4. can someone look at my code and help me fix this?
The grades are ... | In this line:
while (fin >> score){
You read the next score from the file.
But 2 lines afterwards after incrementing count you read another score with:
fin >> score;
This line is overriding the value just read from the file (in the while(...)), causing you to actually skip the 1st, 3rd, 5th etc. scores.
You can obse... |
73,863,161 | 73,863,490 | a code piece from MLIR that make me confused | There is a code piece from the llvm-project/mlir/lib/IR/Dialect.cpp
void DialectRegistry::insert(TypeID typeID, StringRef name,
const DialectAllocatorFunction &ctor) {
auto inserted = registry.insert(
std::make_pair(std::string(name), std::make_pair(typeID, ctor)));
if (!inserted.... | Taking a closer look at what the first entry of the return value of std::map::insert is:
1-3) Returns a pair consisting of an iterator to the inserted element (or to the element that prevented the insertion) and a bool denoting whether the insertion took place.
(Emphasis added.)
If the insertion fails because an elem... |
73,863,315 | 73,863,408 | Why is "sizeof(unsigned int) == sizeof(int)" refused in a cout? | Why can I write:
bool a = sizeof(unsigned int) == sizeof(int);
cout << "(taille unsigned integer = integer) ? " << a;
But this:
cout << "(taille unsigned integer = integer) ? " << sizeof(unsigned int) == sizeof(int);
produces a compilation error?
Invalid operands to binary expression ('std::basic_ostream<char>::__ost... | This is an issue of operator precedence. The << operator has higher prcedence than ==, so your expression is parsed as
(cout << "(taille unsigned integer = integer) ? " << sizeof(unsigned int)) == (sizeof(int))
Since the ostream << operator overloads return the ostream they're called on, you're trying to compare a s... |
73,863,706 | 73,863,717 | std::cin>> is digit or string | I have to determine if the input is a digit or a string.
std::string s;
while (std::cin >> s) {
if(isdigit(s)){
//do something with the variable
}
else{
//do something else with the variable
}
}
For this I get
error: no matching function for call to 'isdigit(std::__cxx11::string&)'
Cou... | isdigit() works on a single character (and indicates if it is a numerical value between '0' and '9'). To check to see if you have a single digit:
std::string s;
while (std::cin >> s) {
if(s.size() == 1 && isdigit(s[0])){
//do something with the variable
}
else{
//do something else with the ... |
73,864,651 | 73,864,747 | Does any of C++ smart pointers avoid data race in strict sense? | For consumer/producer model there is a built-in mechanism to avoid data race - queue.
But for global flag there seems not yet a ready-to-go type to avoid data race rather than attaching a mutex to each global flag as simple as boolean or int type.
I came across shared pointer. Is it true that as one pointer operates on... |
For consumer/producer model there is a built-in mechanism to avoid data race - queue.
The standard library has no thread-safe queue. std::queue and others cannot be used without explicit synchronization in multiple threads.
I came across shared pointer. Is it true that as one pointer operates on that variable, anoth... |
73,865,070 | 73,865,177 | How to overload an iterator so it can be incremented in a dereferenceable state? | to give context i'm trying to re-implement vector container, and while reading about it's iterator system requirements, i've stumbled upon this requirement from cplusplus reference:
can be incremented (if in a dereferenceable state ). the result is either dereferenceable or past-the-end iterator.
EX: ++a , a++, *a++
... | You cannot increment an end iterator, it is not dereferenceable. You cannot increment an invalid iterator, it is not dereferenceable.
Preconditions do not necessarily mean that you have to do something extra. They only give information when some operation, here increment, is defined.
For example
std::vector<int> foo;
... |
73,865,205 | 73,881,146 | Correct implementation of copy constructor for allocated pointers | I have a class, which contains some allocated pointers (reduced to 1 in the example),
and I would like not to have to deep copy when the copy operator is
called. The class is the following:
class Example {
public:
Example() : ptr1(0), len1(0) {}
Example(const Example& other) : ptr1(0), len1(0) {
if... | Having seen your comment, here is one alternative not included in The Dreams' answer. The simplest way out, as suggested by Sebastian's comment, is to just treat Example as not owning its data at all:
struct Example {
char* ptr1 = nullptr;
int len1 = 0;
};
Since this has a default destructor and copy/move func... |
73,865,301 | 73,866,881 | How to find minimum value from vector with some condition? | I need to get the min element value (x) in a vector.
Given the index i of x, I need to check if flag[i] == 0 to return i.
I don't want to sort or discard any value because I need its ordinal number, I need the vector to hold its "structure".
How can I get the index of that minimum element?
A = {1, 2, 3, 4, 0, -1}
fl... | You can have a filter view of A with only the elements where flag is 0, and pass that to std::ranges::min.
With C++23 range views:
namespace views = std::ranges::views;
// min is undefined if passed an empty range
assert(std::ranges::any_of(flag, [](auto f){ return f == 0; });
auto value = std::ranges::min(views::zip(A... |
73,865,323 | 73,865,436 | Extracting the value of a variant to a superclass | Consider the following classes
class A {
public:
virtual std::string to_string() = 0;
};
class B : public A {
public:
std::string to_string(){
return "B";
}
};
class C : public A {
public:
std::string to_string(){
return "C";
}
};
class D {};
Now I will have a varian... | You were close with std::visit, not sure what the error is exactly but I would recommend using a lambda instead of a custom struct:
int main(){
std::variant<B*, C*> bc;
bc = new C();
A* a = std::visit([](auto&& e)->A*{return e;},bc);
a->to_string();
}
The above will compile iff all variants can be cast... |
73,865,367 | 73,868,588 | How are C++20 modules compiled? | Some sources say that compilers parse modules and create an abstract syntax tree (AST), which is then used when parsing all code files that import the module. This would reduce the amount of parsing the compiler has to do as opposed to when #including headers, but everything would still have to be compiled once for eve... | The products of module compilation are implementation dependent. But broadly speaking, they are whatever the compiler needs them to be to make module inclusion efficient. That is, after all, the whole point of modules. When building a module interface, the compiler has 100% of the information it needs to have to make i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.