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 |
|---|---|---|---|---|
68,092,000 | 68,092,018 | Comparing chars one by one in a character array with strcmp | I'm writing a c++ script that compare chars of two strings one by one using strcmp().
I wrote this code:
char test1[1];
char test2[1];
test1[0]=str1[i]; //str1 is a char array
test2[0]=str2[i]; //str2 is a char array
int result=strcmp(test1,test2);
but if I print test1 or tes... | strcmp() takes null-terminated strings, but neither of your char[] arrays are null-terminated.
char test1[2]; // <-- increase this!
char test2[2]; // <-- increase this!
test1[0] = str1[i];
test1[1] = '\0'; // <-- add this!
test2[0] = str2[i];
test2[1] = '\0'; // <-- add this!
int result = strcmp(test1, test2);
Otherw... |
68,092,185 | 68,092,250 | Unexpected output from adding bits to integer (cpp) | Problem
Hello, this is my first stack overflow question. I'm using Bit-boards to represent board states in my chess engine. Currently I have a bit-board class like so:
class Bitboard {
public:
uint64_t Board = 0ULL;
void SetSquareValue(int Square) {
Board |= (1ULL << Square); ... | You’re running afoul of operator precedence. << binds more strongly than ?:, so the bitwise expression is printed directly, and the conditional expression is performed on the resultant state of the stream and has no effect.
Add parentheses around your intended conditional expression: presumably, cout << ((Board & (1ULL... |
68,092,284 | 68,094,775 | How to properly solve macro conflict (GetMessage) between Windows API and DirectX API & other APIs developed by microsoft | Problem:
I'm developing a desktop D3D12 application, so naturally, I need <Windows.h> and <WinUser.h> it included to be able to create a window, but there's a GetMessage macro that conflicts with IDXGIInfoQueue::GetMessage and ID3D12InfoQueue::GetMessage (and also ID3D11InfoQueue::GetMessage ID3D10InfoQueue::GetMessage... | nothing need do here and no any conflict or problems in your code. you already viewed this yourself
it compiled successfully and these methods can still be called
normally runtime
and you correct - methods called not by name but by address in virtual table. the winuser.h always included before IDXGIInfoQueue declarat... |
68,092,431 | 68,101,281 | C++ retrieving multiple types of data from a class | I have made a class that holds all the data that is read from a file.
class Entry
{
std::string key;
std::string value;
std::vector<std::string> arrayString;
std::vector<Entry> arrayEntry;
enum dataValueCheck
{
str,arrStr,arrEnt
};
dataValueCheck dataValue;
public:
Entry(std... | This all gets very easy if you drop the template and return a std::variant from getData. It gets easier still if you store the value in Entry as a std::variant in the first place (you only need to store one of the types in any particular instance of Entry, right?).
Here's a fully worked-up example. Note that I pass t... |
68,092,848 | 68,092,887 | C++: I'm trying to create a calculator, but every time I try to divide, substract, or multiply, the calculator only keeps adding | I'm trying to create a calculator, but every time I try to divide, substract, or multiply, the calculator only keeps adding. I'm dutch btw, so
Add,
Substract,
Multiply,
Divide
Antwoord = answer
Bewerking = operator
Pls help! It's for a school assignment.
Code below
#include <iostream.h>
#include <conio.h>
int main (... | The if (Bewerking = '+') {antwoord = A + B;} always returns true, since you assign Bewerking = '+' not compare Bewerking == '+'.
You need to change all the conditions to have the following form:
if (Bewerking == '+');
Yet, clearing this bug still gives invalid results.
This is because in cin >> Bewerking; user suppli... |
68,093,325 | 68,093,574 | Is it valid to dereference this pointer in C++? | struct myclass{
static const int invalid = -1;
/*explicit*/ myclass(int i, double d = 0.0){
_var = i
}
int _var;
bool operator < (const myclass& rhs);
bool operator > (const myclass& rhs);
bool operator == (const myclass& rhs);
bool operator != (const myclass& rhs);
/*
b... | The more common idiom for this kind of validity testing is to use an explicit operator bool:
struct myclass {
private:
static const int _invalid = -1;
int _var;
public:
explicit myclass(int i, double d = 0.0){
_var = i
}
explicit operator bool() const { return _var != _invalid; }
bool... |
68,093,717 | 68,093,855 | CMake: No such file or directory error with a custom library | I am trying to make a library using CMake.
I would like the library to work as many library widely being used,
so I mimicked several structures of CMake files in the internet and finally made a structure described below, if possible.
Also, I want to use the #includes as shown in the code snippet.
However, I get a fatal... | There is no such variable as ${CMAKE_CURRENT_DIR}. You surely mean ${CMAKE_CURRENT_SOURCE_DIR}. Please see the documentation for the list of CMake variables, here: https://cmake.org/cmake/help/latest/manual/cmake-variables.7.html
For CMAKE_CURRENT_SOURCE_DIR, the documentation is here: https://cmake.org/cmake/help/late... |
68,093,921 | 68,095,568 | Merge 2 sorted linked lists | I am new to data structures and I am trying to code some questions for Linked lists.
The question is to merge 2 sorted Linked lists. I had written the following code for it, but when I am returning next of head from my method I am just getting the last value of the merged linked list. I don't know where I'm going wrong... | You are not incrementing curr after adding a value to the next of that current node, so what really is happening is that you keep on adding values to your current's node next.
To demonstrate
1->5->6 list 1
2->3 list 2
head = new ListNode(); // dummyNode;
current = head; // i.e dummyNode
What happens in the loop:
fir... |
68,094,329 | 68,094,702 | Why is std::vector::push_back declared as constexpr in C++20? | According to cppref, in C++20, std::vector::push_back is declared as follows:
constexpr void push_back(const T& value);
I cannot imagine a scenario in which push_back should be constexpr.
What's the rationale behind?
|
Is there any rationale behind?
This is the abstract of the proposal. There is no separate rationale section:
P1004R2 Making std::vector constexpr
Abstract
std::vector is not currently constexpr friendly. With the loosening of requirements on constexpr in [P0784R1] and related papers, we can now make std::vector cons... |
68,094,444 | 68,094,576 | C++ Using classes in other classes failing | I have a Display class that uses SDL to write pixels to the screen. I'd like another class (Triangle) to be able to use this already existent class object, so I've been trying to pass the object by address.
It's sort of working, in the sense that it is actually calling the methods. However, I was getting a segmentation... | Triangle::Triangle(Display* display) {
display=display;
}
the display is not the member of your class.Use this->display = display instead
|
68,094,553 | 68,094,790 | C++: Building a mulitfunctional calculator | I am trying to build a calculator in C++. I'm new to the program and have to do this for a school assignment, so sorry for my ignorance. English is also my second language so excuse me if I don't make much sense.
Let's say I have two integers A and B for which a user has to assign a value to either add, subtract, etc. ... | Make the variables, and the reading, conditional on the operation.
Example outline:
if (operation takes one input)
{
double x;
cin >> x;
Calculate result...
}
else if (operation takes two inputs)
{
double x, y;
cin >> x >> y;
Calculate result...
}
else if (operation takes three inputs)
{
dou... |
68,095,269 | 68,095,309 | taking input into vector using for-range loop | First of all, I want my user to tell me how many numbers he have to input? Which will create that number of elements in vector initialized to zero. Then I want to use
for-range loop to insert the elements into the vector and similarly an other for-range loop to display the vector elements.
#include<iostream>
#include<v... | std::vector have 2 sizes.
One is actual-used size and the other is reserved-size.
Below creates a vector with actual-size n.
std::vector<int> v(size_type n)
While this creates a vector with empty size and reserved size n.
std::vector<int> v;
v.reserve(n);
std::vector<T>::push_back() increases the actual-size by 1 at ... |
68,095,472 | 68,098,941 | Is there an alternative to std::this_thread::sleep_for that receives std::stop_token besides time duration? | I would like to use std::this_thread::sleep_for and std::this_thread::sleep_until with std::stop_token where the functions return if stop is requested on std::stop_token (ex. jthread destruction is called).
How can I achieve this?
std::jthread thread {[](std::stop_token stoken){
while(!stoken.stop_requested()) {
... | Here is my implementation using std::condition_variable as everyone tells that.
template<typename _Rep, typename _Period>
void sleep_for(const std::chrono::duration<_Rep, _Period>& dur, const std::stop_token& stoken)
{
std::condition_variable cv;
std::mutex mutex_;
std::unique_lock<std::mutex> ul_ {mutex_};... |
68,095,550 | 68,095,729 | C++ write wav file to disk, why is it so loud? | I have written some code that writes a heap allocated float array to disk in the .wav format.
It works great except that the output is really loud and distorted.
Here is the code that I currently have to write the wav file:
typedef struct WAV_HEADER {
uint8_t riff[4] = {'R', 'I', 'F', 'F'};
uint32_t overall_size;
... | You are using the wrong format type in your header.
As you can see here you use format_type 1 for PCM data, but you have float data.
You should be using 3 instead.
|
68,095,945 | 68,096,311 | C++11/Qt Memory leak despite moving | I want to generate a QJsonDocument using a language similar to XPath. For example give this set of parameters:
"#/node1/node2/val"
"hello"
Should yield:
{
"node1":{
"node2":{
"val": "hello"
}
}
}
My implementation looks like this:
QJsonDocument doc;
const auto ascending_construct = [&... | std::move "hollows out" the referenced object but does not automatically delete it, so you are indeed leaking memory.
Luckily, this is not needed as QJsonObjects are implicitly shared. So:
const auto ascending_construct = [&](const QString& json_pointer, QJsonValue val){
auto components = json_pointer.split("/");
... |
68,096,012 | 68,096,116 | How is the size of the std::array calculated in the template | #include <array>
#include <cstdef>
#include <iostream>
// printArray is a template function
template <class T, std::size_t size> // parameterize the element type and size
void printArray(const std::array<T, size>& myArray)
{
for (auto element : myArray)
std::cout << element << ' ';
std::cout << '\n';
... | First, std::array is a template. When you write
std::array myArray5{ 9.0, 7.2, 5.4, 3.6, 1.8 };
Then Class Template Argument Deduction (CTAD, deduction guides for std::array can be found here) is applied to infer that myArray5 is of type std::array<double,5>. That is where the size is "calculated".
Then when you call ... |
68,096,028 | 68,096,400 | SFML - Why does a sprite drawn to a window scale with the window (resize) | Here is a MWE
#include <SFML/Graphics.hpp>
#include <string>
#include <iostream>
int main(int argc, char *argv)
{
sf::RenderWindow window(sf::VideoMode(200, 200), "Title");
std::string image_filename;
image_filename = "image.png";
sf::Image image;
if(!image.loadFromFile(image_filename))
{
... | You can add the following event listener to the events loop:
if(event.type == sf::Event::Resized)
{
sf::FloatRect view(0, 0, event.size.width, event.size.height);
window.setView(sf::View(view));
}
This will update the render area to the dimensions of the window every time the window is resized rather than scal... |
68,096,805 | 68,097,895 | simple Lua corotine test crashed at first run | In brief, the test program creates a coroutine at C++ side, launch it with a Lua-side function and resume several times with some logs. It suddenly crashed at the first call to resume that starts coroutine running, with violated access to invalid heap memory (0xfdfdfd).
This is the whole code:
#include <juce_core/juce_... | You have a mistake in the order of arguments for lua_resume
It should be lua_resume(coro, lua, instead of lua_resume(lua, coro,
concepts of k function ... Where should I use these stuffs?
There is a good example on using k-functions
https://stackoverflow.com/a/67961038/1847592
|
68,097,194 | 68,097,259 | sfinae to detect containers: failure for std:array | I am looking for a way to use SFINAE to implement some function, that must be available only to some containers:
vector, list, array (set is there below only as a test)
Build upon this answer, I tried the code below that uses a traits class that returns true only for the required containers.
As you can see online here,... | This is not SFINAE but regular template specialisation. Your std::array is not recognised because a value of type std::size_t (which ist std::array's second argument) is not a typename.
You can change your check for array specifically:
template <typename T, std::size_t N> struct is_container<std::array<T,N>> : std::tru... |
68,097,498 | 68,103,711 | How to cast volatile int** to void** | I have this old C - code that my compiler is warning me about (old C-style cast).
volatile uint32_t* map;
void** argForSomeAPIfunction = (void**)↦
How can I convert this to C++ cast style? I need to convert volatile uint32_t** to void**.
The reason why I need this is that there is a closed-source vendor API that e... | If this is for initialization, then I guess what it does is fill in a void *, not anything else, i.e. as if in C++ you'd have a parameter of type void *&.
I believe it is intended to be used as
void *ptr;
if (API::InitializeRegisterMap(&ptr)) {
...
}
then afterwards you will take the value in ptr and convert that ... |
68,098,014 | 68,098,169 | Strange bug or am i mssing something? | I am trying to insert elements into an array in ascending order, in order to achieve that i made the following code which works. But i would like to use "arrSize" instead of 10 here for (int i = 0; i < 10; i++) (below code works)
int arr[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int element = 7;
int arrSize = sizeof(a... | You are writing past arr[9] in your code and probably overwrite other variables on the stack.
The valid indices in arr[9] are 0..8. Everything else is undefined behaviour.
this:
int arrSize = sizeof(arr)/sizeof(arr[0]);
sets arrSize to 9. And here:
int p = arrSize;
for (; p && element < arr[p - 1]; --p)
arr[p] = a... |
68,098,309 | 68,098,538 | scope and lifetime of a pointer to struct which is local to a function | In the following code I am inserting at last node. It is working fine.
But my doubt is since I have declared Node * last; locally, so whenever a new call is made a new pointer variable will be created and previous one will be removed from the memory after function gets terminated. So how come Node * last; is holding... | Simpler example, same effect:
#include <iostream>
void DONT_DO_THIS(bool init){
int x;
if (init) x = 42;
else std::cout << x << "\n";
}
void foo() {
int y = 0;
}
int main() {
DONT_DO_THIS(true);
DONT_DO_THIS(false);
DONT_DO_THIS(false);
foo();
DONT_DO_THIS(false);
}
Before you re... |
68,098,572 | 68,098,829 | Alternative to std::set_union with additional predicate parameter for merging elements from the intersection | Given two sorted containers and std::set_union, we can provide a predicate to determine when two elements are equal. I would like to provide an additional predicate that will merge the equal elements (the intersection of the containers) and insert the result into the output container.
Please note in the 'Expected outpu... | As @Useless suggests in the comments, to do extra things over an <algorithm>, you should write something based on that algorithm.
Adapted from the possible implementation:
template<class InputIt1, class InputIt2,
class OutputIt, class Compare,
class BinaryOp>
OutputIt set_union_transform(InputIt1 firs... |
68,098,788 | 68,102,730 | Call button click function from grandchild | I'm creating my first C++ wxWidgets application. I'm trying to create some kind of split button where the options are displayed in a grid. I have a custom button class which, when right-clicked on, opens a custom wxPopupTransientWindow that contains other buttons.
When I click on the buttons in the popup, I want to sim... | You should do mBtn->ProcessWindowEvent() which is a shorter synonym for mBtn->GetEventHandler()->ProcessEvent() already mentioned in the comments.
Note that, generally speaking, you're not supposed to create wxEVT_BUTTON events from your own code. In this particular case and with current (and all past) version(s) of wx... |
68,098,839 | 68,099,214 | Using std::function on a templated function | I am trying to use std::function to achieve this (code does not compile, ofc):
template <typename Duration>
void operation1(int i)
{
// do some chrono stuff
}
template <typename Duration>
void operation2(int i)
{
// do other chrono stuff
}
void callFunc(const std::function<void(int)>& func, int i)
{
func<... | It's similar to the question at here, but this question is slightly different because the template cannot be deduced from the argument type.
The template function cannot be passed or evaluated if it's not instantiated as the answer at the link.
So you should change your function to functor,
struct operation1 {
templa... |
68,098,883 | 68,103,193 | Prolem with parallel openmp multi loop in C++ | I wrote a program to find key with 8 loops.
It takes me 2 hours to found key.
Now i want to use openmp to reduce the time but i can't get it to work, it found nothing.
Please help me i'm new to openmp, thank you.
int main()
{
cout << endl;
clock_t start, end;
cout << "\nStart\n";
start = clock();
in... | Edit: As the OP is new is openMP, I have added more details to my answer.
The problem is with your code is that the collapsed loops has altogether 25^8=152,587,890,625 iterations, which is bigger than the maximum of (32 bit) int (2,147,483,647). The compiler (g++ 10.2) cannot handle this situation and produce incorrect... |
68,098,966 | 68,102,281 | Find files by pattern | I need to find a fews file based on a pattern: C:\Users\Admin\Desktop\*\cities.json and countries.json. Basically it is on the Desktop, but it can be in any folder there.
I found a similar function posted by Thomas Bonini. I don't really need the linux part. How can I do that?
/* Returns a list of files in a directory ... | You need to check recursively (like in merge-sort, for example) if the elements of a directory contains the names of the vector, and if it contains all of them return the vector or in case a recursion returned a match forward that instead.
#include <filesystem>
#include <iostream>
#include <string>
#include <vector>
s... |
68,099,703 | 68,099,935 | How does the compiler deal with the inputs following an invalid input exactly? | I know that, roughly speaking, when the user enters an invalid input, 0 will be assigned to that input (the failbit flag is set on the input stream) and all the subsequent inputs becomes unreliable.
In such cases, I wonder if some unreliable value (or some value with special meaning like 0 above) will be assigned to th... | The various std::istream& operator>>(std::istream& is, arithmetic & num) are functions that an implementation (not just "the compiler") must provide. The standard defines what they do.
The steps are laid out in the definition of FormattedInputFunction and std::num_get::get. Specifically:
If the sentry returned false o... |
68,099,966 | 68,100,086 | Required compile flags in order to user perf | I am trying to understand linux perf and hotspot to understand call stacks/trace of my c++ application.
Should the program compiled in debug mode or in release mode ? Assuming I have only one file inline.cpp. I have seen in one of the example using
g++ -O2 -g inline.cpp -o inline
perf record --call-graph dwarf ./inline... | First of all, -g and -O2 aren't opposites. -g specifies that debugging symbols will be generated, so that you can associate hotspots with actual lines of code. -O2 specifies that code optimization should be performed; this is ordinarily not done with code you intend to run in a debugger because it makes it more difficu... |
68,100,235 | 68,100,407 | Cancel CTRL+C while system() is executing [C++] | How can I make CTRL+C not do anything when I'm currently doing system().
This is my code:
#include <iostream>
#include <functional>
#include <signal.h>
void noCTRLCCancel(int sig) {
signal(SIGINT, noCTRLCCancel);
std::cout << "CTRL+C pressed, not shutting down." << std::endl;
}
inline void command() {
syste... | You can ignore a specific signal with SIG_IGN and set it back to default with SIG_DFL.
void command() {
std::signal(SIGINT, SIG_IGN);
system("some command");
std::signal(SIGINT, SIG_DFL);
}
https://en.cppreference.com/w/cpp/utility/program/signal
|
68,100,775 | 68,101,082 | ranges::view::transform produces an InputIterator preventing the use of std::prev | Consider the following code, which uses the Ranges library from C++20:
#include <vector>
#include <ranges>
#include <iostream>
int main()
{
std::vector<int> v{0,1,2,3,4,5,6,7};
auto transformed = std::ranges::views::transform(v, [](int i){ return i * i; });
std::cout << *std::prev(std::end(transformed));... | It is not a random-access-iterator by C++17's reckoning. transform must return a value rather than a reference, and C++17's iterator categories don't allow that for anything above an InputIterator.
But this type is a std::random_access_iterator by C++20's rules, which allow proxy-like iterators on any iterator/range be... |
68,101,521 | 68,101,587 | How do I fix this issue where my 2D array won't output it's values in C++? | #include <iostream>
using namespace std;
int main(){
string A[5][2] = {{"Shane","M"},{"Michael","M"},{"Devika","F"},{"Akshi","F"},{"Zia","F"}};
for(int i=0; i<5,i++;){
for (int j=0; j<2;j++){
//cout<< "Element at A["<<i<<"]["<<j<<"]: ";
cout<<A[i][j]<<" ";
}
cou... | The loop
for(int i=0; i<5,i++;)
is wrong. The condition i<5,i++ means i++ because the left operand of the comma operator i<5 doesn't have side effect and simply ignored. i++ is evaluated to the value before the increment. In this case the value is 0, so it is considered as false and the loop body won't executed.
The l... |
68,102,199 | 68,102,275 | How to specify file storage | I work with C ++ and I am almost new.
My question is how to specify where to save the text file.
For example, I wrote a program that creates a text file called "usertext.txt"
And it automatically creates the text file in the code storage. But I want to create a folder For example called patch and save the text file the... | Use the functions in the filesystem library to create the directory first. Then use the directory as part of the full name when opening the file.
std::filesystem::create_directories ("/path/to/");
filetext.open("/path/to/usertext.txt", ios::app) ;
You can also use the path class to form the full name if the user give... |
68,102,210 | 68,104,235 | Getting wrong answer in Partition Equal Subset sum on GFG | I am trying to solve the partition equal subset problem on GFG. I am aware of the correct way of doing this via reducing it to the subset sum problem. However, I had another approach in mind and I can't figure out what is wrong with it.
I have maintained two sum variables: partition1 and partition2, and at every recurs... | Your if statement:
if(partition1==partition2 and partition1!=0)
return 1;
can potentially make the function return 1 prematurely, since partition1 can still be equal to partition2 before all numbers have been traversed. The following modification to your code resolves the issue:
int traverse(int N, int arr[], int ... |
68,103,350 | 68,103,412 | Printing different values for ++i||j++&&++k with printf vs cout | This code prints different values for ++i||j++&&++k depending on whether the printf function or cout is used. Why is that?
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
int i = 1,j=1,k=1;
cout<<++i||j++&&++k;
printf("%d", ++i||j++ && ++k);
}
| According to C++ Operator Precedence - cppreference.com, the << operator has higher precedence than || operator. Therefore, the statement
cout<<++i||j++&&++k;
means
(cout<<++i) || j++&&++k;
Therefore, the value of i after the increment is printed.
In the other hand, the value of ++i||j++ && ++k will be printed by
pri... |
68,103,529 | 68,103,629 | Division Function w/ Multiple Return Possibilities | I'm working on a school assignment, but I'm having trouble with a problem.
The problem is as follows:
"Write a function called divideIt that takes two integers, divides them, and returns the result as a float. Have this function skip division when it encounters an unacceptable value, and also retain the decimals. Do yo... |
If I skip division because of an unacceptable value, what do I place in return?
You could return std::nanf ('not a number'):
if (num2 == 0)
return std::nanf ("");
There is also a corresponding std::isnan function.
Also, I'm not sure about the "Do you know what to quit on?" line.
Presumably, they mean 'what do ... |
68,103,581 | 68,104,741 | Wrap a C++ object without move constructor in a unique_ptr? | So I'm pretty new to move-semantics and modern C++ in general, but as far as I understood, I could write code like
Foo doSomething(Bar b) {
Foo f{b};
return f;
}
Note that I did not explicitly write std::move to allow the compiler to apply RVO.
I do not want to modify Foo or Bar and the compiler fails with Cal... | As I understand it.
Traditionally return value optimization was just that, an optimization (albeit one that could potentially change the behavior of your program). So the copy constructor had to be available (not be "deleted"), even if the compiler decided in the end that it did not need to use it.
C++11 introduced mov... |
68,104,048 | 68,104,146 | How to use exprtk to evaluate an equasion as bool? | I'm trying to run this code:
exprtk::parser<bool> parser;
exprtk::expression<bool> expression;
parser.compile("5 > 6", expression);
std::cout << expression.value() << "\n";
But I get this error:
'exprtk::expression<T>::operator T(void) const': member function already defined or declared
On VS 2019. This doesn't happe... | From the documentation:
exprtk::expression<NumericType>
Note: NumericType can be any floating
point type. This includes but is not limited to: float, double, long
double, MPFR or any custom type conforming to an interface comptaible (sic)
with the standard floating point type.
bool is not a floating-point type.
|
68,104,126 | 68,104,262 | Where do I put the QT5 clone in this project | This is my first time every using C++ so please go easy on me. I have about 7000 hours of Python experience so I'm not completely clueless. I'm trying to read the code written for the Collatinus software found here. collatinus. It seems that the initial file is this:
VERSION = "11.2"
DEFINES += VERSION=\\\"$$VERSIO... |
Where do I put the QT5 clone in this project
You don't :)
Qt installations up to 5.14 are not relocatable. That means that once Qt is installed, if you move it to another path, it'll break. Just don't mess with it: once installed, you leave it alone, and it'll work just fine.
Qt source code has to be built before it ... |
68,104,215 | 68,104,240 | Runtime Error: Runtime ErrorSegmentation Fault (SIGSEGV) for the code below | I have solved the parenthesis check problem in gfg. when I checked this code with custom input it's working fine and the output is matched . when I submit this code, it shows
Runtime Error: Runtime ErrorSegmentation Fault (SIGSEGV)
bool ispar(string x)
{
int n=x.length();
stack <char> s;
int i=0;
whil... | You are doing s.top() without checking if s is empty. You should add check for that.
else if (!s.empty() && (x[i]==']'&& s.top()=='['|| x[i]==')'&& s.top()=='('||x[i]=='}'&& s.top()=='{'))
s.pop();
|
68,104,580 | 68,104,614 | C++ How to make Struct Input/Print via Pointers | struct Student
{
char* name;
int balls;
};
void inputdata(Student **s, int *n)
{
int nn;
printf("%s\n", "Input amount of students");
scanf("%i", &nn);
Student* a = new Student[nn];
for (int i = 0; i < nn; ++i)
{
scanf("%s", &a[i].name);
scanf("%i", &a[i].balls);
}
... |
You should pass pointers to what should be modified in callee functions.
Callee functions should dereference pointers passed to modify what should be modified.
You have to allocate for strings before reading.
It is inconsistent that an array of Student in the function inputdata but an array of Student* is required in ... |
68,105,299 | 68,105,569 | How to implement a 2 into every 3 hits to return a true? | I am trying to implement a generic algorithm for 2 in every 5 hit will return a true.2 is the allowed and 5 is the hits. In short this means if a function is called 5 times 2 of those times it will return true otherwise it will be a false. This is my try and it seems to be incorrect. Any suggestions on how I can fix i... | I understand that you want to generate a deterministic sequence of allowedLimit ones followed by hitlimit - allowedlimit zeros. This is a periodic sequence that can be easily calculated from the current index:
int hitlimit = 3;
int allowedlimit = 2;
int hitsTracker = 0;
bool test() {
return hitsTracker++ % hitlimit... |
68,105,429 | 68,105,628 | Window procedure and CreateWindowEx function | Does the Window Procedure specified as lpfnWndProc by window class during registration runs in a separate thread ?
| There is an important concept in windows called the message loop.
It is usually inside the main function (aka: WinMain) and can be characterized in the following manner:
while (true) {
// blocks until there's a new message to process
GetMessage()
TranslateMessage()
// ends up calling the propper WndProc callbac... |
68,105,736 | 68,113,677 | Boost JSON serialization format (boost 1.76.0) | How to control the serialization format in the boost json library. I am trying to serialize this object and the floats are being output in scientific notation. How to output in fixed notation like 12000000 instead of 1.2E7? And 0 instead of 0E0.
i.e.
{"id":"de69041b-141b-4e01-b349-458f26f08259","price":3.343403E12,"qty... | To the best of my knowledge that is not a feature. There has been a fair bit of discussion on the boost mailing list when the library was being reviewed prior to acceptance, so if you want you can check the archives for the rationale.
My recollection of it is that the library focuses on a narrow featureset facilitating... |
68,105,849 | 68,105,966 | Vulkan: Image error when recreating the swapchain after a window resize | So I'm trying to handle window resizing by recreating the swapchain and its image views and all that. This is the method that I'm using:
void VxRenderer::recreateSwapchain() {
device.waitIdle();
for (uint32_t i = 0; i < swapchainImageCount; ++i) {
vkDestroyFramebuffer(device, framebuffers[i], nullptr);... | You need to transfer your image from the undefined layout in which it starts to a presentable image format, depending on what exactly you're doing with it. For example, if you're using it as a texture in a shader, it needs to be in SHADER_READ_ONLY_OPTIMAL layout.
You can do this in multiple ways, one of them being an ... |
68,105,962 | 68,107,049 | Input integer and display individual number and sum of numbers | Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. For example, it should output the individual digits of 3456 as 3 4 5 6, output the individual digits of 8030 as 80 3 0, output the individual digits of 2345526 as 2 3 4 5 5 2 6,... | I'll go line by line:
Each iteration of the loop will effectively "pop" the first digit off of the loop. Let's say the number is 1234 (or 1000 + 200 + 30 + 4). To start the loop off, we'll have div = 1000 (since that's the highest power in the number) and tempNum = 1234
Let's look at a single iteration of the loop:
Th... |
68,106,089 | 68,106,849 | OpenMP - "#pragma omp critical" importance | So I started using OpenMP (multithreading) to increase the speed of my matrix multiplication and I witnessed weird things: when I turn off OpenMP Support (in Visual Studio 2019) my nested for-loop completes 2x faster. So I removed "#pragma omp critical" to test if it slows down the proccess significantly and the procce... |
Here's my question: is "#pragma omp critical" important in nested
loop? Can't I just skip it?
If the matrices m, this and A are different you do not need any critical region. Instead, you need to ensure that each thread will write to a different position of the matrix m as follows:
#pragma omp parallel for col... |
68,106,146 | 68,119,705 | How to access serialized data of Cap'n'Proto? | I'm working with Cap'n'Proto and my understanding is there is no need to do serialization as it's already being done. So my question is, how would I access the serialized data and get it's size so that I can pass it in as a byte array to another library.
// person.capnp
struct Person {
name @0 :Text;
age @1 :In... | This appears to be whats needed.
// ...
::capnp::MallocMessageBuilder message;
Person::Builder person = message.initRoot<Person>();
person.setName("me");
person.setAge(20);
kj::Array<capnp::word> dataArr = capnp::messageToFlatArray(message);
kj::ArrayPtr<kj::byte> bytes = dataArr.asBytes();
std::string data(bytes.be... |
68,106,357 | 68,106,398 | Why create std::move and not use static_cast | I don't understand the reason why std::move() had to be created. Couldn't everything just be static_cast<T&&>() instead? The only reason that I find why std::move() might have been created is just to make code easier to read. So, instead of seeing static_cast, programmers could see std::move() and understand what it is... | Yes, it's mostly about readability.
In addition to clearly expressing the intent, std::move doesn't require you to manually write the type.
|
68,106,790 | 68,106,972 | static_assert inside a macro throwing compile time errors even when it shouldn't (Visual Studio) | tl;dr
When I try to compile this code, Visual Studio throws a compile time error for very static_assert, regardless of wheter it should, and then also one "active error" for the only one that should. This is an issue with my code, or with Visual Studio?
Visual Studio Version
Microsoft Visual Studio Community 2019
Versi... | @1201ProgramAlarm answered in the comments. The solution was to use std::remove_reference to remove the reference added to the ptr when it is passed into the lambda. The final macro was:
#define cast_to_A(ptr) ([&] () { \
static_assert( \
std::is_same<std::shared_ptr<Node>, std::remove_reference<decltype(pt... |
68,107,164 | 68,107,794 | Missing resource name in Code::Blocks and therefore FindResource doesn't work | I have a project in Code::Blocks.
In my resource.rc file I have
#ifndef IDC_STATIC
#define IDC_STATIC (-1)
#endif
#define TWEETY 102
In my resource.h file I have
#include <windows.h>
#include <commctrl.h>
#include <richedit.h>
#include "resource.h"
TWEETY IMAGE "Tweety.png"
I build ... | Resource types are identified by ID or name. Your resource script defines a resource type with name IMAGE (that's why you see "IMAGE" in ResEdit; note the quotation marks).
You are passing a resource type with name PNG to the call to FindResource. The module doesn't have a resource type named PNG. It contains a resourc... |
68,107,348 | 68,107,532 | why std::filesystem::current_path() returns different variables when im in editor and using .exe | I have my project where i am using filesystem to retrieve directory of assets.
When i am lunching my program in editor(im using Visual Studio 2019) everything is fine and this code return value of working direcotry of project.
std::string currentPath = std::filesystem::current_path().string();
But when i am lunching ... |
So my question is why is that happening
It happens because you've configured the editor to set the working directory to one path, while you're running the program with another working directory outside the editor.
how can i resolve this problem.Becouse of that i cannot automatically load assets when lounching app fr... |
68,107,837 | 68,107,961 | Visual Studio C++ C2022. Too big for character error occurs when trying to print a Unicode character | When I try to print a Unicode character to console. Visual Studio gives me an error. How do I fix this and get Visual Studio to print the Unicode character?
#include <iostream>
int main() {
std::cout << "\x2713";
return 0;
}
| Quite simply, \x2713 is too large for a single character. If you wanted two characters, you need to do \x27\x13, if you wanted the wide character, then you need to prefix with L, i.e. L"\x2713", then use std::wcout instead of std::cout.
Note, from the C++20 standard (draft) [lex.ccon]/7 (emphasis mine):
The escape \oo... |
68,108,232 | 68,108,529 | C++ constexpr final virtual functions | I'm implementing a pure virtual function in a C++ derived class, and mark the method final. I would also like to mark the function constexpr, but it appears the standard doesn't allow this.
Is there any practical reason why it would be difficult for compilers to implement this? Or is such a feature omitted due to the ... |
C++20 adds support for this code.
On godbolt, we can try it out: https://godbolt.org/z/f64e93dzY
It looks like this is Defect Report 647
|
68,108,507 | 68,108,712 | How to convert const char& to const std::string&? | std::stof() needs:
float std::stof(const std::wstring &,size_t *)
float std::stof(const std::string &,size_t *)
This function is to convert a string, which is delimited by whitespaces, into a vector containing floats. I try to use the std::stof() function to convert the characters into floats. I cannot find a solution... | You should actually search for the whitespace separators and extract substrings between them accordingly, eg:
#include <string>
#include <vector>
#include <cctype>
std::vector<float> parseLine(const std::string &line)
{
auto is_space = [](unsigned char ch){ return std::isspace(ch); };
std::vector<float> parsed... |
68,108,587 | 68,109,996 | How to overload the stringstream insertion operator? | I would like to parse a comma-separated-value string with a stringstream without having to call stringstream::ignore() for each value.
std::string csvString = "1,2,3,4";
int i1, i2;
std::stringstream ss(csvString);
ss >> i1;
ss >> i2;
if (ss.fail())
throw "failed!"
Most tutorials about overloading the insertion ope... | As cigien said in the comments, the problem was that the right hand side parameter is not passed by reference. The following code works correctly:
template<typename T>
ParserStream & operator>>(T & val)
{
m_ss >> val;
m_ss.ignore();
return *this;
}
|
68,108,804 | 68,108,834 | C++ Efficiency of Classes vs Structs | In C++, I'm trying to decide whether or not to use a struct or class. So far I understand that both are more or less identical, but a class is used more often when private variables are needed or to group the concept of an object that performs actions.
But what I'm wondering is: Does including functions within a class ... |
C++ Efficiency of Classes vs Structs
Structs are classes. There is zero efficiency between one and the other.
Does including functions within a class increase the memory requirements (as opposed to having structs, with functions separated)?
No. There is no practical difference between "memory requirements" of membe... |
68,109,028 | 68,109,354 | why is std::variant permitted to hold the same type more than once? | What can be the use case of std::variant holding the same type more than once?
Refer to https://en.cppreference.com/w/cpp/utility/variant
You can only find the issue when you start to call std::get<T>(v).
| Say we want to represent a token that can be a keyword, an identifier, or a symbol. One possible implementation is thus:
enum TokenType : std::size_t {
Keyword = 0, Identifier = 1, Symbol = 2
};
using Token = std::variant<std::string, std::string, char>;
Now it is possible to use, for example:
std::get<TokenType... |
68,109,171 | 68,631,366 | vkEnumeratePhysicalDevices() not finding all GPUs | My system has the following specs:
GPUs:
AMD Radeon(TM) Graphics
NVIDIA GeForce RTX 2060 with Max-Q Design
CPU:
AMD Ryzen 9 4900HS with Radeon Graphics
When I run vkEnumeratePhysicalDevices() it only returns 1 device, my integrated graphics (AMD Radeon(TM) Graphics). But I figured out that I can force it to use my ... | After much reading of basically every forum on the internet that consists of the function name vkEnumeratePhysicalDevices(), and after the week long bounty on this question still remained unanswered, I've found the answer. It lies within the interop between AMD and Nvidia drivers, at least for my laptop (ROG Zephyrus G... |
68,109,654 | 68,110,155 | Why Application terminates when choosing a row from the QTableView | My application closes when I select a row from the QTableView, which I load, from a PostgreSQL DB.
I have tried making the connection this way but the result is the same.
QObject::connect(ui->tableView->selectionModel(),&QItemSelectionModel::currentChanged,this,
[&](){
in... | Every time you use getConection() you duplicate connection to the database. I don’t know if this is causing the program to fall, but it is at least something bad. Try to fix it.
Also, this is the possible thing to fail:
void Widget::dataMonitoreo(int id)
{
...
qry.next();
ui->lineEdit->setText(qry.value(0).toString());... |
68,109,673 | 68,109,698 | Pass a “char *“ pointer to a function | I set up a class to read the file.
Pass a pointer of type char * to the function, which writes the file to the memory unit that the pointer points to.
Finally, I look forward to reading the contents of the file through the pointer outside the function.
But the result didn't live up to expectations.
Inside the program, ... | The argument char * _out will be a copy of what is passed, so modifying that won't affect what is passed.
You should add & to that (both declaration and definition) like char * &_out to make it a reference so that modification to that will be refrected to what is specified as the argument in caller.
Also make sure what... |
68,110,463 | 68,114,138 | How to purge day-based log files at Windows in C++? | As title, the log file was generated daily named as xxxx-yyyy-mmdd.txt. I hope a log file will be deleted once it's older than one month. That's, the file, xxxx--dd.txt will be removed at day -<mm+1>-dd. Is there any easy way to do such a task or resource to be leverage to save my time of writing tens of line codes?
| As the comment points out, there are several steps:
filter the file with the name pattern
parse the file name into date and compare it with the current date
schedule to delete the target files in a parallel way.
File system access is slow, run the deletion in a parallel way will make it faster than a single thread.
N... |
68,110,706 | 68,110,726 | why std::distance struck in a stl map? | I want to use std::distance to find the index of my element.
here is the code:
#include <iostream>
#include <map>
#include <iterator>
#include <string>
using namespace std;
int main() {
std::map<int, std::string> m = {{1, "huang"}, {2, "wei"}, {3, "pu"}};
auto it = m.find(2);
cout << std::distance(it, m.begin())... | The trouble comes from the fact that std::distance(first, last)...
Returns the number of hops from first to last - cppreference.com
So you need to change to this:
// ...
std::distance(m.begin(), it); // the number of hops from m.begin() to it
// ...
Note, that this way we present distance with a valid iterator ra... |
68,110,864 | 68,126,609 | API/Command to get reason for machine requiring reboot | In the Microsoft Endpoint Configuration Manager, there is a column indicating if a system requires restart and the reason for the restart.
I am able to find if a system requires reboot using get_RebootRequired. But I am not able to find the reason for the restart as displayed in the image.
VARIANT_BOOL
bReboot... | https://learn.microsoft.com/en-us/answers/questions/449982/apicommand-to-get-reason-for-machine-requiring-reb.html
The answer for this is explained in this
|
68,110,872 | 68,111,174 | need help in Char array that auto grow | I want to make auto grow a char array when the user enters any character and stop when the user press enter.
I write this code but the output not correct.
char* dynamicmem(char size) {
char* temp;
temp = new char[size];
return temp;
}
char* regrow(char* ptr, int size, char num) {
char* p = NULL;
in... | You are not null-terminating the arrays you create. Try this instead:
char* dynamicmem(char size) {
char* temp = new char[size + 1];
temp[size] = '\0';
return temp;
}
char* regrow(char* ptr, int size, char c) {
char *p = dynamicmem(size + 1);
for (int i = 0; i < size; i++) {
p[i] = ptr[i];
... |
68,111,251 | 68,111,443 | Is it safe to store string literals pointers? | According to the standard:
5.13.5 String literals [lex.string]
16 Evaluating a string-literal results in a string literal object with static storage duration, initialized from the given characters as specified above. Whether all string literals are distinct (that is, are stored in nonoverlapping objects) and whether... |
Is the above code well defined?
Yes.
Are there any dark corners of standard that I have to be aware of?
Perhaps not a dark corner in the standard but one problem is that you have a pointer and you allow for Base to be instantiated and used like this:
Base foo(nullptr);
foo.print();
From operator<<:
"The behavior i... |
68,111,896 | 68,117,004 | Error : 'to_wstring' is not a member of 'std' | I don't know why this is not compiling.
std::wstring number = std::to_wstring((long long)another_number);
Compiler : gcc 5.1.0
IDE : codeblocks 17.12
| Workaround
std::string temp = std::to_string((long long)number);
std::wstring number_w(temp.begin(), temp.end());
|
68,112,084 | 68,112,085 | Getting numerous errors with Vulkan Memory Allocator, "'(': illegal token on right side of '::'" | I had this issue, come up when first trying to get Vulkan Memory Allocator(VMA) integrated into my program, and it was quite frustrating as nowhere in the VMA documentation could I find such an error. After looking in the vk_mem_alloc.h file I found that the issue was caused because vk_mem_alloc.h uses std::max and std... | The fix is quite easy, all you must do is call the #include "vk_mem_alloc.h" before the #include <windows.h>, but it's something that an amateur like me can get easily hung up on, so I thought I'd document my difficulty here for others attempting to learn this daunting API.
|
68,112,155 | 71,907,459 | Brace Initialize struct with virtual functions | Brace initialization
struct A
{
int a;
int b;
void foo(){}
};
A a{1, 2};
It works fine. But if change foo to a virtual function, It will not compile with error,
Error C2440 'initializing': cannot convert from 'initializer list' to
I find this,
A... | There isn't a way. like in this text you mentioned
An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).
this means that a class/struct or an array that has
n... |
68,112,246 | 68,112,379 | Pointers pointing to Array | I have written following code in C++:
#include<iostream>
using namespace std;
int main()
{
int a[3]={2,3,1};
int (*ptr)[3];
ptr=&a;
for (int i = 0; i < 3; i++)
{
cout<<*ptr[i]<<" "<<ptr[i]<<" "<<&a[i]<<endl;
}
}
And my output is as follows:
2 0x61... | Remember that pointers aren't arrays and arrays aren't pointers. int (*ptr)[3]; is a pointer to a int[3]. When you advance a pointer via +1 then it advances by the size of the pointee. ptr points to a int[3] hence pointer aritmethics advances in steps of sizeof(int[3]).
On the other hand a when decayed to a pointer to ... |
68,112,312 | 68,412,933 | How to check if something is serializable with cereal | I need trait to check if serialization is possible using cereal. I've already used
cereal::traits::is_output_serializable<T, cereal::BinaryOutputArchive>
cereal::traits::detail::count_output_serializers<T, cereal::BinaryOutputArchive>
(plus the symmetric version for input serialization).
Putting such checks in if cons... | I wrote my own based on some static asserts I found in Cereal. I have a base case with a bunch of specialisations I need for my own code. The specialisations are needed as the base case is true for std::shared_ptr<T> even if T isn't itself serialisable.
/// Meta programming constant, can you serialise the type T to... |
68,113,039 | 68,116,553 | Reverse linked list from position left to right | I'm getting run time error and I don't know why. I tried backtracking but couldn't figure out. please help!
Constraints given:
The number of nodes in the list is n.
1 <= n <= 500
-500 <= Node.val <= 500
1 <= left <= right <= n
=================================================================
==31==ERROR: AddressSani... | There are some points to take care of:
Check whether a next reference is not a null pointer before dereferencing it. For example: never do head->next->next=, as you generally don't know whether head->next is not a null pointer. This is the cause of the errors you get.
head->next = prev; will not do the right thing, u... |
68,113,565 | 68,114,316 | Finding smallest number >= x not present in the given sorted array | I am having difficulty writing a modified binary search algorithm that returns the smallest number greater than or equal to X which is not present in the sorted array.
For example, if the array is {1,2,3,5,6} and x = 2 then answer is 4. Please guide me how to write the binary search for this. I have to answer this in O... | If I understand correctly, you are allowed to do any kind of preprocessing and only finding the result for different x must be O(log n). If thats the case finding the result after preprocessing isn't a big deal. O(log n) search algorithms do exist. Good candidates are std::binary_search or std::lower_bound.
A very naiv... |
68,114,060 | 68,114,061 | Does using epsilon in comparison of floating-point break strict-weak-ordering? | Does following class breaks strict-weak-ordering (in comparison to regular std::less (So ignoring edge case values such as Nan))
struct LessWithEpsilon
{
static constexpr double epsilon = some_value;
bool operator() (double lhs, double rhs) const
{
return lhs + epsilon < rhs;
}
};
LessWithEpsil... | From https://en.wikipedia.org/wiki/Weak_ordering#Strict_weak_orderings
Transitivity of incomparability: For all x,y,z in S, if x is incomparable with y (meaning that neither x < y nor y < x is true) and if y is incomparable with z, then x is incomparable with z.
Similarly, from https://en.cppreference.com/w/cpp/nam... |
68,114,309 | 68,114,806 | How can I design a function that can return the length of an array easily? | I want to design a function that can return the value of an array easily. But I meet some problems. In the return statement of function getArrayLen(), the value of sizeof(array) seems to be 4, which is obviously wrong. But if I use sizeof(people) in the main function, it returns 300, which is right. I wonder why? I kon... | Just fix the functions: getArrayLen & test to general function:
template <class T>
int getArrayLen(const T& array) {
return sizeof(T);
}
template <class T>
void test(const T& array)
{
int length = getArrayLen(array);
cout << length << endl;
}
Result:
300
|
68,114,743 | 68,115,064 | Qt: can create widget in ctor, but not in mousePressEvent | I want to dynamically create a child widget on the click of the mouse. When I manually create it in ctor, everything is ok.
Foo::Foo(QWidget *partent) : QWidget(parent)
{
auto *txt{ new QPlainTextEdit(this) };
}
but when I do the same in mousePressEvent, it doesn't appear.
Foo::mousePressEvent(QMouseEvent *event)... | As I understand from your question , I write this example for you :
My example has MainWindow , and in
mainwindow.h
#include <QMainWindow>
#include <QPlainTextEdit>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
// QWid... |
68,114,968 | 68,121,491 | PCL::RegionGrowing on negative Indices | I have a pointcloud from which I extracted a ground plane. Now I want to apply a region growing on all points except for the ground plane. How could I do that efficiently ?
pcl::SACSegmentationFromNormals <pcl::PointXYZRGB, pcl::Normal> ground_seg;
ground_seg.setInputCloud(input_cloud);
ground_seg.setInputNormals(input... | I couldn't just find a way to get the negative indices of what SACSegmentationFromNormals find, but you could try use:
pcl::ExtractIndices, see this tutorial:
https://pcl.readthedocs.io/en/latest/extract_indices.html?highlight
Then use setNegative(true) to get a new point cloud, only containing what you want to do regi... |
68,115,604 | 68,119,010 | Wrong output at last Row, Sodoku puzzle | I write a sodoku solver, everything seems to be fine until the last line of the output is not correct. can someone point me to the right direction why only the last line is not correct? The commented part of the array is supposed to be the correct output.
#include <iostream>
using namespace std;
const int Max = 9;
//S... | if ( grid[b+i][a+i] == n)
Shouldn't one of those i actually be j?
|
68,115,639 | 68,116,259 | LLDB analog for GDB "info sym" | Is there an analog command in LLDB to show current binary file where the symbol is located? In GDB it can be done with info sym command, like shown in this answer.
This is crucial for ODR violation checking.
| https://lldb.llvm.org/use/symbolication.html#id3 has a command just for that:
image lookup --address 0x100123aa3 --verbose
The info about a file is shown even without --verbose option.
|
68,115,760 | 68,115,850 | Overloading_grade_program_accelerated_c++_book | So I am doing exercises in an "Accelerated C++" book. But, when I try to rework the code from the book, Visual Studio keeps saying more than one instance of overloaded function, grade, matches the argument list. But I can not see where is the overloading problem. Can someone please help me with this ?
grade.h
#ifndef G... | The declaration and definition of your second overload for grade() (the one with the vector as the third argument) don't match. The declaration has the vector passed by reference, but your definition has it passed by value. You missed out an & in the latter.
As it stands, when the compiler sees the grade(s.midterm, s.f... |
68,115,853 | 68,116,379 | Why does std::visit in an unsatisfied concept cause a compile error in gcc | This code:
#include <concepts>
#include <string>
#include <variant>
struct any_callable {
public:
template<typename T>
void operator()(T&&) {}
};
template<typename V>
concept is_variant = requires(V v) { std::visit(any_callable{}, v); };
int main() {
constexpr bool wrapped = is_variant<std::string>;
}
d... | That this:
template<typename V>
concept is_variant = requires(V v) { std::visit(any_callable{}, v); };
works at all is a very recent change, a result of P2162. In order for this check to work, you need std::visit to be what's usually referred to as "SFINAE-friendly". That is: it must somehow be constrained on "variant... |
68,115,957 | 68,116,121 | error C2131: expression did not evaluate to a constant when using constexpr | I tried to write three types of meta-programming template to check a class object is able to convert to an int or not.
#include <iostream>
using namespace std;
template<typename T>
struct meta1
{
static char(&resolve(int))[2];
static char resolve(...);
enum { value = sizeof(resolve(T())) - 1 };
};
templat... | constexpr marked functions don't actually need to be called at compile time. They can be, but they can also work at runtime, if their arguments are runtime things. In your case, an std::string would not work for result at compile time (since std::string can't be evaluated at compile-time - no constexpr constructor).
in... |
68,116,012 | 68,121,277 | PCL: use Euclidean Cluster Extraction with labeled points makes a LNK error | I have a point cloud that contains labeled points, thus it is a pcl::PointCloud<pcl::PointXYZL>.
I strictly followed what is said in this tutorial
I need these labels, and I need to extract clusters from the point cloud. But when I call the ECE with the labels I get an LNK error. But it does extract the clusters if I d... | I think you need to use LabeledEuclideanClusterExtraction, see:
https://github.com/PointCloudLibrary/pcl/blob/master/segmentation/include/pcl/segmentation/extract_labeled_clusters.h
This is instantiated for the types with labels and therefore won't give linking errors with point type that has labels.
|
68,116,071 | 68,116,866 | Standard algorithm to operate on adjacent elements | std::adjacent_find looks for the first two consecutive elements that satisfies the given predicate. I am looking for other algorithms that also has a predicate that takes the (previous, current) pair. This is useful for rendering polygons, computing numerical quadrature based on sample data etc.
In addition to std::adj... | There's no special function for this, because you can just call the binary transform std::transform(c.begin(), std::prev(c.end()), std::next(c.begin()), op). This works on the overlapping ranges [c.begin(), c.end()-1] and [c.begin()+1, c.end()].
Similarly, other operations that take two input ranges can work on two ove... |
68,116,118 | 68,116,265 | GetCurrentDirectoryA() remains the same after i move the program | My code has to move itself and some assets to a known directory(C:\windows) and it does so by check its current directory, copying the files and then restarting.
To debug the program i use some msgboxes which return the various variables and i noticed that after the program copies itself and restarts,in the windows dir... | GetCurrent(working)Directory is an O/S state, not the folder of the running .exe.
You can set it to the folder of the exe, if that's what you need.
To get the folder of the .exe, use GetModuleFileName, but it will include the name of the file, not just the folder, so you have to manipulate the returned string (reverse ... |
68,116,228 | 68,119,771 | Cast structs with certain common members | Lets say I have 2 structs:
typedef struct
{
uint8_t useThis;
uint8_t u8Byte2;
uint8_t u8Byte3;
uint8_t u8Byte4;
} tstr1
and
typedef struct
{
uint8_t u8Byte1;
uint8_t u8Byte2;
uint8_t useThis;
} tstr2
I will only need the useThis member... | Using virtual dispatch is usually not what you want when mapping to hardware but it is an alternative.
Example:
// define a common interface
struct overlay_base {
virtual ~overlay_base() = default;
virtual uint8_t& useThis() = 0;
virtual uint8_t& useThat() = 0;
};
template<class T>
class wrapper : public o... |
68,116,417 | 68,207,553 | Using #pragma to remove clang warnings based on clang check | I want to remove/ignore a clang warning for a block of code and found multiple examples of how to use pragamas for this. For example if the warning is unused-variable you can disable it by using:
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-variable"
int a;
#pragma clang diagnostic pop
Ho... | As mentioned in the comments the #pragma clang diagnostic approach can only be used to suppress compiler warnings. The warnings you refer to are coming from clang-static-analyzer which is now a part of clang-tidy.
The only two options to disable a specific clang-tidy check via code are the //NOLINT and //NOLINTNEXTLINE... |
68,116,530 | 68,116,914 | delete vector inside vector issue | template <typename T>
class dvec {
size_t n = 0;
size_t capacity = 0;
T* data = nullptr;
public:
dvec() {
recapacity(21);
}
virtual ~dvec() {
if (data != nullptr) {
delete[] data;
data = nullptr;
}
}
T& operator [] (size_t k) {
if (... | Your implementation of recapacity is faulty.
First problem is that memcpy requires trivially copyable types, which dvec<T> isn't, so dvec<dvec<T>> is ill-formed.
Second problem is that you use ::operator new to allocate, and delete[] to deallocate, so dvec<T> is ill-formed.
Third problem is that you can't have a data m... |
68,116,545 | 68,117,487 | How to make one instance only of class template static member in case of several shared libraries? | I have a template class with a static member, for simplicity:
template<typename T>
struct A
{
static inline int x = 1;
};
But if I include the header with struct A definition in several shared-libraries, each of them will have its own instance of A<T>::x. And I would like to have the instance of A<T>::x (for some... | For GCC you can use:
#define EXPORT __attribute__((visibility("default")))
I've tested it using CMake with the following setup mylib.h:
#define EXPORT __attribute__((visibility("default")))
template<typename T>
struct A
{
EXPORT static int x;
};
mylib.cpp
#include "mylib.h"
template<> int A<int>::x = 1;
template<... |
68,116,772 | 68,118,788 | PeerToPeer data transfer with CUDA graphs | Utilizing CUDA Graphs, I want to transfer some data from one GPU to the other one via NVLink. After defining the graph and nodes, I am populating the memcpy parameters as following to transfer from GPU 0 to 1:
cudaMemcpy3DPeerParms memcpyParams = {0};
memset(&memcpyParams, 0, sizeof(memcpyParams));
memcpyParams.srcDev... | As Abator commented, using cudaMemcpyDefault with cudaMemcpy3Params worked:
cudaMemcpy3DParms memcpyParams = {0};
memset(&memcpyParams, 0, sizeof(memcpyParams));
memcpyParams.srcArray = NULL;
memcpyParams.srcPos = make_cudaPos(0, 0, 0);
memcpyParams.srcPtr =
make_cudaPitchedPtr((void *)d_inputs[0], data_size, data_c... |
68,116,794 | 68,131,955 | How to multithread a button press? | I have an operation that takes several seconds which is blocking my main thread, which freezes my UI. So, I need to put the operation on a separate thread.
Below mimics what I'm trying to do though obviously doesn't work because join() blocks until the thread finishes.
What's the correct approach for allowing the main ... | The simplest way to use threads from a GUI application is to launch the thread and return to the main loop immediately, then post an event when the thread is about to terminate. The handler for this event can join the thread, and you also need to remember to do it on shutdown if the application is closed before the thr... |
68,116,992 | 68,117,010 | Short unsigned int in C++ | So in my exam in the class I was supposed to declare X as a short unsigned. I declared it short unsigned int X. Is this way still OK and correct? Thank you
| Yes, short unsigned int and short unsigned are exactly the same type.
Personally I prefer unsigned short for readability.
See for yourself by testing
std::is_same<short unsigned int, short unsigned>::value
|
68,117,193 | 68,118,029 | Why does default copy constructor not work for this class | Here is the code:
#include <iostream>
class String
{
public:
String() = default;
String(const char* string)
{
printf("created\n");
size = strlen(string);
data = new char[size];
memcpy(data, string, size);
}
~String()
{
delete data;
}
private:
ch... |
Why does default copy constructor not work for this class
Because of this:
~String()
{
delete data; // sic (should be delete[] data)
}
If you delete a pointer, then all pointers to that object become invalid. If you delete an invalid pointer, then the behaviour of the program is undefined.
If ther... |
68,117,468 | 68,117,792 | No matching member function for call to connect | I have one issue with my C++ code in Qt.
I work for a serial connection between my PC and an Arduino.
The window should display the potentiometer value by a QLCNumber widgets. My class contains int m_valeurPot for the potentiometer, and QLCDNumber *m-afficheValeurPotentiometre (I declare this in a constructor).
I use Q... | If I understand you correctly, you are trying to connect slot to an signal of int here (but int is a primitive type - it has no signals or slots):
QObject::connect(m_valeurPot, SIGNAL(valueChanged(int)), m_afficheValeurPotentiometre, SLOT(display(int))).
Instead, you should connect signal from an object, that is derive... |
68,117,654 | 68,123,519 | Print error while creating a sudoku solver in c++ | The print function in the code prints the original board and not the solution, whereas the solver function prints the solution which suggests that the original board has been updated in place. I passed the board by reference to the functions as you can see, so why is not the original board getting updated after calling... | The first call to solver is:
solver(0, 0, board, grid, row, col);
Because board[0][0] is not '.' that first call is only
if(board[x][y] != '.'){
solver(x, y + 1, board, grid, row, col);
return;
}
That is: it calls solver(0,1,board,grid,row,col). Then board[0][1] is '.', and x is not 9 and y is not 9 and that... |
68,118,192 | 68,118,489 | When is the compiler allowed to optimize away a validity check of an enum or enum class type value in C++? | While searching for an answer to the question above, I came across the answer of Luke Kowald to the question Check if a value is defined in an C enum?. It states that one can check if a value is a valid for an enum, by checking if it is equal to one of the possible values in a switch.
typedef enum {
MODE_A,
MOD... |
Would this still be guaranteed to work
Yes.
No rule disallows calling the function like this:
modeValid(static_cast<MODE>(42));
And because that won't match any of the case labels, the behaviour must be that 0 is returned.
could the compiler optimize the check into always true as the enum should never have a value ... |
68,118,371 | 68,118,650 | C++ unordered_map or unordered_set : What to use if I wish to keep an "isVisited" data structure | I want to keep a data structure for storing all the elements that I have seen till now. Considering that keeping an array for this is out of question as elements can be of the order of 10^9, what data structure should I use for achieving this : unordered_map or unordered_set in C++ ?
Maximum elements that will be visit... | As @MikeCAT said in the comments, a map would only make sense if you wanted to store additional information about the element or the visitation. But if you wanted only to store the truth value of whether the element has been visited or not, the map would look something like this:
// if your elements were strings
std::u... |
68,118,498 | 68,118,537 | Header Files Not Found (Wrong Path?) | I am trying to compile the a program in Linux and the program contains the following header files:
#include <iostream>
#include <vector>
#include "Minuit2/FCNBase.h"
#include "FunctionMinimum.h"
#include "MnMigrad.h"
etc. The source file is in
home/christian/code
and the header files are all in
/home/christian/root/i... | If your header is at
/home/christian/root/include/Minuit2/FCNBase.h
Your #include or compile option is wrong.
Currently you are telling the compiler to search for
/Minuit2/Minuit2/FCNBase.h
or
/home/christian/root/include/Minuit2/Minuit2/FCNBase.h
You should specify an option
-I /home/christian/root/include
To have... |
68,118,527 | 68,126,893 | App Crashes with Segmentation Fault when using mysimplebook->GetPageCount() wxWidgets | Hi i am using wxWidgets to create a simple app. But the example app(shown below) crashes when you click on black button on the screen. The app crashes only when you add the statement mySimplebook->GetPageCount() from inside the onClick() event handler. If i remove the use of the above statement from inside onClick() th... | The solution is to use bind instead of connect. Instead of using the Connect() call from inside custombutton.cpp we can just use bind right after that button is created inside the mysimplebook.cpp. So after changing the statement:
Connect(wxEVT_LEFT_UP, wxMouseEventHandler(MySimplebook::onClick));
to
button->Bind(wxEV... |
68,118,568 | 68,130,479 | Should c++ constraints be evaluated eagerly or lazily? | The main purpose of this question is to draw community's attention to libstdc++ ranges not working with clang: https://bugs.llvm.org/show_bug.cgi?id=46746
Avi Kivity suggested this is a gcc bug: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=97120
But then he also suggested this is a clang bug: https://bugs.llvm.org/show... | Following the link from T.C.'s answer I found a related example in the standard, that clang refuses to compile. This is a clear indication of a bug in clang.
[temp.constr.decl]/4:
template <class T> concept C = true;
template <class T> struct A {
template <class U> U f(U) requires C<typename T::type>; // #1
templ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.