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,174,457 | 73,174,566 | Unresolved external symbol "enum days __cdecl operator++(enum days)" (??E@YA?AW4days@@W40@@Z) referenced in function main | I write a small program to encounter the next day by giving day.
I write a program in day_enum.cpp file:-
#include <ostream>
#include "AllHeader.h"
using namespace std;
inline days operator++(days d)
{
return static_cast<days>((static_cast<int>(d) + 1) % 7);
}
ostream& operator<< (ostream& out,const days& d... | According to the C++ Standard
An inline function or variable shall be defined in every translation
unit in which it is odr-used outside of a discarded statement.
It seems in the translation unit with main there is no definition of your inline function (operator).
Place the definition of the function in the header.
|
73,174,678 | 73,174,771 | c++ ofstream doesn't modify files. Even the tutorial examples | I am writing a program that needs to read from one file and write to another. Using fstream, I implemented the reading part, but the writing part didn't work no matter what I tried.
I tried the 'example programs' from all sorts of websites, but none of them worked. I tried changing things like file.isOpen() == false to... | @timebender
I tried following code using g++.exe(cygwin windows)
#include <string.h>
#include <sys/errno.h>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// Create and open a text file
ofstream MyFile("filename.txt", ios::app|ios::out);
if ( MyFile.i... |
73,174,777 | 73,175,178 | C++ - Cannot See Created Mutex Using WinObj | I am using this really simple code to try to create a mutex
int main(){
HANDLE hMutex = ::CreateMutex(nullptr, FALSE, L"SingleInstanceMutex");
if(!hMutex){
wchar_t buff[1000];
_snwprintf(buff, sizeof(buff), L"Failed to create mutex (Error: %d)", ::GetLastError());
... | In order to use a Windows mutex (whether a named one like yours or an unnamed one), you need to use the following Win APIs:
CreateMutex - to obtain a handle to the mutex Windows kernel object. In case of a named mutex (like yours) multiple processes should succeed to get this handle. The first one will cause the OS t... |
73,175,240 | 73,175,405 | C++ Fibonacci number generator not working. Why? | I just wanna know why does this method to get the fibonacci number not work thanks.
#include <iostream>
#include <cctype>
#include <cmath>
using namespace std;
int fibonacci()
{
cout << "enter sequence num: " << endl;
int num;
cin >> num;
int list[num] = {0, 1};
int x;
if (num == 1)
{
... | There is some inconsistent indexing here. If num = 1, the fibonacci number is 0, and if num=2, the fibonacci number is 1... but this does not quite match the declaration int list[num] = {0,1}, as indexes start with 0.
I have rewritten the code so that the first number has an index of 1 (list[1]=0 and list[2]=1)
A neste... |
73,175,419 | 73,175,559 | Safety questions when increasing vector's capacity | I've stumbled accross a case where increasing the capacity of a vector hurts one of the variables related to its element, and I would like someone to help me understanding what exactly the issue is.
Let's say, I have a class MyObject and a container vector<MyObject> myVector which was already populated with 4 elements.... | Any access to the value returned by GetFirstActiveElement is always undefined behaviour, since the vector is passed by value to the function, inside the function you're dealing with copies of the MyObjects stored in the vector inside the calling function; those copies get destroyed when returning.
Even if you pass a re... |
73,175,558 | 73,175,852 | Define a type alias in C++ templates conditionally on template arguments | I would like to write a template class along the lines of:
template <typename T>
struct lerp1d {
lerp1d(const T& abs_begin, const T& abs_end, const T& ord_begin, const T& ord_end) {}
auto operator()(val_t x) const -> val_t {
// ...
}
const std::vector<val_t> x_data_;
const std::vector<val_t> y_dat... | The way you've designed it, if you provide two different types of collection having the same value_t, it will produce two different classes where there is no points of them being different, except to construct them.
E.g. in (1), you would build a lerp1d<std::vector<double>::iterator> and in (2) a lerp1d<double*>. But y... |
73,175,951 | 73,176,080 | Visual Studio 2022 - Modules (Intellisense errors) | I have 3 files, namely engineering.cpp, engineering.ixx and system.ixx. Contents briefly are:
system.ixx:
export module sys;
export import :engineering;
engineering.ixx
module;
#include <string>
#include <vector>
export module sys:engineering;
namespace sys::engineering
{
export class Psychrometry
{
... | Two module units cannot use the same module partition name. As such, sys:engineering cannot be used in two module units. No diagnostic is required, which is why you don't get a compile error.
Also, if engineering.cpp is going to be a module implementation partition, then it must explicitly import the module if you want... |
73,176,034 | 73,177,566 | Why doesn't the shared pointer aliasing constructor use pass-by-value semantics | The shared pointer aliasing constructor (8 on cppreference) takes r by a constant reference. Is there a reason that value semantics are avoided?
The libcxx implementation of this basically copies the two pointers and increments the reference count if applicable.
shared_ptr(const shared_ptr<_Yp>& __r, element_type *... | You are missing the destructor. your suggested implementation will decrement the count upon return from constructor (the automatic shared_ptr instance will be destructed). So if the compiler is not able to optimize to noop, you just pay the cost of two extra atomic operation for no gain and an added logical error that ... |
73,176,122 | 73,176,517 | Why does typeid refuse to work for function types with const at the end? | So I've got this code:
template <typename T, typename class_t>
struct remove_ptr_to_member { using type = T; };
template <typename T, typename class_t>
struct remove_ptr_to_member<T class_t::*, class_t> { using type = T; };
class container {
public:
void func() const;
};
void print_member_type() {
std::cout ... | A function type with const or other cvref-qualifiers is a valid type in the language, but it has very limited uses, mainly to declare non-static member functions and to form pointers to non-static member functions.
Therefore the standard has restrictions on where they may be used, listed in [dcl.fct]/6. In particular t... |
73,176,500 | 73,179,059 | How to convert string from UCS2 to readable text | I need to convert the given string from UCS2 to readable text. How can I implement this in Python and C++ Arduino without using third-party modules.
st ="041204410451002004210443043F04350440003A00200031003300200413041100200438043D044204350440043D043504420430002C00200031003500300020043C0438043D00200030002004410435043A00... | Based on Python UCS2 decoding from hex string - Stack Overflow
import binascii
st = "041204410451002004210443043F04350440003A00200031003300200413041100200438043D044204350440043D043504420430002C00200031003500300020043C0438043D00200030002004410435043A0020043D04300020043C043E04310438043B044C043D044B043500200420041A002004... |
73,177,115 | 73,180,796 | Can asan issue trap upon violation like ubsan does? | Minimum reproducible example: https://godbolt.org/z/4hje5h1js
A great feature of ubsan (undefined behavior sanitizer) is to issue a trap that breaks into gdb when an issue occurs. This is turned on with -fsanitize-undefined-trap-on-error. However asan (address sanitizer) does not seem to have such option.
Is that corre... | For historical reasons Asan simply exits the application on error but you can ask it to abort (which will be intercepted by gdb) by setting environment variable:
export ASAN_OPTIONS=abort_on_error=1
Or you could simply set a breakpoint at __asan_report_error in gdb.
|
73,177,342 | 73,177,661 | c++ triangle rasterization using edge detection | I am trying to implement triangle rasterization using this article as reference
https://www.scratchapixel.com/lessons/3d-basic-rendering/rasterization-practical-implementation/rasterization-stage
as such I have implemented an edge function with an input of 3 points. 2 defining a line and one as the point to be tested, ... | this expression was backwards
(xp - xa) * (yb - ya) - (yp - ya) * (xb - xa)
it should have been
(yp - ya) * (xb - xa) - (xp - xa) * (yb - ya)
|
73,177,421 | 73,363,765 | Makefile Errors while building megasdk python in Alpine Edge Docker | I recently am facing problems on building MegaSdkC+ python wheel on alpine edge Linux docker ...I currently tried to port it via the Ubuntu Dockerfile
Error:
#8 184.6 In file included from /usr/include/openssl/bio.h:20,
#8 184.6 from /usr/include/openssl/ssl.h:18,
#8 184.6 from ./include/mega/posix/meganet.h:28,
#8 184... | Thank you @mpb I had added the -fpermissive flag as you told and the errors were actually downgraded to warnings also my built code is working very well
Fix :
https://github.com/AmirulAndalib/MLTB-ALPINE-DOCKER/blob/master/Dockerfile%20Base/Dockerfile#L45
thank you very much for helping
|
73,177,618 | 73,178,073 | winuser.h keyboard input char to hex convertion | I've been searching and testing this for a while now and haven't found an answer to the problem i have.
What i'm trying to do is make my own kind of library for mouse and keyboard simulated keypress. I'm trying to do this for a fun little project where i can automate some tasks that are impossible to integrate with any... | Your functions don't work as expected because ASCII codes are not Virtual Key codes, though there is some overlap but not the way you think.
The A and B keys on the keyboard are represented by virtual key codes VK_A (65/0x41) and VK_B (66/0x42), respectively. They also happen to be the same values as the ASCII codes ... |
73,177,689 | 73,178,090 | this c++ code of file handling runs in dev c++ but not in vs code | newbie here my code doesn't seem to compile in vscode. It give me the desired output while using dev c++. It gives me error while reading from file, writing to a file no problem. I have posted error message below the code.
#include <iostream>
#include <fstream>
#include <string.h>
using namespace s... | Better code would be this
void readfromfile(){
ifstream infile("student.dat",ios::binary|ios::in);
while (infile.read(reinterpret_cast<char*>(this),sizeof(*this)) {
show();
}
}
As already pointed out istream::read does not return an integer, which is ... |
73,177,944 | 73,178,262 | Is std::views::keys guaranteed to work correctly with any pair/tuple type? | Code is pasted here & https://www.godbolt.org/z/qszqYsT4o
I am attempting to provide boost::adaptors::indexed functionality that is compatible with c++20 views. My primary use case is for std::vector, but I would definitely prefer a generic solution. I was shocked to discover that std::views::keys did not work as exp... | This was LWG 3502. Your code fails on gcc 10.3 because of that particular issue, but it has been resolved and your code works fine on gcc 10.4 (or 11.1, etc.).
The example in the issue there should look familiar:
std::vector<int> vec = {42};
auto r = vec | std::views::transform([](auto c) { return std::make_tuple(c, c)... |
73,178,514 | 73,178,543 | A question about dynamic memory allocation 2 | After a few years, I discovered a memory leak bug in my code. Unfortunately the bug was not causing any issues to be noticed until I found out about it indirectly.
Below is a function addElement() from class c_string which adds a new element to a chain. My old way of doing it is like this:
class c_string
{
private:
... | The best way to do it is simply drop the second allocation, it serves no purpose.
void c_string::addElement(char ch)
{
char *tmpChain = new char[chain_total+1];
for(size_t i=0;i<chain_total;i++)
tmpChain[i] = chain[i];
tmpChain[chain_total++] = ch;
delete[] chain;
chain = tmpChain;
}
The ... |
73,178,604 | 73,178,894 | Possible way to get rid of abominable function types in C++? | So I was recently exposed to the grotesqueness that is the so-called "abominable function type" in C++ (originates from this paper as far as I know: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0172r0.html). I thought about it for a while and it does seem to make some amount of sense, but everything would ... | Pretty much exactly what you are suggesting has already been accepted for C++23 as member functions with explicit object parameters like this:
struct container {
void func(this container const&);
};
The type of this function is then void(container const&) instead of void() const or equivalently the type of &contai... |
73,178,843 | 73,178,891 | c++ portable address encoding | I'm writing a software that, at some point must write internal addresses into a buffer. I wrote the following code which works. But produce warnings when cross-compiling to a target device with an address size smaller than 64 bits.
How can I make this portable without generating errors?
I would have expected gcc to ign... | Try
if constexpr (addr_size >= 8)
If C++17 is not available to you, you can suppress the warning
if (addr_size >= 8) {
computed_addr |= ((static_cast<uintptr_t>(buf[i++]) << ((addr_size >= 8) * 56)));
computed_addr |= ((static_cast<uintptr_t>(buf[i++]) << ((addr_size >= 8) * 48)));
computed_addr |= ((static_c... |
73,179,104 | 73,179,148 | How to resolve Exception Error in C++ Builder | I am in the process of converting an older DOS based 16-bit application into a current Windows console app. Each time I run the application in debug mode I receive the following error:
Project xxxx.exe raised exception class $C0000005 with message 'access violation at 0x004151f9: read of address 0x00000000'.
The follo... | By the convention argc cannot be lower than 1, because it will have at least the name / symbolic link to the execution (binary) file. In the case of no arguments passed to your program it will try to deference NULL pointer (the last element of argv[]).
if ((1 < 1) || (strcmp(NULL,"/?")) == 0) prg_syntax();
I believe... |
73,179,805 | 73,179,941 | Control dimension of vector at run time | I am working on a program that needs to be able to create vectors with different dimensions at runtime. I know that C++ templates are a compile time feature, and I am not sure how to work around this currently. I have seen some examples that use if statements to control the allocation of memory like so:
if (some_co... | This is a way to implement the recursive template application:
#include <iostream>
#include <vector>
#include <type_traits>
template<typename T>
struct ID {};
template<size_t i, typename U>
auto n_dim_vec_gen(U u)
{
if constexpr (i) {
return n_dim_vec_gen<i - 1>(std::vector<U>());
} else {
ret... |
73,179,808 | 73,200,480 | How to transfer elements of 1 vector into another vector? | I am learning C++ and decided to make a card deck system using vectors. I have been able to randomly shuffle it, make 1 singular deck, and now I want to make a function that deals a hand from that deck.
Say I wanted a hand of 10 cards from a deck of 52 cards, therefore 42 cards would be left and the first 10 cards of t... | I would probably not bother with actually erasing elements from the deck's internal vector. That's because you might want to reshuffle and deal cards multiple times over the course of a game, which is easier if you just keep them all in the deck and track which ones have been dealt. And since almost everything containe... |
73,179,838 | 73,180,520 | How to prove c++11 make_shared() can keep shared_ptr's control block alive even after its dtor? | My question is: is there a case that share_ptr ref count is 0, while weak_ptr ref count is not 0?
Difference in make_shared and normal shared_ptr in C++
Referr this thread, showing that if a shared_ptr is created by make_shared and there's weak_ptr, its control block will be alive until both shared_ptr and weak_ptr's ... | Your code couldn't prove, because sp1,sp2 are local variables, they will be released when they out of range. And you could use hook or froce jump to show the result you want to see, but it's not easy.
We could read the source code of weak_ptr, so we can know about what really does, the souce code of weak_ptr is too muc... |
73,181,160 | 73,184,875 | C++ stack overflow error, even though i use a pointer array | Hello im trying to test a algorithm(Quicksort) by sorting an array with 1 000 000 numbers but i get a stack overflow error. I found out earlier that i should save the array on the heap instead of the stack. So i did it like this.
int *enMiljon = new int[1000000];
Instead of this:
int enMiljon[1000000] = {};
T... | Recurse on smaller partition, loop on larger partition. This will limit stack space complexity to O(log2(n)), but worst case time complexity remains at O(n^2).
template<typename T>
void quicksortPivotLastTwo(T arr[], int startIndex, int endIndex) {
while(startIndex < endIndex)
{
int p = partitionPivotLa... |
73,181,173 | 73,181,240 | Any creative ways to detect deleted data allocated in heap? | I am designing a game engine and a lot of subsystems would interface with each other better if deleted pointers could be detected. I decided to take a look at what the actual memory address points to. It appears to point to 0000000000008123 in my PC. I wonder, does it points to the same memory address to anyone else. I... | Smart pointers do exactly what you are looking for with the advantage that they will reclaim memory as objects go out of scope.
You can query them to check if they are empty or not.
Example: https://godbolt.org/z/6s5vxrjsa
#include <iostream>
#include <memory>
int main() {
std::cout << "Program operating..." << std... |
73,181,225 | 73,181,392 | Print neat progress bar from macOS terminal command prompt | macOS terminal is of type xterm-256color. I'd like to print colored progress bar with special characters.
for example, I uses printf with the symbol \xb0 to present the progress bar :
printf("%s", msg.c_str());
in debugger :
(lldb) p msg
(const std::string) $0 = "[\xb0\xb0\xb0\xb0]"
But apparently, it prints invisi... | Well doing it from scratch is pretty cumbersome.
Why don't you use an existing library like this, the code seems pretty straightforward.
You get all fancy progress bars, with color, and it seems pretty intuitive, and its very customizable.
(From the Github Repo, here)
#include <indicators/progress_bar.hpp>
#include <th... |
73,181,233 | 73,181,338 | C++ Is there any difference in performance by calling a func with code instead of calling the code directly? (From python) | I am from Python and still new at c++.
Now I wonder if calling a function is slower in performance then calling the code of the func itself?
Some example.
struct mynum {
public:
int m_value = 0;
constexpr
int value() { return m_value; }
// Say we would create a func here.
// That wants to use... | If the function body is available at the time it is called, there is a good chance the compiler will try to either automatically inline it (the "inline" keyword is just a hint) or leave it as a function body. In both cases you are probably in the best path as compilers are pretty good at this kind of decisions - or bet... |
73,181,336 | 73,181,351 | Are iterators still valid when the underlying elements have been moved? | If I have an iterator pointing to an element in an STL container, and I moved the element with the iterator, does the standard guarantee that the iterator is still valid? Can I use it with container's method, e.g. container::erase?
Also does it matter, if the container is a continuous one, e.g. vector, or non-continuou... | Yes, you've modified the object in the container. You've not modified the container itself so the iterator is still valid
|
73,182,098 | 73,182,177 | Question of removing numbers from a loop in c++ | so I have a question, so I have these codes here in c++
#include <bits/stdc++.h>
using namespace std;
int main()
{
for(int i = 1; i <= 100; i += 2)
{
cout<<i<<"\t";
}
return 0;
}
so the result of this is all odd numbers from 1 to 100, but I want it to remove the number 5 7 93 from th... | inside the loop you can do a check condition of the current loop index value and skip by using continue;
for(int i = 1; i <= 100; i += 2)
{
if (i == 5 || i == 7 || i == 93) {
continue;
}
cout<<i<<"\t";
}
|
73,182,141 | 73,183,627 | Undefined reference when creating entry point in shared library clang | I have an issue I don't understand. My project is quite simple for now. I have a shared library Engine which is called by my executable. I'm trying to move the entry point inside my shared library, so the executable part only has functions and some class to create.
---EDIT: I edit to post the project as it is reproduct... | The game class lacks a destructor definition. I suggest making it default:
class myGame : public game
{
public:
myGame(){};
~myGame() override = default; // here
bool initialize() override;
bool update(float deltaTime) override;
bool render(float deltaTime) override;
void on_resize() ov... |
73,182,242 | 73,182,272 | Cout trigger breakpoint when i try to print something which is not a string | I trying to build fft function in c++.
I realized there are errors in the process so I wanted to print each step on it's own.
When I try to do cout to everything that is not a string it trigger a breakpoint and error: "A heap has been corrupted "
In the main it sometimes and sometimes not
Any help, or suggestions would... | You allocated dynamically arrays with len / 2 elements. But in for loops like this
for ( int i = 0; i <= len/2; i++ )
you are trying to access len / 2 + 1 elements that results in undefined behavior. The valid range of indices is [0, len / 2 ).
You have to write
for ( int i = 0; i < len/2; i++ )
|
73,182,373 | 73,184,227 | std::invoke with ref qualifiers | I'm running into the following issue when using ref qualifiers with operator() below. What is the correct syntax to enable the l-value ref overload in this instance?
#include <functional>
struct F {
void operator()() & {}
void operator()() && {} // Commenting this overload enables code to compile
};
int main(... | For the first argument of std::invoke, which is expected to be a pointer to a member function.
As per cppref:
A pointer to function may be initialized from an overload set which may include functions, function template specializations, and function templates, if only one overload matches the type of the pointer
cppre... |
73,182,555 | 73,183,255 | How to read "std::greater<>{}" in "std::make_heap" | // min heap solution
// extract k smallest data from a min-heap of all n data points
class K_Smallest_MinHeap {
public:
K_Smallest_MinHeap(std::size_t n, std::size_t k): N(n), K(k), count(0)
{ }
void add(int value){
values.push_back(value);
}
std::vector<int> get(){
std::make_heap(values.begi... | According to the cppreference:
template< class RandomIt >
void make_heap( RandomIt first, RandomIt last );
template< class RandomIt >
constexpr void make_heap( RandomIt first, RandomIt last );
template< class RandomIt, class Compare >
void make_heap( RandomIt first, RandomIt last,
Compare comp );
tem... |
73,182,592 | 73,182,859 | Character counter returning incorrect value for char[n] array | I am writing a C++ program for homework, and it needs to count the characters in a char arr[n] string. However, my counter keeps returning the wrong values. I have looked through other answers to similar questions, however, they are not specific to C++ and none of the answers explain the value I am getting.
#include<io... | So it seems you haven't figured out how arrays and C strings work in C++ yet.
void setWord(const char* word)
{
strcpy(this->word, word);
}
and
Logic input;
input.setWord(text);
Your code is a bit weird, I guess you are just experimenting, but I think those two changes should make it work.
|
73,182,925 | 73,182,979 | How to create a function inside a structure in a header file and implement this function in another c source file? | Here I created a main.c
#include <iostream>
#include "Header.h"
struct person_t a;
int main()
{
a.func(1,2);
}
And I have a header called "Header.h", I define a structure in this file
struct person_t {
char name;
unsigned age;
int(*func)(int, int);
};
Then I implement int(*func)(int, int); in another ... | You may not use statements outside a function like this
a.func = &add2;
Remove this statement and this declaration
struct person_t a;
from Source.c.
In the header place the function declaration
int add2(int x, int y);
And in the file with main write
int main()
{
struct person_t a;
a.func = add2;
a.func(... |
73,183,032 | 73,184,141 | bytearray to numpy array in Python for displaying in pyqt5 GUI | I'm new to Python and have sorta c++ style coding background.
In short:
tring to display 16 bit grayscale images in my GUI(pyqt6)
have the stored the image data in bytearray, that is, 1024 by 768 (the total size of the byte array would be 1024 x 768 x 2 since it's 16 bit).
having difficulties with using this data = by... | Versions of Qt >= 5.13 include QImage.Format_Grayscale16:
# load 8-bit image with size w x h
raw8 = Path('image8.raw').read_bytes()
image8 = QImage(raw8, w, h, w, QImage.Format_Grayscale8)
# load 16-bit image, note 2 * w bytes per line!
raw16 = Path('image16.raw').read_bytes()
image16 = QImage(raw16, w, h, 2 * w, ... |
73,183,668 | 73,183,797 | How to encode a string in C++ so as to not collide with seperator? | I am currently developing an open-source Text-based storage utility called WaterBase. The aim is to facilitate easy saving and access of persistent key-value data, like we have in Android SharedPreferences.
The data storage scheme is like this:
type:key:value
The problem I am facing is that if someone uses : as a chara... | If you indeed want no special characters in the output string, you need to store the information about the string length beforehand. You could use an approach similar to name mangling: store the length of the next entry as integer followed by a seperator followed by the actual content:
Example
A string is stored as
<st... |
73,183,982 | 73,184,008 | how to return a reference of an object from std::vector<std::vector<>> | like in the title, here is a pice of code:
class matrix{
std::vector<std::vector<bool>> base;
std::pair<int, int> size;
public:
matrix(int x, int y){
size.first = x; size.second = y;
std::vector<std::vector<bool>> b(x, std::vector<bool>(y));
base = b;
}
bool& operator ()(int ... | bool& operator ()(int x, int y) const {
The const at the end means that this is a constant class method, and this is constant.
return base[x][y];
Everything in this is constant. Including this. The return value from this operator overload should, therefore, be const bool & instead of bool &.
If after understanding th... |
73,184,082 | 73,184,112 | How are templates work so that the classes are properly generated by the compiler to work with both pointer types and non pointer types? | Given
int i = 42;
int* p = &i;
we cannot do
const int * & d = p;
In my current understanding, this is because const int * & d can be read as "d is a reference of a pointer to an int that is a const" and p is "a pointer to an int", which means the RHS needs to be turned into a temporary being "a pointer to an int that... | Your guess is correct.
For const T, const is qualified on type T directly. Given T is int* (non-const pointer to non-const int), const T results in const pointer, i.e. int* const (const pointer to non-const int) but not const int* (non-const pointer to const int).
|
73,184,335 | 73,184,506 | c++ design with unique_ptr with custom deleter | I am writing a tree data structure. Each node has a fixed size so I use a fixed size allocator for allocating/deallocating Node. This gives me a headache:
struct Node {
// other attributes ...
std::array<std::unique_ptr<Node, CustomDeleter>, num_children> children_;
};
Since all allocations/deallocations of Node a... | You can use Template template arguments:
#include <memory>
template <template <class T> class AllocTemplate>
struct Tree {
struct Node;
using Alloc = AllocTemplate<Node>;
[[no_unique_address]] Alloc alloc_;
struct Deleter {
[[no_unique_address]] Alloc alloc_;
Deleter(const Alloc &alloc) : alloc_{allo... |
73,184,447 | 73,188,480 | Why does my compiler complain about a missing template argument for a concept? | Initially I had following concept which worked just fine:
template<typename T, typename...KEYS>
concept js_concept = requires(T t, int index, std::string& json_body, KEYS... keys, std::string key) {
{ t.template get_value<T>(keys) } -> std::same_as<T>;
{ t.template get_value<T>(key) } -> std::same_as<T>;
};
... | template<js_concept JSON_OPERATOR>
JsonUtil(std::string body, JSON_OPERATOR&& json_impl) {}
Is equivalent to
template<typename JSON_OPERATOR>
JsonUtil(std::string body, JSON_OPERATOR&& json_impl)
requires js_concept<JSON_OPERATOR> {}
KEYS... empty, so it works fine. (But I really doubt if it behaves as you expect...
... |
73,184,451 | 73,185,793 | how to split a sentence into strings using recursion in c++ | string strings[10];
void split(string s){
int curr=0,start=0,end=0,i=0;
while(i<=len(s)){
if(s[i]==' ' or i == len(s)){
end = i;
string sub;
sub.append(s,start,end-start);
strings[curr] = sub;
start = end + 1;
curr += 1 ;
... | This solution assumes you want only words from the string to enter your array and that you want to split on some predetermined string delimiter like <space>" " or <double-dash>"--".
If you need to keep the void function signature, here is one:
void split_rec(string str_array[], size_t arr_index,
string s... |
73,184,464 | 73,184,540 | How to direct initialize a C++ variant with one of its non-default option? | Consider the following:
class Foo {
[...]
public:
Foo(int);
}
class Bar {
[...]
public:
Bar(int);
}
using MyVariant = std::variant<Foo,Bar>;
How can one direct initialize (i.e no copy and no Foo building involved) an instance of MyVariant as a Bar ?
| Pass the a tag of type std::in_place_type_t<Bar> as first constructor parameter:
struct Foo
{
Foo(int value)
{
std::cout << "Foo(" << value << ")\n";
}
};
struct Bar
{
Bar(int value)
{
std::cout << "Bar(" << value << ")\n";
}
Bar(Bar const&)
{
std::cout << "Bar(... |
73,184,493 | 73,184,813 | How can I efficiently search for multiple adjacent elements in a std::set? | I have a set containing a sortable data type. I need to be able to search to find all elements that lie between two unknown points within this set. For the sake of simplicity I'll use some pseudocode to describe this.
set = {
(a, 0),
(a, 3),
(a, 8),
(b, 2),
(b, 5),
(c, 0)
}
In reality, my code is implement... | Something along these lines, perhaps. This relies on the capability, added in C++14, of std::set::equal_range et al to perform heterogeneous searches, given a comparator that has overloads for combinations of different types.
template<typename A, typename B>
class overall_type {
public:
auto find(A min_a, A max_... |
73,184,496 | 73,184,515 | c++ is there a way of use properties allready declared in the header file inside implementation | I know it's a basic question, but I didn't find the answer anywhere.
Supose we have this header:
#pragma once;
#include "user.h"
class Teacher
{
public:
float teachSkill = 0.01;
void teach(User &user);
};
And a implementation like this:
#include "teacher.h"
class Teacher
{
public:
float teachSkill;
v... | You can simply write, in the implementation:
void Teacher::teach(User &user)
{
user.knowledge += (*this).teachSkill;
}
No need to re-declare the class there.
Furthermore, you don't need (*this), so it's simply:
void Teacher::teach(User &user)
{
user.knowledge += teachSkill;
}
|
73,184,670 | 73,188,731 | Visual Studio cmd doesn't display Unicode characters | I am trying to make an ASCII converter in C++ that outputs an image using ▀ ▄ ░ █ Unicode characters.
It works, except for the output part. Instead of the actual characters, it just displays ?.
When I add system("chcp 65001"); or system("chcp 65001"); (to use UTF-8/UTF-16) at the beginning of the file, it doesn't do an... | After testing, the following code can output ▀ ▄ ░ █ , you could refer to my code to modify your code.
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
int main()
{
_setmode(_fileno(stdout), _O_U16TEXT);
wprintf(L"░▒▓▄▀█▀ ▄ ░ █\n");
return 0; // CYRILLIC CAPITAL LETTER YAE U+0518
}
Result:
Update:
I... |
73,185,045 | 73,200,688 | Compiler error with 'static const std::wstring DELETE;' | I started a new VCL application under C++Builder, and I observe something bizarre.
When I declare a const member named DELETE as std::string, I get an error.
Here is the .h file:
#pragma once
#ifndef Communication_ButtonTagH
#define Communication_ButtonTagH
#include <string>
namespace OverB::Communication
{
cla... | The VCL is built on top of the Win32 API, which has a DELETE preprocessor macro defined in winnt.h:
#define DELETE (0x00010000L)
The preprocessor is run first, and it performs text replacements of defined macros before the compiler is run. Thus, after the preprocessor has processed your code ... |
73,185,229 | 73,185,230 | 'clang -ftime-trace' does not produce a JSON file | Clang supports the -ftime-trace flag since version 9 which allows to analyze compilation times by producing a JSON file that can be read by Google Chrome. Unfortunately, Clang fails to output a JSON file for me, even for the simplest program.
Minimal example: I have a main.cpp file
#include <iostream>
int main(){
... | The -ftime-trace flag produces JSON files for each object file and places them next to each object file. It does not profile the linking stage.
Running clang++ -ftime-trace main.cpp produces a temporary object file in the /tmp/ directory and then runs the linker to form the complete executable a.out in your working dir... |
73,185,261 | 73,198,514 | Unhandled exception: An invalid parameter was passed to a function that considers invalid parameters fatal in UWP application | So I was making a polynomial simplifier for my school project. I decided to make the application using C++ UWP in Visual Studio.
As one of the extra features of the application I implemented a system to store and retrieve polynomials from a file so that you can access your previously entered polynomials. I am using boo... | When writing UWP applications, be aware that they by design run in a 'locked-down' environment. One aspect of this is that they have very limited access to the file system.
A UWP application by default has:
read-only access to its own installed directory (which is typically the 'current working directory' at start-up)... |
73,185,798 | 73,186,302 | Best practices for large array of integers in C++ | I am loading a 123 MB file of unsigned integers that needs to be in memory (for fast look ups for a monte carlo simulation) in C++. Right now I have a global array but i've heard global arrays are frowned upon. What are the best practices for this?
For context, I'm doing Monte Carlo simulations on a poker game and need... |
Use local variables, and pass them to functions as appropriate. This makes the program easier to reason about.
Use vector instead of an array for this large amount of data, otherwise you might cause stack overflow.
Modify your functions to work with std::span instead of a particular container, as this creates more d... |
73,186,143 | 73,197,935 | Error: the preLaunchTask build terminated with exit code -1, launch program does not exist | Recently I've been trying to move from CodeBlocks to Visual Studio Code, but the latter has been giving me problems especially when making projects with classes, in this case when trying to run it I get this window:
the preLaunchTask C/C++:g++.exe build active file terminated with exit code -1
If I click show errors i... | Found a way in the spanish stack overflow.
In tasks.json I added this:
"label": "g++.exe build active file",
"args": [
"-g",
"${fileDirname}\\**.cpp",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe",
],
Then run by either debuging or running the C/C++ file NOT just clicking run code and then it works perfectly... |
73,186,343 | 73,186,392 | Why c++ don't infer template argument T for simple nested types variables? | In this piece of code:
#include <iostream>
#include <vector>
#include <utility>
template <typename T>
using Separation = std::pair<std::vector<T>, std::vector<T>>;
int main()
{
std::vector<int> vector1 = {1};
Separation s1(vector1, vector1);
std::cout << s1.first[0];
return 0;
}
The g++ compiler ... | If you can make it a subtype, you may add a deduction guide:
#include <iostream>
#include <vector>
#include <utility>
template <typename T>
struct Separation : std::pair<std::vector<T>, std::vector<T>> {
using std::pair<std::vector<T>, std::vector<T>>::pair;
};
template <class T>
Separation(std::vector<T>, std::v... |
73,186,387 | 73,186,708 | std::uniform_real_distribution cannot be const anymore in MSVS2022? | In MSVS 2019 I used to declare my distribution const. Yet in the latest MSVS2022 preview, I get an error:
error C3848: expression having type 'const std::uniform_real_distribution<double>' would lose some const-volatile qualifiers in order to call 'double std::uniform_real<_Ty>::operator ()<std::mt19937>(_Engine &)'
1>... | const std::uniform_real_distribution<> was never guaranteed to be usable. The standard did not specify that operator() of std::uniform_real_distribution is const. In particular <random>'s distributions are allowed to have internal state, e.g. to remember unused bits returned from the generator or to store state if the ... |
73,186,510 | 73,193,383 | Is checking the location of the sign bit enough to determine endianness of IEEE-754 float with respect to integer endianness? | I recently wrote some code that uses memcpy to unpack float/double to unsigned integers of the appropriate width, and then uses some bit-shifting to separate the sign bit from the combined significand/exponent.
Note: For my use case, I don't need to separate the latter two parts from eachother, but I do need them in t... |
Is checking the location of the sign bit enough to determine endianness of IEEE-754 float with respect to integer endianness?
As I read it, given the C++ spec and the C spec that it tends to also rely on, checking the sign bit is technically insufficient to determine endian relationship between float/uint32_t. It ... |
73,187,171 | 73,187,205 | How does the argument list for std::function work | I'm sorry if this is a very noobish question, but I'm confused on how you can specify std::function argument lists like this:
std::function<void(double)> func;
But in an actual function, this doesn't work:
void passFunc(void(double) func) {}
For the method above you have to specify a function pointer. So how is void(... | You can declare a type like that:
using Func = void(double);
But in the definition, you still need the name of the argument; otherwise, you could not use it in the function:
void passFunc(void func(double)) {}
Note that func is inbetween the return type and the arguments. If you don't like that, you can use the above... |
73,187,217 | 73,187,415 | Problem with CreateProcessA() windows 10 c++ code::blocks | I have a problem with CreateProcessA, I looked at all the questions about it on stackoverflow and other sites, I rewrote a program following the advice of others but it still does not execute any commands and return error 998. I'm sure the string is correct because it works both with system and written directly on cmd.... | You pass uninitialized STARTUPINFOA si;. It must be initialized. See the example.
#include <iostream>
#include <string>
#include <windows.h>
using std::cout;
using std::string;
int main()
{
STARTUPINFOA si{sizeof(si)};
PROCESS_INFORMATION pi{};
string com = R"("C:\Program Files\MKVToolNix\mkvextract.exe" ... |
73,187,451 | 73,187,472 | Is assignment operator a sequence point under C++17? and what would be the result of this expression? | It is recommended not to modify an object more than once in a single expression nor using it after modifying it in the same expression.
int i = 0;
++++i; // UB
++i = i++; // OK?
I think that the last expression was UB before C++17 standard but now I guess it is OK because the assignment operator has become a sequ... | There's no sequence points now: we have sequenced-before and sequenced-after. When you have an operator= call (or any other operator@= call - built-in operator= or user-defined call), right-hand side is sequenced-before left-hand side. So ++i = i++ is valid in C++17, with i++ sequenced-before ++i.
Before C++17, as you ... |
73,187,895 | 73,188,317 | Getting full path in C++ adjacency list Dijkstra | I want to get full path in adjacency list Dijkstra algorithm using C++ queue. Graph edges are oriented.
Dijkstra algorithm works fine and I understand why. However getting full path is a bit more complicated to me, this usually described much less than Dijkstra algorithm itself. I tried to reused a few solutions (this,... | Your path function makes no sense. You should be using the parent array to walk backwards from the goal state to the start. As written, this function simply outputs all the parents. Consider something like this:
deque<int> path;
while(finish != -1)
{
path.push_front(finish);
finish = (finish == start) ? -1 : pa... |
73,188,576 | 73,188,847 | How to alloc largest available memory on different computer? | If I need a program to r/w data larger then 1T randomly, a simplest way is putting all data into memory. For the PC with 2G memory, we can nevertheless work by doing a lot of i/o. Different computers have different size memory, so how to alloc suitable memory on computers from 2G to 2T memory in one program?
I thought ... | You can use the GNU extension get_avphys_pages() from glibc
The get_phys_pages function returns the number of available pages of physical the system has. To get the amount of memory this number has to be multiplied by the page size.
Sample code:
#include <unistd.h>
#include <sys/sysinfo.h>
#include <stdio.h>
int mai... |
73,189,041 | 73,189,451 | Why I did not get the right result in this c++ code ( see the f3.show_fraction() in main )? | I did not get right result for object f3 when I see the f3 using show_fraction() function in
the below code: I am confused. I want to access the sum of f1 and f2 fraction that is stored in f3.But when i see the result in f3 it shows 0/0 in result using fraction_show() function
#include <iostream>
using namespace std;
c... | I don't like this style of coding, but at least this works
void sum(fraction &f, fraction &d) // calculates sum of two fractions
{
numerator = (f.numerator * d.denominator + f.denominator * d.numerator);
denominator = f.denominator * d.denominator;
}
then
f3.sum(f1, f2);
I would prefer something like this
fri... |
73,189,351 | 73,204,858 | "Name: value" widget via GTK | How to make a widget via GTK that looks like the following?
------------------
| Text1: | 1 |
|-----------+----|
| Text2: | 10 |
|-----------+----|
| | |
| | |
| | |
------------------
'Text1', 'Text2' - constant strings; '1', '10' - dynamically changed values.
What Gtk::W... | Make Gtk::Grid with labels, align them, set column spacing and column homogeneous.
#include <gtkmm.h>
class window : public Gtk::Window {
protected:
Gtk::Box box;
Gtk::Grid grid;
Gtk::Button button;
Gtk::Label name1, name2, value1, value2;
int n_click = 0;
public:
window();
~window() = def... |
73,189,691 | 73,190,169 | Storing a std::function as a private member results in it being null when used | I am at a loss for why this isn't working. I've tried passing a function by value, by reference, and still when I go to call the function from within SetFromState, it is null.
My class:
StateIndicator::StateIndicator(QWidget *parent) {
StateIndicator(parent, StateIndicator::DefaultSelectionStrategy);
}
StateIndica... | The problem was with how I was calling the overloaded constructor it seems:
StateIndicator::StateIndicator(QWidget *parent) {
StateIndicator(parent, StateIndicator::DefaultSelectionStrategy);
}
should be
StateIndicator::StateIndicator(QWidget *parent) :
StateIndicator(parent, StateIndicator::DefaultSelectionSt... |
73,189,899 | 73,189,975 | Why 0xFEFF appear in recv data | i try to create a client written in c++ and a server using python flask. The task is simple, client connect and get data from server, then display it on console. I have two piece of code:
Server:
from flask import Flask
app = Flask(__name__)
@app.route('/hello')
def hello():
return "hello".encode("utf-16")
if _... | Its is BOM (byte order mark). I just need to decode from the client or use:
return "hello".encode('UTF-16LE') # not UTF-16
|
73,189,988 | 73,190,207 | Is there a better way to overload operators on objects without making tons of copies? | So I wrote a very simplified example of what I'm trying to accomplish which in this case is a simple "matrix" struct.
As expected this program will compile and run (gcc 9.4 on ubuntu 20.04) and provide a valid result for the matrix D, however the problem is that I can't use references as arguments for the functions and... | This compiles and should work fine:
#include <vector>
template <typename T> struct matrix
{
std::vector<T> data;
std::size_t lines, columns;
matrix() = default;
matrix(const std::size_t L, const std::size_t C);
void print();
};
template <typename T>
matrix<T> operator+(const matrix<T>& A, const ... |
73,190,294 | 73,190,344 | Is there any tools for detecting files and lines that is using c++17 features? | Question
Is there any tools for detecting files and lines that is using c++17 features?
Background
I'm developing some software with c++17.
Recentlty a customer requested us to list files and lines that is using c++17 features.
The reason is that they have to applicate deviation permits for using c++17 feature because ... | If you compile with Clang, the -Wpre-c++17-compat diagnostic flag warns about the case from your example:
<source>:4:14: warning: nested namespace definition is incompatible with C++ standards before C++17 [-Wpre-c++17-compat]
namespace aaa::bbb::ccc
^
1 warning generated.
It will also warn on if/switch i... |
73,190,422 | 73,192,691 | Is there a flood fill outlining algorithm for constructing a polygon? | Is there a flood fill like method of generating an outline around the object? I'm trying to detect an object in an image and outline it. I'm currently successful with highlighting it but don't know how to outline. I'm using QT C++ and would like to construct a QPolygon of the points at the edges.
My code so far:
while... | You can use OpenCV API, cv::findContours().(It's based on Satoshi et al., 1985)
Call cv::findContours() on the image you labeled. It returns points of all contours(outlines).(Be careful to filter out trivial contours in the tree of contours such as a root node.)
See the official tutorial, Contours Hierarchy.
|
73,191,905 | 73,204,134 | Cannot run more than 1 thread in parallel using OpenMP in Windows 11, VIsual Studio 2019 | I created an empty C++ project using Visual Studio 2019 in Windows 11.
Then I ran this minimal piece of code to test multi-threading, using OpenMP:
#include <iostream>
#include <omp.h>
int main() {
omp_set_dynamic(0); // ensure that the number of threads doesn't change due to system demands
omp_set_num_t... | OK, real rookie mistake(s) here.
First of all, I didn't add the /openmp flag to the CMAKE_CXX_FLAGS which is necessary in Windows (I thought find_package(OpenMP) was enough, while adding -fopenmp, as in Linux, was not recognized, so I skipped it).
Even after I did, it didn't work. The reason was that the project I was ... |
73,192,837 | 73,193,909 | Set Extended Styles on Win32 Edit Control | Is it possible to set extended styles on Edit control (simple Edit, not Rich Edit)? For example, I want to set the extended style to WS_EX_ZOOMABLE | WS_EX_ALLOWEOL_ALL. The creation of the control is as follows:
HWND hEdit = CreateWindowExW(
ES_EX_ZOOMABLE | ES_EX_ALLOWEOL_ALL,
L"EDIT",
L"",
... | As noted in comments, edit control extended styles are set by sending the control an EM_SETEXTENDEDSTYLE message:
HWND hEdit = ::CreateWindow(
L"EDIT",
L"",
WS_BORDER | WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL | ES_LEFT | ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL,
0, 0, 100, ... |
73,193,356 | 73,193,408 | Thread safety for deterministic one-time write to static location? | I'm checking CPUID flags on x86-64 for instruction set extensions, and caching the results in a static array. The function doing this may be called from any of several different threads, so race conditions are possible - but does this matter? Any thread will produce the same results, so I don't care about conflicting w... |
so I don't care about conflicting writes
Conflicting writes to non-atomic objects are a data race and a data race always causes undefined behavior. The compiler may optimize based on that.
Therefore you must care about this.
You can use a std::array<TriVal, arch_max - 1> for the static local variable cached_results a... |
73,193,691 | 73,199,757 | Understanding calling inherited methods from abstract class in C++ | I was doing an experiment on inheritance and abstract classes without using pointers (avoiding the use of new when possible), and I came across a behavior that makes sense but I havent found documentation on it on the internet (neither a name for it or example).
I create a class, Abstract that has two methods, one is d... | Your example seems simple -- and for the most part, it is. But it leads to some important concepts. First, what you can do is a google on c++ polymorphism. There are a lot of hits, and the first several didn't seem to be wrong.
Let's look at some of your code:
virtual void DoSomethingAbstract() = 0;
This is referred ... |
73,194,326 | 73,208,035 | What wrong with OMP APIs? | Sorry again for my ignorance, I want to run #include <omp.h> for the #pragma omp parallel for command.
As it didn't work for me I checked my gcc version and it is 5.1.0, I added the libgomp.a and libgomp.spec files to the mingw lib folder. From codeblocks-> settings-> compiler I added -fopenmp
on other compiler options... | GCC 5.1.0 is extremely old!
Use a newer GCC (current is 12.1.0) with MinGW-w64 (instead of MinGW, which is also very old).
There is a standalone package available for both 32-bit and 64-bit Windows at https://winlibs.com/ and the site also explains how to configure Code::Blocks to use it.
|
73,194,469 | 73,194,618 | c++20 template parameter of random_access_iterator concept, cannot accept iterator type? | For c++ 20 concept, I had a quick test:
#include<iostream>
#include<vector>
using namespace std;
template <random_access_iterator I>
void advance(I &iter, int n) {
cout << "random_access_iterator" << '\n';
}
int main() {
vector vec{1, 2, 3};
{
vector<int>::iterator itRa = vec.begin();
advan... | begin() returns an iterator by-value, meaning the call expression is a prvalue. You can't pass a prvalue as an argument to a non-const lvalue reference parameter. That is not specific to iterators. It applies to any type, e.g.
void f(int&);
//...
f(1234); // fails because 1234 is a prvalue
To allow for prvalues as a... |
73,194,620 | 73,260,140 | How do I get the size of a c-string input in cin? | So, basically I want to write a program in c++ that encrypts text by moving the chars by a random number in the ascii table. But first I need to get a string by the user. When I want to store the c-string in a char array my problem is that I first need to know the size of the string to have the right size in the array.... | Below are two simple approaches to solving this problem you have.
You can choose one of them based on the needs of your program.
Here:
#include <iostream>
#include <string>
#define METHOD_NUM 1 // set this to 1 for the 1st approach
// or 2 for the 2nd approach
int main( )
{
// an arbitrary si... |
73,194,762 | 73,195,339 | C++ file doesn't recognize function defined in assembly file | I'm trying to learn some assembly code and I'm following a tutorial proposed by a book, I've got a C++ code defined as follows (Ch02_01.cpp) :
#include <iostream>
using namespace std;
extern "C" int IntegerAddSub_(int a, int b, int c, int d);
int main() {
int a, b, c, d, result;
a = 101; b = 34; c = -190; d... | You need to tell CMake that the project includes nasm code too - or masm if that's what it actually is.
Example:
cmake_minimum_required(VERSION 3.22)
project(Assembly CXX ASM_NASM) # or perhaps it should be ASM_MASM
set(CMAKE_CXX_STANDARD 14)
add_executable(Assembly Ch02_01.asm Ch02_01.cpp)
This makes it at least tr... |
73,195,147 | 73,196,580 | Converting shift-jis encoded file to to utf-8 in c++ | I am trying with below code to convert from shift-jis file to utf-8, but when we open the output file it has corrupted characters, looks like something is missed out here, any thoughts?
// From file
FILE* shiftJisFile = _tfopen(lpszShiftJs, _T("rb"));
int nLen = _filelength(fileno(shiftJisFile));
LPSTR lpszBuf = new ch... | There are multiple problems.
The first problem is that when you are writing the output file, you need to set it to binary for the same reason you need to do so when reading the input.
fstream File("filepath", std::ios::out | std::ios::binary);
The second problem is that when you are reading the input file, you are onl... |
73,196,578 | 73,906,542 | Why do some classes of a library need to be included and not others? | Starting Point
I have a C++ application (working with VS2019, Window 10 64bit), which heavily relies on the Open3D library. Everything was working perfectly fine, I was using the previous version (0.14.x), which I built from source using CMAKE and Visual Studio 2019.
There are some features in the new version (0.15.1) ... | A namespace has nothing to do with including files. It's just a way of grouping and organizing classes, functions, etc. For instance, vector and cout are both in the std namespace. But #include does not give you access to the vector class. Why would it? Vectors have nothing to do with I/O; it would be upsetting if the... |
73,196,817 | 73,196,965 | Why do lambda functions need to capture [this] pointer explicitly in c++20? | Pre-c++20, the this pointer is captured in [=] implicity. So what's the reason that c++20 decided that user should write [=, this] to capture this pointer explicitly, I mean, without this change, the pre-c++20 code could have any code-smell or potential bug?
Any good sample or reason for this language change?
| This is explain in P0806, which as the title says, "Deprecate[d] implicit capture of this via [=]"
The argument in the paper is that at this point we had [this] (captures the this pointer) and [*this] (captures the object itself), and [&] (captures the object by reference, which is basically capturing the this pointer ... |
73,197,114 | 73,197,864 | Entering a folder with a template path - C++ MFC | I am using Visual Studio C++ 2017 Professional and MFC
I am working on a project which has a function that collects file paths (like C:/foo1/foo2/foo3.txt) as strings, if a file with that path exists (found using the filesystem library).
At first this looks straightforward until I see that the file paths often are sim... | Once you replace YOUR env variables (%A, %B, etc.), then FindFirstFile, FindNextFile API calls support wild cards.
|
73,197,738 | 73,197,871 | C++11 lambda: when do we need to capture [*this] instead of [this]? | For a quick sample we could see:
class Foo {
std::string s_;
int i_;
public:
Foo(const std::string& s, int i) : s_(s), i_(i) {}
void Print() {
auto do_print = [this](){
std::cout << s_ << std::endl;
std::cout << i_ << std::endl;
};
do_print();
}
};
Ok, capture [this], so the lambda d... | You capture *this if you want a copy of the element to be captured. This can be useful if the element may change or go out of scope after the lambda is created, but you want an element that is as it was at the time of creating the lambda.
#include <iostream>
class Foo {
std::string s_;
int i_;
public:
Foo... |
73,198,042 | 73,198,060 | What is the >> operator really doing in this C++ code? | I am following along with Programming: Principles and Practice Using C++, and I am messing with the "get from" (>>) operator from some code in the third chapter. Here is a minimal reproducible version.
#include<iostream>
using namespace std;
int main() {
int first_num;
int second_num;
cout << "Enter a numb... | The program has undefined behavior because you bitshift using second_num which is not initialized.
first_num >> second_num // right shift `second_num` bits
Note that the operator >> you use above is not the same as the overload used to extract a value from std::cin.
|
73,198,292 | 73,198,739 | Cannot convert argument 1 from 'const char[13] to 'char*' | I am attempting to implement some TWAIN functionality into a QT project.
I have opened this code from the provider and compiled it. However when I past the code into my project it wont compile.
Basically I have 3 files CommonTWAIN.h, TwainAPP.cpp, and DSMInterface.cpp.
In CommonTwain.h I define a constant I believe, ca... | you should be able to cast it away:
LoadDSMLib((char*)(kTWAIN_DSM_DIR kTWAIN_DSM_DLL_NAME))
as long as the function isn't trying to modify the string it should be fine.
|
73,198,350 | 73,198,640 | C++11/14/17 Lambda reference capture [&] doesn't copy [*this] | Refer to this thread: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0806r2.html
It says:
In other words, one default capture ([&]) captures *this in the way that would be redundant when spelled out, but the other capture ([=]) captures it in the non-redundant way.
Which says that pre c++17, the [=] captur... |
[=], [this], [=, this] and [&, this] all captures this by value. That is, it copies the value of the pointer that is this.
[&] captures *this by reference. That is, this in the lambda is a pointer to *this outside the lambda.
The effect of the above versions with regards to this in the lambda will therefore be the sa... |
73,198,589 | 73,212,112 | Concept requires parameter list with template parameters | What I'm trying to do is find a clean way to implement a concept for a callable object that takes in a single parameter of type either int or long.
My first attempt was to create a single concept with a secondary template parameter to ensure the parameter type is either int or long. The problem with this approach, as s... | After some browsing around, I came across https://stackoverflow.com/a/43526780/1196226 and https://stackoverflow.com/a/22632571/1196226. I was able to utilize these answers to build out a solution that can apply concepts to parameters concisely and without the compiler losing the ability to infer template parameters.
/... |
73,198,594 | 73,198,718 | How does std::conditional_t<std::is_enum_v<T>, TypeWhenTrue, TypeWhenFalse> determine how to evaluate? | It seems that std::conditional_t<B,T,F> doesn't always return the second value, even when B is false. Here's an example:
#include <type_traits>
template<class T>
using UnderlyingType = std::conditional_t< std::is_enum_v<T>, std::underlying_type_t<T>, T >;
template< typename T >
constexpr UnderlyingType<T> toUnderlyi... | std::conditional doesnt even get to choose one of the types, because the first argument isnt a type. std::underlying_type_t<int> just doesnt exist. From cppreference:
If T is a complete enumeration (enum) type, provides a member typedef type that names the underlying type of T.
Otherwise, the behavior is undefined. (u... |
73,198,653 | 73,200,002 | Creating custom boost serialization output archive | I'm trying to use Boost serialization to serialize objects into a buffer. The objects are large (hundreds of MB) so I don't want to use binary_oarchive to serialize them into an std::stringstream to then copy-them into their final destination. I have a Buffer class which I would like to use instead.
The problem is, bin... | Don't create your own archive class. Like the commenter said, use the streambuf interface to your advantage. The upside is that things will work for any of the archive implementations, including binary archives, and perhaps more interestingly things like the EOS Portable Archive implementation.
The streambuf interface ... |
73,198,732 | 73,198,899 | Using V8 Isolate in separate thread | I have a program that uses a v8 isolate to execute javascript code. I would like to spawn a separate thread and execute code in the isolate there too. The thread does not need to run in parallel, I am only using the separate thread so I can cancel it from a signal handler on the main thread.
I am currently using pthr... |
The thread does not need to run in parallel
You do not need to lock with v8::Locker lock(isolate);
Debug check failed: blocks_.empty().
You don't seem to enter the isolate v8::Isolate::Scope scope(isolate); after the lock.
void *call(void* vargs) {
Isolate *isolate = (thread_args *) vargs;
try {
... |
73,199,078 | 73,199,416 | Set every nth bit in an integer without for loop | Is there a way to set every nth bit in an integer without using a for loop?
For example, if n = 3, then the result should be ...100100100100. This is easy enough with a for loop, but I am curious if this can be done without one.
--
For my particular application, I need to do this with a custom 256-bit integer type, tha... |
… I need to do this with a custom 256-bit integer type.
Set r to 256 % n.
Set d to ((uint256_t) 1 << n) - 1. Then the binary representation of d is a string of n 1 bits.
Set t to UINT256_MAX << r >> r. This removes the top r bits from UINT256_MAX. UINT256_MAX is of course 2256−1. This leaves t as a string of width-r ... |
73,199,739 | 73,199,839 | Is it safe to call exit() from a C++ function to terminate the program? | I've read several questions here on Stack Overflow, Microsoft docs, and cplusplus.com. Some claim that exit() terminates the program normally, just as a return 0; would from main. Others claim that exit() doesn't call all the destructors, etc. So I was wondering if someone could help.
edit:
As someone asked, I added so... |
Some claim that exit() terminates the program normally, just as a return 0; would from main
std::exit gets called anyway, as part of standard application lifecycle. Quote from CPPReference:
Returning from the main function, either by a return statement or by
reaching the end of the function performs the normal funct... |
73,199,996 | 73,200,081 | How to produce a compilation error if a pointer to a particular object is deleted? | I have a pretty large and verbose codebase and I am trying to find a trick to discover if an object of a particular class has gone through a delete anywhere in the code, preferably by giving me a compilation error if this is the case.
I found out that you can overload the delete operator as in: void operator delete(voi... | You cannot new an object for which the corresponding operator delete is unusable because construction of the new object or the initializer of the new-expression may throw exceptions and then the new expression must be able to call operator delete to free the memory again.
Also note that often the global allocation and ... |
73,200,721 | 73,200,742 | Why don't temporary return types of rvalue functors cause undefined behavior? | I'm new to rvalues and lvalues so please forgive me.
Say I have the following code:
int&& temp() { return 5400; }
int x = temp();
This code compiles just fine with MSVC. When I print out x, it prints 5400. Shouldn't this not be possible, since temp() returns a reference to a destroyed object?
| It does cause undefined behavior because you are returning and accessing a reference to an object that is destroyed when the function returns, specifically a temporary int object materialized from the 5400 prvalue in the return statement to bind the reference in the return value to. Whether the return type is a (const)... |
73,201,708 | 73,201,780 | std::array's data member is public in a standard library implementation. Why? | I was trying to study standard library implementation of the containers that are part of the C++ standard library. I have Microsoft Visual Studio 2022 on my machine and I could go to the header file definition of std::array class.
While I reached the end of the class definition of std::array class, I noticed that the d... | It is required that std::array have a public member to satisfy the requirement that std::array be an aggregate.
An array is an aggregate that can be list-initialized with up to N elements whose types are convertible to T.
https://eel.is/c++draft/array#overview-2
It doesn't however specify what the public member shoul... |
73,201,859 | 73,205,159 | Is it okay to bind the same OpenGL object twice? | I've been writing some code to check if a texture, buffer, or shader is currently bound, and avoid binding it twice if it is.
if (lastShaderBound != shaderName) {
lastShaderBound = shaderName);
glUseProgram(shaderName);
}
However, there's a potential pitfall; if any of these objects are deleted while bound, Op... | It is technically legal to bind the same shader or texture again.
There would be costs associated with either binding overheads or branching.
Consider following code
QElapsedTimer elapsetimer;
elapsetimer.start();
ResourceManager::GetShader("Screen").Use(); // glUseProgram(this->ID);
for (int i = 0; i < 10... |
73,201,872 | 73,201,955 | Forward declare instantiated template class | We forward declare class in the api.h files, like the struct Abc in example below, because we only use std::shared_ptr<Abc>
This has the advantage we can change the definition of struct Abc without recompiling api.h related files. But this forward declaration doesn't seem to work with instantiated template class, like ... |
But this forward declaration doesn't seem to work with instantiated template class, like the commented using Xyz = std::map<int, int>. Can anybody explain why it is so?
Because typedeffing a template does not instantiate the template.
Note that when we instantiate a class template for the first time a new type like C... |
73,202,178 | 73,202,285 | uint8 array passing value fail - only one uint8_t sent | I try to start a array in the header file
rs485.h
class RS485
{
public:
uint8_t off[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07};
void sendmsg(uint8_t* cmd);
};
rs485.cpp
void RS485::sendmsg(uint8_t* cmd)
{
//digitalWrite(ENTX_PIN, HIGH); // enable to transmit
Serial.println("sending message----------... | A member variable declared as
uint8_t off[] = { ... };
does not become an array with the number of elements in the initializer list, like when you declare a non-member variable. Instead, it then becomes a "flexible array" (a C thing that g++ enables by default in C++) - and flexible arrays can't have initializers, whi... |
73,202,227 | 73,202,315 | Getting a substr from a std::variant<std::string, std::vector<std::string>>> in C++ | So I've got a map with a string key and either a string or vector value. I want to cycle through all the string values (whether they're found in a vector or they can be directly checked) in the map and check if they match a given string (it's irrelevant what the string is). If that string matches completely or partly, ... | Here's how to tell what type a variant holds
std::string* pstr = std::get_if<std::string>(&h->second);
if (pstr != nullptr)
{
// do stuff with string
}
else
{
std::vector<std::string>& vec = std::get<std::vector<std::string>>(h->second);
// do stuff with vector
}
BTW you can simplify this monstrosity
for (... |
73,202,376 | 73,202,630 | Segmentation fault in Linked List code, deletion part | I am trying to code for insertion and deletion in linked list.
Here is my code for basic insertion and deletion of nodes in a singly linked list.
There are no errors in the code, but the output on the terminal shows segmentation fault. Can someone explain why am I getting a segmentation fault? And what changes do i mak... | The problem is not with the delete function since even commenting it out leads to segmentation fault.
The problem is that you are initializing tail = head which is set to nullptr at the start. However, when you insertAtHead, you set the value of head but leave the tail to nullptr. You need to do tail = head when adding... |
73,202,679 | 73,202,874 | Problem using std::transform with lambdas VS std::transform with std::bind | I am using Clang 14.0.0 and C++20. My goal is to write a general function in order to use std::lerp on a set of elements. So I came up with this:
template <typename InputIterator, typename OutputIterator>
constexpr OutputIterator
lerp_element(InputIterator first, InputIterator last, OutputIterator result,
... | The function argument to std::bind or std::bind_front should not be invoked, but rather the function itself is passed as the first argument:
using T = std::iter_value_t<InputIterator>;
using F = T (*)(T, T, T) noexcept;
return std::transform(first, last, result,
std::bind_front<F>(std::lerp, a, b... |
73,202,732 | 73,203,881 | Slight acos precision difference between Clang and Visual C++ | I have some cross platform code I'm working with. On the Mac it's compiled with Clang, on Windows it's compiled with Visual C++.
There is a calculation that can be sensitive, and there was a difference between Mac and Windows that was triggering asserts. It ends up there is a difference between acos results, but I'm no... | If you look at the binary representation of these floating point values you can see that the mac/clang's value A is the next lowest floating-point number than windows/msvc's value B
A 3.14159250 0x40490FDA
B 3.14159274 0x40490FDB
Whilst B is closest to the true value of π, it is actually greater than π as ... |
73,202,761 | 73,202,784 | What does this do in C++? []() {}() | I am unit testing for code coverage, making sure that every possible code path is executed by a unit test.
I find that a switch/case element which merely contains a break can be breakpointed, but that the break is never hit, control just jumps to the end of the switch, presumably because of compiler optimization.
A col... | This is an empty lambda that gets executed and does nothing. Usually to set a breakpoint in debugging, at the end of a function or another code block.
[] () { } ()
^^^ ------------------- no captures
^^^ ---------------- no parameters
^^^------------ function body
^^ ------- call operator (ope... |
73,202,795 | 73,425,351 | vector<int> pushback causes runtime error? | For some reason, if I don't have a certain line commented out my code doesn't work.
Here are my three files: Maze.hpp, Kruskal.cpp, main.cpp,
#include <vector>
#include <utility>
#include <cstdlib>
using namespace std;
class KruskalGenerator{
private:
void GetNextDirection();
public:
};
#include "Maz... | The issue was that there were two DLLs on my machine. One was old and outdated, the other new and updated. Windows was defaulting to the old one, so I overwrote that DLL with the new one.
A better solution was most likely to simply delete the old DLL that way it wouldn't conflict, but since for some reason the old one ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.