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,202,845 | 73,203,070 | Can I use return from a coroutine when calling another coroutine? | Suppose that I have the followings:
Task<int> A() { co_return 1; }
Task<int> B() { co_return co_await A(); }
Task<int> C() { return A(); }
Both B and C compile just fine. So I'm leaning towards using return since it looks simpler but it feels awkward to not use co_return from a coroutine. What's the best practice?
| Well, C is not really much of a coroutine, is it? It just returns one. Well, all coroutines in C++ are like that from outside, I like that design choice. In Python, you would have to mark B as async and could not mark C as async (or you would have to await it twice).
Next, B is not exactly the same because you "unwrap"... |
73,202,902 | 73,203,012 | Parallel execution taking more time than serial | I am basically writing code to count if a pair sum is even(among all pairs from 1 to 100000). I wrote a code using pthreads and without pthreads. But the code with pthreads is taking more time than the serial one. Here is my serial code
#include<bits/stdc++.h>
using namespace std;
int main()
{
long long sum = 0, cou... | The all cores in the threaded version compete for cnt[].
Use a local counter inside the loop and copy the result into cnt[t] after the loop is ready.
|
73,203,313 | 73,203,426 | MoveFile function convert syntax / how to use MoveFile with variables to rename folders | This part of my programm tries to rename all folders and subfolders. All other functionality is in another code, here I'm just renaming a single folder by providing a path.
Since rename doesnt seem to work for me I tried using MoveFile.
I understand that it requires an LPCTSTR value.. but the paths I am currently provi... | You can't type cast a std::filesystem::path object directly to a character pointer. That is exactly what the error message is telling you.
And you can't use the L prefix with variables, only with compile-time literals.
You need to call the path::c_str() method instead, eg:
MoveFileW(std::filesystem::path(dirEntry).c_st... |
73,203,586 | 73,203,748 | Recursive binary search errors in c++ | I'm trying to write a recursive binary search function using below approach. I'm basically using divide and conquer strategy and everything looks good to me in code, but unable to figure out where my code and approach goes wrong.
#include<iostream>
using namespace std;
bool b_search(int *arr, int n, int start, int end)... | When arr[mid]>n you then search for the number in the part with higher number which is guaranteed to miss. You need to search in the part with lower numbers.
Example:
bool b_search(int *arr, int n, int start, int end) {
if (start == end) return arr[start] == n;
int mid = start + (end - start) / 2;
if (arr... |
73,203,635 | 73,215,915 | How to add custom library to docker image | There is remote server with gitlab runner and docker. I need to build c++/qt project on it, but i should use custom qt libraries(they built with deprecated webkit). I have them on local pc. How can i create docker image with this specific libraries? Is it ok to use COPY command for this purpose?
| Yes, you can certainly use COPY from your local machine.
However, I would make sure that the custom qt libraries are available online on GitHub or so, so that the docker image can be built correctly from anywhere without having to set up every local machine where the docker image is meant to be created.
This way, you c... |
73,203,857 | 73,206,739 | FFmpeg compilation warnings ATOMIC_VAR_INIT | While compiling ffmpeg (commit 1368b5a) with emscripten 3.1.17, there are two warnings, I would like the internet to help me better understand (I am not someone with deep c++ experience):
fftools/ffmpeg.c:339:41: warning: macro 'ATOMIC_VAR_INIT' has been marked as deprecated [-Wdeprecated-pragma]
static atomic_int tran... | For ATOMIC_VAR_INIT I found this note:
This macro was a part of early draft design for C11 atomic types. It is not needed in C11, and is deprecated in C17 and removed in C23.
So, the deprecation was by the C standard (and the C++ standard, though there it was deprecated in C++20)
As for the floating point issue, the ... |
73,204,005 | 73,204,154 | clang: error: unknown argument: '-no_adhoc_codesign' | I'm trying to get rid of linker-signed out of my xxx.dylib. So according to this, I added -no_adhoc_codesign to linker flag with -DCMAKE_SHARED_LINKER_FLAGS="-no_adhoc_codesign" but it seems clang has no idea about this flag. ld does have this option
clang: error: unknown argument: '-no_adhoc_codesign'
/Applications/Xc... | You can use -Wl,-no_adhoc_codesign to pass the option directly to the linker if the compiler doesn't support adding the option itself.
|
73,204,213 | 73,251,314 | C++(MFC) using Pylon :How to draw image which is in array | Hello I am working on a Pylon Application, and I want to know how to draw image which is in array.
Basler's Pylon SDK, on memory Image saving
In this link, it shows I can save image data in array(I guess) Pylon::CImageFormatConverter::Convert(Pylon::CPylonImage[i],Pylon::CGrabResultPtr)
But the thing is I can not figur... | For quick'n dirty displaying of Pylon buffers, you have a helper class available in Pylon SDK to put somewhere in buffer grabbing loop:
//initialization
CPylonImage img;
CPylonImageWindow wnd;
//somewhere in grabbing loop
wnd.SetImage(img);
wnd.Show();
If you want to utilize in your own display procedures (via either... |
73,204,218 | 73,215,326 | Is it allowed to create a `typedef` for a function with attributes? | I have several functions with identical prototypes declared as noreturn. I want to declare a pointer to these functions in a header shared between C and C++.
typedef __attribute__ ((noreturn)) void (*apply_transition_effects_t)(object_t *, data_t *);
I am using GCC's syntax here, but the question applies equally to [[... | Answer applying to C++ (C++20):
__attribute__ is completely a compiler-specific feature that is not covered in any way by the standard. The standard does not say where it may or may not appear. From its point of view this is simply an identifier which is reserved in all contexts and therefore using it in the program ca... |
73,204,678 | 73,204,743 | priority_queue of vectors in increasing order | I'm trying to build a priority_queue of vectors in increasing order of the first element in each vector, in C++. Could someone help me with this? I can use a normal priority_queue with all vector elements in negative sign but is there some other way to do that?
Thanks already :)
| You can pass it a different comparator. The default is std::less, but here you'll want std::greater, for example:
#include <functional>
typedef std::vector<int> ItemType;
std::priority_queue<
ItemType, // Type of items
std::priority_queue<ItemType>::container_type, // Type of ... |
73,206,867 | 73,211,398 | Failed to build capnproto on ARM, test failed | I am trying to build capnproto library for linux arm machine using arm-linux-gnueabihf-clang++ and it builds correctly but because tests is a part of a build it fails to finish build because i am building it on x64 machine for arm platform and capn binary cannot be started on x64 machine because it is compiled for arm.... | When cross-compiling, you need to first build and install Cap'n Proto on the host machine, so that the commands capnp and capnpc-c++ are available on the command line.
Once you've done that, you can cross-compile. Pass --with-external-capnp to ./configure when configuring cross-compiling, to tell it to use the installe... |
73,207,032 | 73,208,027 | Regarding the pause-resume data loss in MSVC std::experimental::generator | Since the std::generator is making it into CPP23, I am playing around with MSVC's incomplete version.
However, I notice that it seems lose exactly one yield when used with std::views::take. Here is the example:
#include <iostream>
#include <ranges>
#include <experimental/generator>
std::experimental::generator<int> G... | std::generator is an input_range, its begin() does not guarantee equality-preserving:
auto Ret = GeneratorFn();
std::cout << *Ret.begin() << "\n"; // 1
std::cout << *Ret.begin() << "\n"; // 2
When your first for-loop finishes, Ret's iterator has already incremented to the value 3. When you apply views::take to Ret in ... |
73,207,457 | 73,207,953 | C++ make a string raw using macros | So to make a string in C++ raw you do
std::string raw = R"raw_string(text_here""n/whatever)raw_string"
but my question is can you make a macro that preprocesses the string ,
so its raw but it looks normal in code?? Like in a function argument
#define start_raw_string R"raw_string(
#define end_raw_string )raw_string"
... | It cannot work like this. Once you passed the string literal to the function it is a std::string not a literal anymore. A string literal is the thing you type in your code. Its not something that you can pass around. Even if you'd pass a char[N] to the function it cannot work. You cannot turn a character array to a lit... |
73,208,959 | 73,215,103 | Vim complete option not worknig | I have complete=.,w,b,u,t,i. Using :h cpt you can find this:
i scan current and included files
I have the below c++ code:
#include <vector>
using namespace std;
int main()
{
vector <int> v;
v.push_
}
When I press C-n in front of v.push_ vim says -- Keyword completion (^N^P) Pattern not found.
How can I fix... | As @romainl pointed out, your path doesn't include your c++ directory in /usr/include/c++/, so you only need to add this directory to your path in your user runtime directory ~/.vim/after/ftplugin/cpp.vim. For example, this should be enough for your purposes as it will read files recursively based on the initial matche... |
73,209,866 | 73,209,944 | How to use std::generate | https://en.cppreference.com/w/cpp/algorithm/generate
states that it takes Parameters
ForwardIt first, ForwardIt last, Generator g
and the description is
Assigns each element in range [first, last] a value generated by the given function object g.
so I declared an Array (std::array) with X Elements, where
std::ge... | You are allowed to form a pointer one past the end of an array, but not dereference it.
For raw arrays, &Arr[X] is defined to be equivalent to &*(Arr + X), i.e. you first dereference, then take the address. Containers define [] in terms of a (hidden) raw array.
Similarly begin() and end() will be something like return ... |
73,210,025 | 74,054,221 | In VSCode, how can I disable the GCC warnings in the problems window (I'm not compiling with GCC and I only use clangd extension) | I'm using CMake with clang to compile.
I'm using only the clangd VSCode extension (i.e., not using any other C++ extensions).
In the "Problems" window, which is powered by VSCode and not compiler output (so there's not an issue with my CMake stuff or compile_commands.json, because I don't even have to compile to see th... | You can use the filter in the "problems" tab. Write clang to remove gcc entries.
|
73,210,092 | 73,308,854 | jthread vs std::async - what is the use-case for jthread over std::async | I have just stumbled accross std::jthread: https://en.cppreference.com/w/cpp/thread/jthread
Which seems to be solving the same problem as std::async/future has already solved (although you may need to force the behaviour of async std::async(std::launch::async, ... to run immediately.
So my question is what is the point... | Abstractly, they are very similar. Assume that one uses std::launch::async and one does not call std::jthread::detach. They both accept synchronous functions and run them concurrently with the current thread of execution. They both provide a way to wait on the completion: std::future::get or std::jthread::join. They bo... |
73,210,968 | 73,211,387 | ComCtl32.dll Ordinal 345 not found error only on Windows XP | I need to make an application that runs on Windows XP and up for multiple reasons. I am using ComCtl32.dll to call TaskDialogIndirect. The only problem is that the error "The ordinal 345 could not be located in ..." only occurs on Windows XP. The program runs fine on all other versions. I do have a manifest in my .rc f... | First of all the minimum supported client requirement for TaskDialogIndirect is Windows Vista you might also wanna check this out.
Your best bet might be XTaskDialog. This serves as a good emulation of the Vista Task Dialog APIs for down level operating systems including Windows 98, Windows ME, Windows 2000, Windows XP... |
73,211,206 | 73,211,525 | What mechanism prevents captured variables from being moved? | I did some further experimentation on the topic of my previous question and have another one.
Consider the code below where, as I expeded, both l_ref are r_ref are const:
#include <string>
#include <iostream>
struct Func
{
void operator()() const
{
static_assert(!std::is_const_v<decltype(v)>);
... | The move and copy constructors are both part of the same overload set. The compiler will either choose the copy or the move constructor according to the value category and const-ness of the arguments.
You second example is wrong and won't compile according to the standard. decltype(l_ref) and decltype(r_ref) are indeed... |
73,211,686 | 73,212,583 | C++20 consteval functions and constexpr variables - are they guaranteed to be evaluated at compilation time? | In C++20, we have the consteval keyword that declares an immediate function. For example:
consteval int f(int x) { return x * x; }
Such a function is required to produce a constant expression. However, according to the standard, a constant expression is not required to be actually evaluated at compilation time, unle... | The standard does not have the concept of "compile time". There is only "constant evaluation" and a "constant expression". Implementations may implement "constant expressions" such that they are evaluated at compile time.
But there is no C++ standard-defined behavior you can point to in the actual C++ program that make... |
73,211,949 | 73,212,387 | how to check if a float number is an integer in cpp? | For example 14.2 is not an integer but 14.0 is an integer in a mathematical perspective. What I've tried to do is the following, let n be a long double, so to check if it's an integer I compared it to its integer form:
if (n == (int) n)
{
// n is an integer
}
It all looks perfect but when I applied it, it didn't ... | The cleanest approach is to use floor() and not concern yourself with casting to integer types which makes the false assumption that there will be no overflow in converting a floating-point value to integer.
For large floats that's obviously not true.
#include <iostream>
#include <cmath> // This is where the overloaded... |
73,212,209 | 73,225,491 | Is there a way to resize a buffer in C++ | I'm a noob to memory management so please forgive me. Say I have the following code:
std::allocator<T> alloc;
T* buffer = alloc.allocate(42);
Is there a good way to "add space" to this buffer, instead of creating a new buffer, allocating more space, copying the old buffer to the new buffer, and then replacing the ol... | Short answer: No.
In general you can't use realloc. The problem is that resizing the buffer may or may not mean allocating a new, larger buffer somewhere else and then it depends on T what you have to do. T may be trivially copyable, in which case realloc would work. But it's unlikely for realloc to actually just grow ... |
73,212,841 | 73,212,998 | Reordering bit-fields mysteriously changes size of struct | For some reason I have a struct that needs to keep track of 56 bits of information ordered as 4 packs of 12 bits and 2 packs of 4 bits. This comes out to 7 bytes of information total.
I tried a bit field like so
struct foo {
uint16_t R : 12;
uint16_t G : 12;
uint16_t B : 12;
uint16_t A : 12;
uint8_t... | If we create an instance of struct foo, zero it out, set all bits in a field, and print the bytes, and do this for each field, we see the following:
R: ff 0f 00 00 00 00 00 00 00 00
G: 00 00 ff 0f 00 00 00 00 00 00
B: 00 00 00 00 ff 0f 00 00 00 00
A: 00 00 00 00 00 00 ff 0f 00 00
X: 00 00 00 00 00 00 00 f0 00 00
Y... |
73,213,232 | 73,215,041 | Why does the impl of shared_ptr ref count hold a pointer to the actual pointed type? | This was motivated by an interview question:
shared_ptr<void> p(new Foo());
Will the destructor of Foo get called once p goes out of scope?
It turns out it does, I had to look at the implementation of shared_ptr in GCC 1, and find out that apparently the control block holds a pointer to the actual type (Foo) and a poi... | A std::shared_ptr<T> instance itself must keep track of the pointer to return when .get() is called. This is always of type T*, except when T is an array, in which case it is of type std::remove_extent_t<T>* (for example, std::shared_ptr<int[]>::get() returns int*).
Also, when a std::shared_ptr<T> is destroyed, it has ... |
73,213,470 | 73,215,851 | QT 6.3 convert QVector to std::vector | I am converting my code from QT 5 to QT 6
https://doc.qt.io/qt-5/qvector.html#toStdVector
I have came across this, when noticing toStdVector() function was removed.
until now I had a line of code like this
collection.dgValues = imageset.digitalGainValues().toStdVector();
I am now suppose to change it into this?
std::... | Yes, you can do that.
However, it is worth noticing that there is no use for QVector anymore since Qt 6 made it an alias to QList, so you should migrate your code away from it.
However, we decided that QList should be the real class, with implementation, while QVector should just become an alias to QList.
Prefer to u... |
73,213,892 | 73,214,965 | How to pass a Smart Pointer in a method without deleting it | I have a program that checks me some tokens, the first time it checks the one with the least HP, the other times it takes one randomly. I thought about transforming this code using the strategy pattern. The code works, but there is a problem: the tokens are cleared
Token
class Token{
private:
string name;
int h... | Here:
if (control == 0) {
strategy = new FirstAttack(std::move(token));
} else {
strategy = new WarStrategy(std::move(token));
}
std::move doesn't do anything, because arrays are passed by pointer.
The move occurs in the strategy constructor for each element:
FirstCase(std::unique_ptr<Token> pieces[3]){
fo... |
73,213,990 | 73,214,048 | Why r-value becomes l-value? | Due to the fact that the general question "how std::forward works" is too complicated I decided to start with a question on a particular example:
#include <utility>
#include <iostream>
namespace
{
void foo(const int&)
{
std::cout << "const l-value" << std::endl;
}
void foo(int&)
{
... | The thing that everyone seems to be confused about when being introduced to this is that value category is not a property of an object, variable or other entity. It is not part of a type or anything, which makes it confusing because we also talk about lvalue references and rvalue references which are distinct concepts ... |
73,214,155 | 73,214,270 | How can I define different struct members for different template parameters? | How can I define different struct members for different template parameters? I've tried to use the requires keyword the following way:
template<typename T> requires std::is_void_v<T>
class Foo
{
public:
void Bar()
{
}
};
template<typename T>
class Foo
{
public:
T* Bar()
{
if (!m_T)
... | While requires may be useful in general, its advantages for exactly matching one template parameter type are outweighed by the negatives.
Template specialization of types has been possible since C++03, maybe even C++98:
template<typename T>
class Foo;
template<>
class Foo<void>
{
public:
void Bar()
{
}
};
... |
73,214,824 | 73,215,245 | Missing CMAKE_ASM_NASM_COMPILER when compiling gRPC with MS visual studio | I am trying to build gRPC C++ (1.48.0) with Visual Studio 2022 on Windows 10. It's a CMake build (cmake 3.22.22011901-MSVC_2)
I was able to build everything else but am stuck at BoringSSL. The relevant CMakeList is trying to enable_language(ASM_NASM). Context below:
if(NOT OPENSSL_NO_ASM)
if(UNIX)
enable_language... | To answer at least some of my questions for my future self, and others who are at a similar point in the journey.
NASM is an assembly compiler (assembler). BoringSSL has some assembly language code, which is why it needs an assembly compiler (and gRPC or other modules don't). I'll let someone else opine on why NASM and... |
73,215,242 | 73,215,255 | Default member variables in defaulted copy/move constructors | What exactly occurs to a member variable with a default value, during a defaulted copy/move construction? As so:
struct A {bool a = true;};
A x;
x.a = false;
A y = x;
I can imagine a few different ways this works, equivalently written as
struct A {bool a;}; //no default
//option 1
A::A(const A& other) noexcept : a(o... | A constructor must and will always initialize all the class data members.
Default initializers will be used in constructors where that data member isn't explicitly initialized. The default copy constructors will initialize each data member with a copy of the corresponding data member from the copied object, so default ... |
73,215,417 | 73,215,418 | CMake Treat Warnings as Errors | How can I configure CMake to treat compiler warnings as errors during the build?
I am aware of the possibility to manually configure command line options for the compiler like -Werror through commands like target_compile_options, but I would prefer a portable solution that does not require fiddling with tool-dependent ... | This can be configured in CMake version 3.24 and higher via the COMPILE_WARNING_AS_ERROR target property.
For example, to enable warnings as errors for the my_app target you could write:
set_property(TARGET my_app PROPERTY COMPILE_WARNING_AS_ERROR ON)
You can also set a global default for all targets in your project v... |
73,215,454 | 73,215,486 | Why is this map returning an rvalue? | I am using the library nlohmann/json and wish to create an unordered_map of std::string to nlohmann::json.
#include <nlohmann/json.hpp>
class basic_container {
public:
using key_type = std::string;
using mapped_type = nlohmann::json;
using container_type = std::unordered_map<key_type, mapped_type>;
usi... | Your wrappers for at(), et. al. are returning the wrong thing.
If you look up the reference for unordered_map::at(): it returns a reference to a (const) T, a.k.a. value_type, a.k.a. your mapped_type.
reference/const_reference is something completely different.
The same problem also happens with your operator[] overload... |
73,215,750 | 73,233,765 | C++ Functions return or global | im struggleling with some "best practice" idea's
only posting a small piece of the code the original is very and complicated.
See below a litte test function
TEST1 runs in 5ms
TEST2 runs in 1405ms
to me TEST2 feels like the best practice but the performace diffence are so big!
in the my full code the Functions are in t... | Your code has some code smell:
vector<double> TESTFUNTC2A(int ID) {
vector<double> TEST124(12);
for (int x = 0; x < 12; x++) {
TEST124[x] = 1.123;
}
return TEST124;
}
You create TEST123 with size 12 and initialize every element to 0.0. Then you overwrite it with 1.123. Why not just write vector... |
73,216,135 | 73,216,203 | Passing class as a parameter c++ | im new to programming and just start learning C++ a few weeks, im current doing the random number stuff, but i don't understand why the parameters sometime has "()" and sometime doesn't, hope someone can explain to me, thanks!.
int main()
{
random_device rd;
mt19937 rdn(rd()); //Why this parameter needs "()"?
... | Case 1
mt19937 rdn(rd());
In the above statement, rd() uses(calls) the overloaded std::random_device::operator() and then the return value from that is used as an argument to mt19937's constructor.
Basically the parenthesis () is used to call the operator() of std::random_device. That is, here the parenthesis () after... |
73,216,268 | 73,223,128 | How to include Xcode sub-project headers? | I'm trying to compile libcpr for iOS. I have built cpr using CMake using the Xcode generator. This has generated an .xcodeproj I have imported (read drag&drop) into my Xcode project. The problem lies when I try to import the library headers, they are not found:
// currently with quote notation but also tried with brack... | Great findings, Oscar!
So, the issue is really Xcode not knowing where to find the header files, and the solution (as you already found out) is simply to use the right search path(s). You have to use HEADER_SEARCH_PATHS (USER_HEADER_SEARCH_PATHS only works for quote includes).
diff --git a/ios/libcprtest.xcodeproj/proj... |
73,217,253 | 73,217,390 | How Calculate MD5 and other hashes in C++? | I am trying to hash strings in C++. I am trying to use the following code that I found to do a MD5 hash:
void digest_message(const unsigned char *message, size_t message_len, unsigned char **digest, unsigned int *digest_len)
{
EVP_MD_CTX *mdctx;
if((mdctx = EVP_MD_CTX_new()) == NULL)
handleErrors();
... | For MD5 which is a 128-bit hash, you'd call it like this:
unsigned char* digest = nullptr;
unsigned int len = 0;
digest_message(message, message_len, &digest, &len);
Then to convert to 32-char hex string:
std::string s;
std::ostringstream ss;
for (unsigned int i = 0; i < len; i++)
{
ss << std::hex << std::setfill... |
73,218,071 | 73,218,353 | Assigning Eigen Block to a Matrix gives wrong elements | When I'm using block method of Eigen Matrix and assigning the return values to the MatrixXd variable itself , the element of the matrix changed weirdly.
Here is a simple example to reproduce this problem.
Eigen::MatrixXd temp(3, 5);
temp << 60, 1.44583e-14, 2.90553e-14, 59.9308, 60,
60, 60, -2.90553e-14,... | It happens because the left side aliases the right side of the assignment. In general, Eigen does not guard against this in the interest of performance. Exceptions are made for matrix multiplication, where the noalias() method indicates that you, the programmer, has made the assessment. You can read the Aliasing chapte... |
73,218,662 | 73,218,756 | Text can not be appended to the file | I want to append text to the file "filename.txt" but the text won't append. I have even set the attribute ios_base::app but it does not work(I have tried deleting the file and starting the program again so that the part where the attribute is added will be run;
ifstream MyReadFile("filename.txt");
ifstream f("filename... | You could open the file for reading and writing, and then use positioning functions to move around in the file or to switch from reading to writing
fstream MyFile("filename.txt");
while (getline(MyFile, myText)) {
// Output the text from the file
cout << myText << "\n";
}
MyFile.clear(); ... |
73,218,666 | 73,218,934 | The private member function's action scope | The Issue:
Class declaration is as below:
class Select {
public:
template<typename Iterator>
static Iterator function(Iterator , Iterator , bool (*judgeFunction)(Iterator A, Iterator B) = priFunction);
private:
template<typename Iterator>
inline static bool priFunction(Iterator , Iterator);
And my tes... | The program is well-formed as we're allowed to use priFunction as a default argument the way you did in the above example.
This seems to be a clang bug. Demo. As you can see in the above link, clang also give the error:
<source>:6:100: error: 'priFunction' is a private member of 'Select'
static Iterator function(It... |
73,219,402 | 73,219,425 | When I use typeid() to judge a type, different type will compile error | When I use typeid() to judge a type, different type will compile error.
This code can't compile successfully because the judge of typeid() is RTTI. How shall I modify this code?
error: no matching function for call to 'std::vector<int>::push_back(std::basic_string<char>)'
template <typename T>
void SplitOneOrMore(const... | Compiler will compile both branches no matter the condition, the C++17 solution is constexpr if
There is no reason to use typeid machinery for this, std::is_same_v from <type_traits> will do its job just fine:
if constexpr (std::is_same_v<std::string, T>) {
res->push_back(str.substr(next_begin_pos, next_end_pos - n... |
73,219,445 | 73,219,692 | Are there any tricks I can use to initialize global constants with a separate function call? | I have a lot of global settings defining the behavior of my program. I found it convenient to declare these settings as extern constants in a separate namespace like this:
// settings.hpp
namespace settings
{
extern const int waitEventTimeoutSeconds;
// ...
}
// settings.cpp
#include "settings.hpp"
const in... | Do not use global variables. They make stuff confusing, like the problems you are having. Make it all local. Write getters and if needed setters. Force the user to call a function to get the configuration, where you do the stuff you want.
// settings.hpp
struct TheSettings {
int waitEventTimeoutSeconds;
};
const Th... |
73,219,741 | 73,221,070 | Compiling opencv program cause gcc -I/usr/local/lib test.cpp test.cpp:1:10: fatal error: opencv2/core.hpp: No such file or directory | There is a error when compiling opencv program program simple includes #include <opencv2/core.hpp>
I compiled it with this command
g++ test.cpp -o app `pkg-config --cflags --libs opencv`
compiling opencv in c++
This is full error
gcc -I/usr/local/lib test.cpp
test.cpp:1:10: fatal error: opencv2/core.hpp: No such fi... | With the -L option you should specify the library search path.
Then with -l options you specify the library names you'd like to link against.
So in your case I'd expect to see -L/usr/local/lib -lopencv_core. Note that the -l name has the lib prefix and file extension omitted. (You may need more OpenCV libraries.)
Se... |
73,220,562 | 73,220,632 | nlopt: Passed data structure gives me damaged values | I need to pass structure to the function Constraint::AddFixedOrientationAxis, however when I check the passed data their values are completely wrong. I have tried to use different datatypes but without any luck.
typedef struct{
size_t idx;
size_t axis_idx;
double axis_vector_1;
double axis_vector_2;
... | As @{Some programmer dude} told me in the comments, the problem was that the variable was not alive when the function was called.
|
73,220,610 | 73,261,547 | Template specializations in friend declarations post C++20 | Context: To our surprise, MSVC with C++20 mode and two-phase compliance enabled accepts the following code:
template<class T>
class X
{
friend int foo<X>(X x);
int a = 10;
};
template <class T>
int foo(T t)
{
return t.a;
}
int main()
{
return foo(X<float>{});
}
This compiles/links and returns 10 in ... | It’s true that there are no parsing difficulties here: C++20 does give the right meaning to the <, and template argument lists are parsed independently of the template declaration (which is how function template overloading and ADL can work).
Next, C++20 as published doesn’t say much in general about the process of dec... |
73,220,783 | 73,237,670 | Sorting 'Alphabetically' (Alien Dictionary Code Problem) | I've started tackling coding problems to try and improve my skills.
I'm working on the 'Alien Dictionary' coding problem which, when given a sorted list of 'Alien Words' you need to determine the 'Alien Alphabet'. The alien alphabet is made up of Latin characters but in a different order than ours.
I've since learned t... | In order to implement the getRule function if there is no implicit rule for {a, b}, you should search for {a, x} = '>' where {x, b} = '>' or {a, x} = '<' where {x, b} = '<'
// in case if a > b, you search for "a > x and x > b".
// In other words, if a is greater than x and x is greater than b,
// then a is greater tha... |
73,221,640 | 73,221,712 | why does 0 convert from int to string? | I am baffled by this error:
#include <string>
#include <iostream>
void f(int, std::string) {std::cout << "f1\n";}
template <class T>
void f(std::string, T&&) {std::cout << "f2\n";}
void f(int) {std::cout << "f3\n";}
void f(std::string) {std::cout << "f4\n";}
int main() {
// f(0, "as"); // call of overloaded 'f(i... |
The third line does compile, even though it is the same conversion.
Yes, but it's not the only conversion. A string literal like "as" is not of type std::string, and requires a converting constructor. So it's a user defined conversion. The rank of the overload is the worst rank for any conversion of any argument.
Sam... |
73,222,122 | 73,222,297 | C++ Metaprogramming sum of two types | I have a class like this
template <typename T>
class Matrix {
typedef T value_type
...
};
I would like to write a function that needs to deal with different Matrix<T> types but also with arithmetic types (that is why I cannot use Matrix<T1> and Matrix<T2> as template arguments). Inside the function I need a Matrix tha... | No, it's not possible to work directly with the types, but you can use std::declval - a function which returns whatever type you want - to "convert" a type to a value:
template <typename T1, typename T2>
auto add(T1&& a, T2&& b) {
Matrix<decltype(
std::declval<remove_cvref_t<T1>::value_type>()
+ std... |
73,222,195 | 73,256,041 | How to abort when the number of rows in the file is less than the number of rows read in the target in C++? | Now I have a txt file like this:
5
1 2 3
1 2 3
1 2 3
1 2 3
1 2 3
5
1 2 3
1 2 3
1 2 3
1 2 3
1 2 3
...
One loop of this file is 7 lines, and the second line of the 7 lines is a blank line. My file has a total of 5 loops , but when my code is set to read 10 loops, the code will not report an error, how should I modify ... | Check the input stream's eof bit, which can be done by directly accessing it get_in.eofbit or by using the eof() function, get_in.eof().
I would recommend using the eof() function.
I am not sure what you are doing with your code, but here is a simple to understand modification of your code as a demonstration:
#include ... |
73,222,485 | 73,256,935 | Using R (and Rcpp), how to pass a default 'std::vector<int>' array into a function | I have a function to SORT:
// https://gallery.rcpp.org/articles/sorting/
// https://www.geeksforgeeks.org/sorting-a-vector-in-c/
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector cpp_sort_numeric_works(NumericVector arr, std::string dir = "ASC" )
{
NumericVector _arr = clone(arr);
... | Here is a version that at least compiles and runs. I am not quite sure what you want with partial -- but what you had is simply outside the (documented, but we already know you do not have time for the documentation we provide) interface contract so of course it didn't build.
Code
// https://gallery.rcpp.org/articles/s... |
73,224,589 | 73,224,654 | Pointing from a shared_ptr to a list yields memory error | I'm trying to have a list of shared_ptr's to int. When I try to point to one of the elements on the list, if I have a shared_ptr to the object that will point to the element it fails.
#include <iostream>
#include <list>
using namespace std;
class A
{
public:
A(){};
shared_ptr<int> p;
};
int main()
{
l... |
/* This does not work */
shared_ptr<A> a2;
a2->p = l.back();
and it's not supposed to work. a2 is a shared pointer that does not own anything. Yet, you try to dereference it with the -> operator. The A object you think a2 owns doesn't exist! You need to make one, e.g., like you did with your int using make_shared().... |
73,225,173 | 73,225,220 | What effect does `static` have on a method in a namespace? | Does static mean anything on func2 in the context of a namespace? Both methods appear to be equivalent.
// MyHeader.h
namespace TestNameSpace
{
int func1() { return 1; }
static int func2() { return 2; }
}
// SomeFile.cpp
#include "MyHeader.h"
// ...
int test1 = TestNameSpace::func1(); // 1
int test2 = TestName... | static functions (which are not member of classes) are only visible in the compilation unit they are defined in. Apart from that there should not be any difference between those two
|
73,225,396 | 73,225,498 | Get iterator to beginning of function-generated range within for loop | I am trying to get an iterator to the beginning of a for loop, in which the range is generated by a function:
std::vector<int> buildList() {...}
int main() {
for (const auto& i : buildList()) {
const auto& id{ &i - RANGE_BEGIN};
}
}
Is there a way to point to the beginning of the range without declarin... |
Is there a way to point to the beginning of the range without declaring the vector outside of the for loop?
No, there is not. You must save it to a local variable in order to refer to it inside the loop body, eg:
int main() {
auto theList = buildList();
for (const auto& i : theList) {
const auto& id{ &i... |
73,225,484 | 73,226,137 | regex to parse json content as a string in c++ | My application receives a JSON response from a server and sometimes the JSON response has format issues. so I would like to parse this JSON response as a string. Below is the sample JSON response I'm dealing with.
[{
"Id": "0000001",
"fName": "ABCD",
"lName": "ZY",
"salary": 1000
},
{
"Id": "0000002",
"fName": "EFGH",
... | I'm not quite sure how your code is even compiling (I think it must be trying to treat the "{" and "}" as iterators), but your regex is pretty clearly broken. I'd use something like this:
#include <string>
#include <regex>
#include <iostream>
std::string input = R"([{
"Id": "0000001",
"fName": "ABCD",
"lName": "ZY",
"... |
73,225,551 | 73,225,757 | Image labeler google kickstart | problem :
Crowdsource is organizing a campaign for Image Labeler task with participants across N regions. The number of participants from each of these regions are represented by A1,A2,…,AN.
In the Image Labeler task, there are M categories. Crowdsource assigns participants to these categories in such a way that all p... | Q1: These are just declarations for importing libraries
Q2: Before the start of this code, the vector contains n integers in ascending order. The for loop then will sum the last m elements of the array, so therefore summing largest m elements in the input. After the for loop the median of the remaining numbers is appen... |
73,225,886 | 73,226,763 | Difference between a const reference parameter and const parameter in the context of a function | I tend to use const reference parameters when calling functions assuming this would be efficient since copies of the same wouldn't not be made. Accidentally I changed the function parameter in a function that previously had a const reference parameter to const now, and I observed that the code size is reduced upon comp... | A reference can be understood as something in between a name alias and a pointer.
From What are the differences between a pointer variable and a reference variable?:
A compiler keeps "references" to variables, associating a name with a memory address. Its job is to translate any variable name to a memory address when ... |
73,226,144 | 73,226,725 | Is it safe for a QObject's thread affinity to be a deleted QThread? | Consider the following code:
QThread *thread = nullptr;
QObject *object = nullptr;
void setup() {
QThread *thread = new QThread;
QObject *object = new QObject;
object->moveToThread(thread);
thread->start();
}
void cleanup() {
thread->exit(0);
thread->wait(1000);
if (!thread->isFinishe... | QThread starts the event loop by calling exec() and runs a Qt event loop inside the thread.
However, what happens if cleanup() is called before postEventToThread()?
thread is deleted and it's event loop exits, all event processing for object stops.
Does object automatically start behaving as though it has no thread ... |
73,226,827 | 73,227,167 | Counting sort problem in c++ , compiler shows no output | Counting Sort problem in c++
I tried to write a counting sort algorithm in c++. But this program is not working. I tried to debug, but can't find the problem. Compiler shows no output(code is attached in the below). Can anyone tell me, What's going wrong in this code?
How can I fix this problem?
Thanks in advanced.
#... | I've changed all of your dynamically size arrays to vectors. I also changed your cumulative sum and backtracking loops to better match a counting sort.
#include <bits/stdc++.h>
using namespace std;
void printArray(vector<int> a, int n){
for(int i=0;i<n;i++){
cout<<a[i]<<" ";
}
cout<<endl;
}
int m... |
73,226,969 | 73,228,963 | How to create an un-escaped string of hex bytes in C# | I am working with a C++ API from my C# codebase and am having issues with Cyrillic characters in a file path.
I am trying to call the wrapped C++ function which should load an object from the file. The C++ function signature looks like this:
GetModelFromFileCpp(ModelRefType * model, const char * file_path)
This functi... | What you are doing to pass UTF8 simply isn't how UTF8 is supposed to be represented. That's just the way you write it in C# code as a literal string. What you show in your debugger is just a hex representation of the actual bytes.
In actual UTF8 strings, each character occupies a single byte, or multiple if using chara... |
73,227,224 | 73,227,416 | C++: Initialize struct with incomplete type | I have two types defined in a header file like so:
struct vec2{
float x;
float y;
vec2() : x(0), y(0) {}
};
struct vec3{
float x;
float y;
float z;
vec3() : x(0), y(0), z(0) {}
};
In some C++ file I would like to be able to write:
vec2 a2 = {2,4};
vec3 a3 = vec2(a2);
//This would give me a3... | No problem, you have to set the constructors up to perform implicit conversions:
namespace vec{ // if in a header, this should avoid possible name conflicts
struct vec3; // forward declaration
struct vec2{
float x;
float y;
vec2(float inp1 = 0, float inp2 = 0):
x(inp1), y... |
73,227,934 | 73,228,134 | shared_ptr of barrier doesn't keep the expected counter | I have 2 code examples syncing 2 threads with std::barrier{2}. In one I create the barrier statically, and in one I create it dynamically. The 2nd way mimics the way I want to use the barrier - since number of threads - and hence the "size" of the barrier, is something I'll know only on runtime, making it impossible to... | You're attempting to call a default-initialized std::function.
Your two examples use different CompletionFunction types.
std::barrier b{2} uses the default CompletionFunction type, which is an unspecified DefaultConstructible function that does nothing.
std::make_shared<std::barrier<std::function<void()>>> use std::fu... |
73,228,078 | 73,230,180 | Protobuf packed (de)serialization | Since protobuf does not support the uint16_t datatype, I have a field below describing what I have in place.
uint32_t fingerprints = 1 [packed=true];
To save space, I have a C++ program that packs together two uint16_t values and add them that way, here is an example:
uint16_t value1 = 100; // Arbitrary values
uint16_... |
To save space, I have a C++ program that packs together two uint16_t values and add them that way
No bother to do that. Protobuf uses variable length encoding to serialize uint32_t, which will do 'pack' for you to save space, i.e. for an uint16_t number, protobuf will not encode it to 4 bytes, instead, it might encod... |
73,228,114 | 73,228,358 | Launch command line programs behind all open windows from a C++ executable | I am working on C++ program in windows which launches numerous external programs using command lines in quick succession after previous one finishes. Currently a new terminal pops up in front every time I make an external program call. I have tried SYSTEM an POPEN. Is there a way to launch these terminals in the back b... | Unless you really need to use system(), I would recommend using ShellExecuteA, if you set nShowCmd to 0, it doesn't generate any windows or pop up any consoles.
|
73,228,415 | 73,229,431 | How can A and not A be both true when using static_assert | A very confusing situation involving some constexpr and type traits led me to think the value of an expression is true, when in fact it was both true and false.
https://godbolt.org/z/McYMvxasT
#include <utility>
#include <iostream>
template<typename T>
struct S {
constexpr int f() const {
constexpr bool ... | A template which is not instantiated and which has no well-formed instantiation is ill-formed with no diagnostic required. The program is invalid but the compiler is not required to diagnose it.
|
73,228,546 | 73,228,928 | Pointer losing visibility during cross-class access | I have an issue where class GUI_System accesses a member of class ThreadManger through class GUI_Top. What happens is that accessing the member from its original container shows its correct contents, but when accessed from GUI_System it doesn't.
I have found out that in class ThreadManger, prior to the member in questi... | I downloaded your project and had a look at it. The primary issue seems to be that you are storing a pointer to a method on a forward-declared type. The size and/or padding for such values is unknown without the definition of what it points to.
Here is your ThreadManger [sic] stripped back:
class GUI_System;
class Thr... |
73,228,567 | 73,230,146 | Set elements from array pointer into protobuf in C++ | I have a pointer to an array called array which is defined as uint16_t *array. I have another variable called size that shows how many elements there is. I have a field in a protobuf message defined as:
required bytes array = 1;
How can I use the generated method protoMessage.set_array to convert my array into the fie... | Since Protobuf's bytes type is a std::string, you need to serialize your uint16_t array into a string, and calls set_array.
protoMessage.set_array(array, sizeof(uint16_t) * size);
However, your serialization might not be portable, because of the big/little endian problem.
In your case, why not define your proto messag... |
73,229,197 | 73,229,380 | transfer lambda to another lambda with different type | Suppose I have two functions testMethodOnInt and testMethod, they both take std::function as parameter. One is on type int, the other is on type pair<string, int>.
Is there a way to keep testMethod(lambda); call in main function, but modify testMethod to use testMethodOnInt, so it can print every value in the map.
Ther... | You can wrap f with a lambda and forward it to testMethodOnInt.
void testMethod(std::function<void(std::pair<std::string, int>)> f) {
testMethodOnInt([&](int x) { f({"", x}); });
}
|
73,229,272 | 73,229,580 | Common interface with a wrapper around std::variant or unions | This question is related to Enforcing a common interface with std::variant without inheritance.
The difference between that question and this one, is that I wouldn't mind inheritance, I am simply looking for the following structs/classes...
struct Parent { virtual int get() = 0; };
struct A : public Parent { int get() ... | You can't automagically set this up to allow multiB.get(), but you can allow multiB->get() or (*multiB).get() and even implicit conversion, by providing operator overloads:
template<typename Base, typename... Types>
struct Multi : std::variant<Types...>
{
using std::variant<Types...>::variant;
operator Base&()... |
73,229,349 | 73,229,605 | What is the "const operator" in C++? | Note: This does not mean the const keyword, as the following example doesn't contain it at all.
P1102R2 contains the following:
std::string s1 = "abc";
auto withParen = [s1 = std::move(s1)] () {
std::cout << s1 << '\n';
};
std::string s2 = "abc";
auto noSean = [s2 = std::move(s2)] { // Note no syntax error.
std::... | This is referring to the fact that a lambda is really just a dressed up operator() overload in an anonymous class.
And, guess what? Lambda captures are merely members of the anonymous class.
The above example is equivalent to:
class [anonymous] {
std::string s1;
public:
[anonymous](std::string &&s1) : s1{ st... |
73,230,291 | 73,238,455 | Why the symbols for cards is not showed ( hearts, spades, diamonds, clubs) when I run the program? | //This program first set 52 cards with their number and their Suit and then it displays them. After that it shuffles the cards and swaps them with random cards and display them. But problem is that while displaying the cards the symbol of their suit is not displayed. Why??
Please help someone!!!
PS: In the deck of card... | switch (suit)
{
case clubs:
cout << "\u2663";
break;
case diamonds:
cout << "\u2666";
break;
case hearts:
cout << "\u2665";
break;
case spades:
cout << "\u2660";
break;
}
|
73,230,334 | 73,230,602 | Find an element in a matrix M*M of numbers which have exactly 3 divisors in given time? | This was a task given on a coding competition a few months ago, and its still bugging me now. I did solve it, but my code did not give the result in required time for 3 test samples, likely due to the very large numbers they used. The thing is, looking at my code i see no obvious improvements that would reduce the time... | Rather than this:
while(count<elem)
{
num+=2;
if(prime(num))
count++;
}
This:
vector<long long> primes;
primes.push_back(2);
while (count < elem)
{
num += 2;
if (prime(num, primes)) {
primes.push_back(num);
count++;
}
}
Where your prime function is modified to only test di... |
73,230,441 | 73,234,617 | Launch command line window in hidden mode from a C++ code and read output log file | On windows machine, My code runs ShellExecute to launch abc.exe with SW_HIDE as the last argument to hide the launched command line window. This runs fine as desired.
std::string torun = "/c abc.exe >abc.log";
HINSTANCE retVal = ShellExecute(NULL, _T("open"), _T("cmd"), std::wstring(torun.begin(), torun.end()).c_str(),... | You need to wait for the child process to finish:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <tchar.h>
#include <shellapi.h>
...
SHELLEXECUTEINFO sei = { sizeof(sei), SEE_MASK_NOCLOSEPROCESS|SEE_MASK_FLAG_NO_UI };
sei.lpFile = TEXT("cmd.exe");
sei.lpParameters = TEXT("/C ping localhost > a... |
73,230,831 | 73,230,892 | Scope resolution operator with shadowing in blocks | Not that you'd write code like this, but trying to better understand the scope resolution operator ::. Is it possible to access the version of foo that stores the value 2
in the inner scope without having it be a named namespace?
#include <iostream>
using std::endl;
using std::cout;
// Some global.
int foo = 1;
int... |
Is it possible go access 2 here?
No, it is not possible to access the 2nd foo as it has been hidden from the inner foo.
One thing that you can do if you must use the outer foo from #2 is that you can create an alias for it with some other name like ref and then use that alias as shown below:
// Some global.
int foo =... |
73,231,836 | 73,235,027 | define macro with conditional evaluation in C/C++ | is there a way/trick to make a #define directive evaluate some condition?
for example
#define COM_TIME_DO(COND, BODY) \
#if (COND) BODY
#else
#endif
it's ok also to use template but body must be an arbitrary (correct in the context is used to) piece of code, simply just present or not in the source dependi... |
i was just asking if it was POSSIBLE because i like it more than the #if ... #endif.
If the expression of the condition will always expand to 1 or 0 (or some other known set of values) it is possible to implement such a macro.
#define VALUE_0(...)
#define VALUE_1(...) __VA_ARGS__
#define COM_TIME_DO_IN(A, ...) VALU... |
73,232,002 | 73,232,389 | CMake non-configurable option | In CMake, how can I define an option that is not configurable by the user, but automatically calculated?
I would like to do the following:
if (FOO AND NOT BAR)
option(BOO "Foo and not bar" ON)
endif()
And then I can use BOO in different CMake files:
if (BOO)
# do something
endif()
And also in sources:
#ifdef ... | Your "non-user-configurable" option sounds like a variable, which you can create like:
if(FOO AND NOT BAR)
set(BOO TRUE)
else()
set(BOO FALSE)
endif()
To use this variable in C++ code, you need to tell CMake to create a C++ file which defines this information. Take a look at CMake's configure_file function. Here's... |
73,232,067 | 73,232,216 | Using Hull shader and Domain shader breaks 2D shader | I'm following Rasterteks DirectX11 tutorial at https://www.rastertek.com/tutdx11.html and have been combining them to create and learn.
I just implemented tessellation for my 3D models and noticed that my 2D shader for rendering text stopped working. I have separate shaders for 2D and 3D, which worked fine until I impl... | It's probably because you forgot calls for unbinding HS and DS. Such as
immediateContext->HSSetShader(NULL, NULL, 0);
immediateContext->DSSetShader(NULL, NULL, 0);
You should enable debug layer, it's useful for debugging.
|
73,232,963 | 73,233,967 | How can I erase elements from a std::set in reverse (from the end until a lower_bounds) | So I need to erase elements from a std::set in a particular order, doing something with the first.
so if I had a set containing {1,2,3,4,5,6} and my I wanted to go until 4, I need to:
doSomething(6);
erase(6);
doSomething(5);
erase(5);
doSomething(4);
erase(4);
I have the following code that does not work:
#include <i... | The correct way of doing what you want is to getting your end iterator each time.
for (auto it = rbegin; it != std::make_reverse_iterator(s.lower_bound(4));) {
doSomething(*it);
s.erase(std::next(it).base());
}
Now let's see why you initial code didn't work.
In set, the iterators are not invalidate... |
73,232,965 | 73,288,265 | Why do I get double binary size when I instantiate a static object inside a free function in C++? | On an embedded system (Cortex-M4) I write C++ that compiles with GCC arm-none-eabi-g++. Compiler version 10.2.1 20201103.
My code is kind of complicated to copy paste it here, so here's an example:
I have a class that abstracts a hardware peripheral.
class A
{
public:
void init(void)
{
// initializes h... | It appears that somehow the compiler produces more code into the final binary when you create static objects inside functions like my example in the question.
That piece of code has something to do with exceptions which is not a desirable result in my case.
Changing the linker flags from
-specs=nosys.specs
to
-specs=n... |
73,233,039 | 73,236,064 | CERN ROOT framework segmentation fault with visual C++ | I am trying to use CERN's ROOT framework inside a Visual C++ project.
I built it from sources using the following commands (https://root.cern/releases/release-62606/):
``
cmake -G"Visual Studio 17 2022" -A x64 -Thost=x64 -DCMAKE_INSTALL_PREFIX=..\install_dir ..\root_src
cmake --build . --config Debug --target install
g... | %ROOTSYS% must be set else ROOT won't be able to find %ROOTSYS/etc directory.
This can be achieved by running thisroot.bat.
|
73,233,267 | 73,306,121 | Invalid alignment value (Producer: 'LLVM14.0.0git' Reader: 'LLVM 13.0.0git') | I try to build wasm on my ubuntu desktop. I'm using Ubuntu 22.04 I tried to install llvm-14 in terminal. But it didn't work. Error is here:
Invalid alignment value (Producer: 'LLVM14.0.0git' Reader: 'LLVM 13.0.0git')
Has anyone encountered this problem before?
| I fixed this problem. I updated my emsdk version to 3.1.13
|
73,233,307 | 73,233,574 | How to distinguish odd and even for big numbers more efficiently? | Please let me know by comments if there are already some similar questions.
When we usually try to distinguish odd and even numbers we can try the following code,
in C++.
int main() {
int n=10;
for(n; n>0; n--){
if(n%2==0) std::cout<< "even" << '\n';
if(... |
Is the performance time for 50000000%2 and 5%2 really the same?
This is making the assumption that the compiler "looks at the number" and "knows" how big its value is. Thats not the case for divisions. The compiler sees an int and performs some operations on that int. Different values are merely different bits set in... |
73,233,493 | 73,234,024 | How virtual functions are called in c++ | // b.h
#include <stdio.h>
class Tmp {
public:
// virtual void vfunc11() {}
virtual void vfunc1();
virtual ~Tmp() {}
};
class Tmp2 : public Tmp {
public:
virtual void vfunc1();
};
// b.cc
#include "tutorial/b.h"
#include <stdio.h>
void Tmp2::vfunc1() {
printf("Tmp2::vfunc1\n");
}
// a.cc
#include "b.... | So 'under the hood' each object of a class with virtual function holds data about how to call its version of that function.
That's a logical fact. During execution the code must have a way of determining which version of each virtual function to call for all the concrete object instances it may encounter(*).
In practic... |
73,234,385 | 73,239,630 | Perspective transformation using coordinates of a 2D image | Given a 2D image, I want to transform it to a given plane using a function() to transform the original coordinates to new coordinates on the same screen, with correct proportion.
An example of what I mean: Perspective Transformation
Now, translating the x coordinates I've been able to do, the problem is the translation... | Your image doesn’t seem right. In actual perspective transformation, only infinitely far points would merge on the horizon.
One possible way to apply the transform is in several steps:
With an affine (linear+offset) transform, place the plane into 3D space
Divide x and y by z
With another affine transform, move the re... |
73,234,812 | 73,236,045 | I am having problem debugging this Merge Sort for LinkedList Problem | I am trying to mergeSort two linked lists, and have used functions
mid - To find the midpoint of LL
merge - To merge the sorted linked lists
mergeSort - The final function is called recursively
Following is the class structure of the Node class:
class Node
{
public:
int data;
Node *next;
Node(int data)
... | The problem is that your recursion does not stop. You have as base case that head is NULL, but what if head is a list with one element? Then the list will split into an empty list and a list with that one element. So there will be a next recursive call with that one element... which is what you already had, and so it c... |
73,234,879 | 73,235,087 | make template class with std::vector<T> non-copyable when T is non-copyable | #include <vector>
#include <memory>
template<typename T>
class V {
public:
template<typename U = T, std::enable_if_t<std::is_copy_assignable_v<U>, int> = 0>
auto operator = (const V &rhs) -> V & { v = rhs.v; return *this; }
private:
std::vector<T> v;
};
template<typename T>
class U {
public:
template<... | The special copy assignment operator is never a template.
In cpp insights we can see that the compiler will generate a non-template copy assignment operator in addition to the template operator you provided.
You can conditionally disable special member functions of template class based on template parameter by inheriti... |
73,234,967 | 73,235,120 | CMake: add compile flag for header only library | Unsure about how to use CMake properly here. I have one library, which is a template header only library which uses C++20 features. Therefore, I want to make sure that any [downstream/consumer/dependent] of my library compiles the specialization of my library with the correct flags.
First lib does the following:
add_li... | target_link_libraries is to set libraries to link with when actually building the specified target. The problem here is that INTERFACE libraries aren't built.
You need to add the libraries to link with as a dependency for your library.
This is done with the set_target_properties command to set the INTERFACE_LINK_LIBRAR... |
73,235,016 | 73,235,141 | Huge memory usage in C++ MCTS algorithm | I am implementing a Monte Carlo Tree Search algorithm in C++. I create one huge tree at a time in a for loop, a different one at each iteration. My problem is that each tree is vast and if i create 12000 trees, my program crashes because all available memory in the PC is allocated.
The thing is, that the tree that i c... | The call to std::make_shared is using new to allocate memory on the heap. So when you finish using the tree, just recursively iterate it, deleting the nodes as you go (deepest first, then work backwards).
|
73,235,815 | 73,248,775 | I want to deploy a pytorch segmentation model in a C++ application .. C++ equivalent preprocessing | I want to deploy a pytorch segmentation model in a C++ application. I knew that I have to convert the model to a Torch Script and use libtorch.
However, what is C++ equivalent to the following pre-preprocessing (It's Ok to convert opencv, but I don't know how to convert the others)?
import torch.nn.functional as F
... | To create the transformed dataset, you will need to call MapDataset<DatasetType, TransformType> map(DatasetType dataset,TransformType transform) (see doc).
You will likely have to implement your 2 transforms yourself, just look at how they implemented theirs and imitate that.
The libtorch tutorial will guide you throug... |
73,236,632 | 73,237,211 | How can I access variables stored in the dynamic memory in a different function? | So I made this little piece of code that asks the user the size of an array and the contents of the array (in order) and makes the array in the dynamic memory (heap?).
void leesgetallen() {
int *n = new int();
cout << " Wat is de lengte van de Array?" << endl;
cin >> *n;
int g;
int *A = new int[*n];... | new int[*n] creates new, global (in a sense), unnamed array, and returns pointer to its beginning. That pointer is the only way to access that array. But A, the variable you store it in, is local to leesgetallen so can only be accessed from said function. To overcome that, you can define A and n in main, for example, a... |
73,237,497 | 73,237,565 | Can member functions of an object acces private members of local a object variable of the same nature? And if yes why? (see example...a.x) | float vector3d::scalar(vector3d a){
return (x*a.x + y*a.y + z*a.z); // here we can acces a.x even if x is a private
// member of a (vector3d)....my guess as scalar is a
// member function of vector3d it can acces private
... | Yes an instance can access private members of a different instance of same class. From cppreference:
A private member of a class is only accessible to the members and friends of that class, regardless of whether the members are on the same or different instances: [...]
Suppose other instances would have no access. Th... |
73,238,133 | 73,238,268 | How to do COM dll reference counting the right way? Official Microsoft samples are inconsistent |
Some implementations calls DllAddRef() and DllRelease() in the CClassFactory constructor, destructor, and LockeServer member function:
https://github.com/microsoft/workbooks/blob/master/Clients/Xamarin.Interactive.Client.Windows.ShellExtension/ClassFactory.cpp
Some do it only in LockeServer:
https://github.com/microso... | COM makes a distinction between DLL reference counting and object server reference counting.
Sometimes the object server is exactly one DLL and no more and it makes sense to combine them, sometimes the object server needs to maintain additional state (open files, network connections) and therefore requires different li... |
73,238,314 | 73,239,690 | Problems with LinkedList, overwritten? | I have recently been working on this problem: Reorder List - Leetcode 143
and found out I don't have the concept of Linked List as clear as I imagined.
The answer looks as following (got it from Grokking the coding interview):
static void reorder(ListNode *head) {
if (head == nullptr || head->next == nullptr) {
... | The variables that are of the ListNode* type, are pointers. They are not the structures themselves. It may help to visualise this. When the while loop starts, we might have this state:
head headFirstHalf
│ │
▼ ▼
┌────────────┐ ┌────────────┐
│ data: 1 │ │ data: 2 │
│ next: ───────► │ next: null │
└... |
73,238,927 | 73,239,077 | not displaying output using gets() function in c++ | I came into this problem where gets does not work inside condition statement. Can we not use gets() function in this way? Is it even taking input or not as it is not displaying output. Help me how to fix this issue.
#include<iostream>
#include<fstream>
#include<string.h>
using namespace std;
class Hospital
{
char... | You really should be using get with a string, and also in this scenario I don't see why its even necessary. If you delete the line with get(), your code works as intended.
|
73,239,559 | 73,239,850 | How do I escape the `\0 character` or why is my method not working? (C++, GTest) | I am writing a function to test going from URL to a query name format. For example, the URL "google.com" should turn into "\x6google\x3com\0". But if I want to test matching this I thought I just had to do something like this:
// Test first that "google.com" becomes "\6google\3com\0"
EXPECT_EQ(
test_dns... | To embed zero in a string literal, write \0 or \x00. But in most contexts, char arrays (including string literals) are treated as C strings, i.e. zero-terminated. Thus the first embedded zero will be considered as string end and not its part. Indeed, that is the only way as the size is not passed along string (even str... |
73,239,761 | 73,240,437 | Looking for nbit adder in c++ | I was trying to build 17bit adder, when overflow occurs it should round off should appear just like int32.
eg: In int32 add, If a = 2^31 -1
int res = a+1
res= -2^31-1
Code I tried, this is not working & is there a better way. Do I need to convert decimal to binary & then perform 17bit operation
int addOvf(int32_t res... | You have your constants for max/min int17 reversed and off by one. They should be
max_int17 = (1 << 16) - 1 = 65535
and
min_int17 = -(1 << 16) = -65536.
Then I believe that max_int_n + m == min_int_n + (m-1) and min_int_n - m == max_int_n - (m-1), where n is the bit count and m is some integer in [min_int_n, ... ,max... |
73,239,848 | 73,240,309 | pointer pointing to a class object created from template for later use? | Edit 1: I am not allowed to modify the class bar atm, aschepler’s #1 solution fits the best. I am closing this question. Thank you for the help.
Description:
I was trying to create a class object based on the user input. I tried to store its reference with a pointer and use it at a later stage. A similar idea with the ... | As comments have pointed out, you can't use a pointer to a variable declared in a block after the end of that block. You could fix this with a std::unique_ptr, or possibly std::optional.
Here are two possible solutions.
#1: A std::variant<foo<bar_1>, foo<bar_2>> can hold an object of either type, without requiring any ... |
73,240,362 | 73,241,026 | Doubly Linked List inserting in order | I need to write a function that insert valuse in order for doubly linked list e.g
I have an int list that contains: [3, 4, 6, 9, 10] and the input is 7,
then the list should be updated to contain: [3, 4, 6, 7, 9, 10]
I tried to write but i get segmentation fault
LinkedList is already sorted , I only need to put the... | There seems to be something missing here:
prev->next = node;
temp->prev = node;
node->next = temp;
If we look at the chain before and after:
Before your code is run:
prev
V
********** **********
* next *---------------------------... |
73,240,553 | 73,240,650 | Relationship between factory design pattern and polymorphism | Is factory design pattern can only be used when there is a polymorphic behavior exists?
| You use the factory pattern if you want to be able to change the concrete type that is created later on - in other words to use polymorphism to return an instance of a derived class in the form of the base class.
So polymorphism is a precondition for the factory pattern to work. Without polymorphism, you couldn't retur... |
73,240,645 | 73,254,427 | Turn off "Debug Assertion Failed" | I get the error, "Debug Assertion Failed", when executing my .exe via the Start-Process command in PowerShell. I do not get this error when normally executing via File Explorer (double-click). Please see the error below.
There have been similar questions on this forum that have suggested I add the following code to mu... | The solution is quite simple, adding the full path...
fp = fopen("C:\\Program Files\\FileZilla FTP Client\\fz-dump-26072022-1635.bin", "rb");
I found that the value of fp was NULL when executing via the PowerShell command Start-Process. This is because it was adding the file name fz-dump-26072022-1635.bin to the direct... |
73,240,891 | 73,240,936 | Calling template function inside another one but for function returning template type | I cannot understand why I can't build this code:
template<typename T> T* func ( void )
{
return NULL;
}
template<typename T> T* func2 ( void )
{
T* var = func();
return NULL;
}
Compilation result is: "error: no matching function for call to ‘func()’"
The code below is fine:
template<typename T> void func ... | The compiler needs to be able to determine the template parameter by some means. The type occurs in the function parameter list, the compiler often can deduce the type parameter based on the parameter passed. In the second example this is possible, since you pass var to func in func2.
If the functions do not take any f... |
73,241,114 | 73,268,810 | Is there a way to check if virtualisation is enabled on the BIOS using C++? | I'm trying to check if virtualisation (AMD-V or Intel VT) is enabled programmatically. I know the bash commands that gives you this information but I'm trying to achieve this in C++.
On that note, I'm trying to avoid using std::system to execute shell code because of how hacky and unoptimal that solution is. Thanks in ... | To check if VMX or SVM (Intel and AMD virtualization technologies) are enabled you need to use the cpuid instruction.
This instruction comes up so often in similar tests that the mainstream compilers all have an intrinsic for it, you don't need inline assembly.
For Intel's CPUs you have to check CPUID.1.ecx[5], while f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.