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 |
|---|---|---|---|---|
65,586,331 | 65,600,049 | Cannot set Scanner Capability because L_TwainStartCapsNeg returns error -84 | I'm trying to use the Leadtools API version 21 for automatically scanning some documents and here is a sudo code of what I have done (it runs in a secondary thread and the unlock has been done in the main thread):
void CheckRetCode(int rc)
{
if (SUCCESS != rc)
{
L_TCHAR errMsg[1024];
memset(err... | To test your code, I put the main window’s handle in a global variable:
globalhWnd = hWnd;
And modified your function to use that handle like this:
void OnThreadExecute(void *)
{
...
appData.hWnd = globalhWnd; // hWnd is valid handle of my main window
...
}
Then created a thread for it from the main program like this... |
65,586,352 | 65,620,000 | Is it possible to use FetchContent or an equivalent to add a library that has no CMakeLists.txt through CMake? | I have a small project in the works that requires the use of two libraries, namely ASIO (standalone) and nlohmann/json.
Adding the json library to my CMake project is pretty straight-forward:
include(FetchContent)
FetchContent_Declare(json
GIT_REPOSITORY https://github.com/ArthurSonzogni/nlohmann_json_cmake_fetchcon... | FetchContent can deal with non-CMake projects, too. See the full documentation here and in particular the first sentence, which states it can deal with projects "via any method supported by the ExternalProject module."
In the case of asio, which is a header-only library it is quite simple, as you just need to tell Fetc... |
65,586,454 | 65,586,564 | Triggering a breakpoint while deleting memory C++ | In my task I need to input some data about, let's say, depositor and then increase his amount of money by 15% but that`s not the point. The main problem is that it always "triggers a breakpoint" and transfers me to this page
Function where I allocate memory:
void allocateMemory(char*** szData, const int rows, const in... | The bug is here
void assignFirst(char*** szData, const int rows, const int max) {
char* s1 = new char[max];
...
for (int i = 0; i < rows; i++)
{
szData[i][0] = s1;
...
}
}
You assign the same pointer to multiple entries of szData. But here
for (int i = 0; i < rows; i++)
{
fo... |
65,586,859 | 65,588,443 | std::size_t vs. size_type as parameters and function return types | Suppose I have this code. Which method is better?
// Method 1
std::size_t size()
{
// m_myVector is of type std::vector<MyClass*> in all examples
return m_myVector.size();
}
// Method 2
std::vector<MyClass*>::size_type size()
{
// m_myVector is of type std::vector<MyClass*> in all examples
return m_myVector.si... |
but of course there's the off-chance that the size of the vector isn't of type std::size_t
Such off-chance doesn't practically exist in this case because std::vector<MyClass*>::size_type is (indirectly guaranteed and required to be) of type std::size_t. Using std::size_t is fine in this case, and it doesn't leak unne... |
65,586,958 | 65,588,649 | Why is there an ability to override non abstract methods of base class | C++, PHP, Python and other OOP languages allow to override non-abstract methods of base class.
However, this ability allow to violate Liskov substitution principle. Because in such case base class can not be substituted in program with a derived class without changing program behavior.
Am I wrong?
|
But this ability allow to violate Liskov substitution principle. Because in such case base class can not be substituted in program with a derived class without changing program behavior.
This is an incorrect characterization of the Liskov substitution principle. To be correct, change "without changing program behavio... |
65,587,188 | 65,587,496 | access a constexpr member variable of a derived class through a base class reference via CRTP | I'm running into an error when trying to access a constexpr member variable of a derived class through a base class reference via CRTP;
template <typename Der>
struct Base
{
constexpr std::size_t getsize()
{
constexpr const auto &b = static_cast<Der*>(this)->arr;
return b.size();
//retur... | Informally, you should imagine there being a rule that a constexpr variable defined inside a function is required to be initialized by an expression that is always a constant expression regardless of the circumstances under which the function is called. In particular, you can always do something like this:
Base<Derived... |
65,587,257 | 65,588,037 | Split a mathematical expression using regex | I want to split the following mathematical expression -1+33+4.4+sin(3)-2-x^2 into tokens using regex. I use the following site to test my regex expression link, this says that nothing wrong. When I implement the regex into my C++, throwing the following error Invalid special open parenthesis I looked for the solution a... | C++ uses a modified ECMAScript regular expression grammar for its std::regex by default. It does support lookaheads (?=) and (?!), but not lookbehinds. So, the (?<=) is not a valid std::regex syntax.
There is a proposal to add this in C++23, but it is not currently implemented.
|
65,587,561 | 65,587,796 | read/write to large array using large loop - execution time concerns | So recently I ran into a problem that I thought was interesting and I couldn't fully explain. I've highlighted the nature of the problem in the following code:
#include <cstring>
#include <chrono>
#include <iostream>
#define NLOOPS 10
void doWorkFast(int total, int *write, int *read)
{
for (int j = 0; j < NLOOP... |
Looking at the two doWork* functions, for every iteration, we are reading the same addresses adding the same value and writing to the same addresses.
This is not true!
In doWorkFast, you index each integer incrementally, as array[i].
array[0]
array[1]
array[2]
array[3]
In doWorkSlow, you index each integer as array[... |
65,587,698 | 65,593,344 | How do you solve the "deep copy of an abstract class" problem when you are working with an abstract class from a library? | I have a member pointer to an abstract class, and I ran into the common problem where I can't copy what the pointer is pointing to because I don't know what derived class the pointer is pointing to.
When Googling for a solution, I found this question: Copy constructor: deep copying an abstract class
It brings up this e... | For the sake of this answer, let's assume you are working with the SFML's sf::Shape abstract class:
So, you are probably dealing with sf::CircleShape, sf::ConvexShape, and sf::RectangleShape objects through sf::Shape pointers or references. These are concrete classes.
Instead of working through sf::Shape you could def... |
65,587,782 | 65,590,555 | Analog of _mm256_cmp_epi32_mask for AVX2 | I have 8 32-bit integers packed into __m256i registers. Now I need to compare corresponding 32-bit values in two registers. Tried
__mmask8 m = _mm256_cmp_epi32_mask(r1, r2, _MM_CMPINT_EQ);
that flags the equal pairs. That would be great, but I got an "illegal instruction" exception, likely because my processor doesn't... | Yes, cast intrinsics are just a reinterpret of the bits in the YMM registers, it's 100% legal and yes the asm you want the compiler to emit is vpcmpeqd / vmovmaskps.
Or if you can deal with each bit being repeated 4 times, vpmovmskb also works, _mm256_movemask_epi8. e.g. if you just want to test for any matches (i != ... |
65,587,799 | 65,587,899 | How to check if any row of a matrix contains all 'A's? | I've been trying to do this, but the problem is that there's always something wrong or missing with the final result.
I have a lot of if statements and I wanted to see if it is possible to reduce it by using a for loop.
char matrix[3][3] = {
{'A','A','A'},{'B','A','B'},{'C','A','C'}
};
if (matrix[0][0] == 'A' && m... | You can use standard algorithms to express this conveniently:
if (std::any_of(std::begin(matrix), std::end(matrix),
[](auto const & row) {
return std::all_of(std::begin(row), std::end(row),
[](char c) {
... |
65,587,830 | 65,588,219 | What does Note 10 mean in [basic.lval]/11? | [basic.lval]/11:
If a program attempts to access the stored value of an object through a glvalue whose type is not similar to one of the following types the behavior is undefined:48
(11.1)
the dynamic type of the object,
(11.2)
a type that is the signed or unsigned type corresponding to the dynamic type of the object,... | This note is language lawyering at its best!
While defining its equivalent rule (§6.5/7 in C99), C bundles in aggregates and union types when describing the valid aliasing possibilities.
C++ doesn't do that. With constructors, conversion operators and inheritance thrown into the mix, classes can be lot more complex tha... |
65,587,834 | 65,588,253 | Editing QTreeWidgetItem while retaining file extension | I have a QListWidget that contains filenames. Right-clicking on an item brings up a menu which contains a Rename... item. Clicking on Rename... lets the user edit the filename. So far so good.
But in the Qt Creator Projects window, right-clicking on (say) foo.cpp and selecting Rename... presents the user with a field i... | A possible solution is to create a QObject that intercepts the editor's show event and then change the selection:
#include <QtWidgets>
class Helper: public QObject{
public:
Helper(QLineEdit *le): QObject(le), m_le(le){
m_le->installEventFilter(this);
}
bool eventFilter(QObject *watched, QEvent *eve... |
65,588,745 | 65,588,917 | Could NOT find Glog (missing: GLOG_INCLUDE_DIR GLOG_LIBRARY) | I am trying to install openpose in Ubuntu 20.04 using CMAKE and I get the following error:
Could NOT find Glog (missing: GLOG_INCLUDE_DIR GLOG_LIBRARY)
I am following the instructions here (unfortunately, the screenshots are not available but I just followed the textual commands):
https://github.com/CMU-Perceptual-Co... | $ sudo apt install libgoogle-glog-dev
Also,
$ sudo apt-get install libgflags-dev
$ sudo apt install libgoogle-glog-dev
$ sudo apt-get install protobuf-compiler libprotobuf-dev
since initially I didn't have any of them installed.
|
65,589,844 | 65,590,505 | how to center a middle widget and expand its cell | In Qt designer, how do i center a middle widget in a vertical/horizontal/grid layout and expand its cell at the same time, what i want to get is something like this:
what i get:
| One possible solution is to place the middle QPushButton in a QWidget through a layout, and then place that QWidget in the second column of the QHBoxLayout:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<property name="geometry">
<rect>
<x>... |
65,590,127 | 65,613,051 | How to use a particular version of llvm out of different versions? | I have installed llvm 6,7,10,11 on my linux(Ubuntu 20.04) machine along with same clang versions. Different projects require different versions of llvm. How to compile c++ programs using a particular version of clang and llvm?
For example: currently llvm 10 and clang 10 are defaults and I use :
clang++ program_names.cp... | It depends on your disctribution. On FreeBSD OS, for instance, all LLVM executables are appended with version number, so you can run clang80, clang++90, etc.
For each package you used, check the list of files it installs.
|
65,590,173 | 65,590,316 | Searching using unordered map vs array | I have a block allocation function that takes in an array and then searches through it to find values 0 which indicates the free space, and then allocates blocks to the available free space. I am trying to use unordered map to improve the speed of searching for 0s. In my function, all the elements in the array are inse... | First, note that both functions as you've written them always return zero, which is not what you want.
Now, to answer the main question: No, this approach doesn't help. In both cases you're just iterating over the values in the array until you hit on one that's a zero. This is an O(n) operation in the worst case, an... |
65,590,346 | 65,590,451 | C++: undefined reference to Constructor | I just started working with C++ and am working on an exercise that deals with polymorphic pointers. I'm having trouble trying to solve an error message I believe I'm getting from my Rectangle.cpp as I call the class from my main.cpp.
The error message:
undefined reference to 'Rectangle::Rectangle(double, double)'
Mai... | The error is generated by the linker because it can not see where the definition of the constructor is located.
If you are using an IDE, you should add .cpp file to the project so that it can be compiled and the definition would be found by the linker. It not, then you have to compile it yourself -assuming you are usin... |
65,590,945 | 65,591,049 | Data insertion and deletion speed of queue in STL of c++ | I have question about insertion and deletion speed of queue in c++ STL.
When i tried to slove algorithm question using Dequeue i made, i face running time out problem.
So i think my Dequeue is so slow, and i want to know what is the difference between my Dequeue and queue in c++ STL.
Here is my queue code.
Please give ... | You Dequeue is implemented via a linked list, where nodes are allocated/deallocated in each push/pop operation. std::queue is implemented via a std::deque, which is much more efficient (it allocates only once a while).
Linked lists are good if you need to insert in the middle, but this is not your case. std::deque is b... |
65,591,515 | 65,591,807 | How to have a function template get the parameter types of its lambda argument? | Assume we have a class template like this:
template <typename baseT, typename ...argTs>
class CCallable : public baseT
{
public:
CCallable(std::function<bool(argTs...)> lambda)
: m_lambda(lambda) {
}
bool Invoke(argTs ...args) override {
return m_lambda(args...);
}
private:
std::function... | With C++17 CTAD, you could harness deduction guides for std::function:
template<class T>
struct Identity { };
template<typename baseT, typename ...argTs>
class CCallable : public baseT {
public:
CCallable(std::function<bool(argTs...)> lambda, Identity<baseT> = {})
: m_lambda(lambda) {
}
bool Invok... |
65,591,726 | 65,591,934 | Dll Injector not detecting Dll | I recently coded an injector where as long as the dll is in the same directory as the exe injector it will inject but even when the dLL is in the same path it still returns with the error file not found.
Very new to c++ so not exactly sure how to fix it, only this I know that the problem must lie in the dll_name
The c+... | Try to use C++ STL function or Windows native API:
#include <string>
#include <filesystem>
#include <Shlwapi.h>
#pragma comment(lib, "Shlwapi.lib")
bool IsExists(const std::string &FilePathName)
{
return std::filesystem::exists(FilePathName);
}
bool IsExists(const std::string &FilePathName)
{
return PathFi... |
65,591,780 | 65,591,936 | Implementing insert on BST by recursion for c++ | I was going through insertion of a node on BST recursively and I found an implementation below (check rinsert() function in the code below). The recursive function returns a pointer of the newly inserted node.
If the node is inserted lets say to the leaf node of height 4 for a tree. Shouldn't all the nodes along the pa... | Yes the function is bugged because although it promises to return a Node* it doesn't in all cases.
The correct code (untested) is
Node* rinsert(Node* cur, int key) {
if (!cur) return new Node(key);
if (key < cur->key)
cur->left = rinsert(cur->left, key);
else
cur->r... |
65,592,163 | 65,592,277 | (C++) Palindrome Numbers using Function | #include <iostream>
using namespace std;
bool pals(int n) {
int remainder;
int reverse=0;
while(n>0){
remainder=n%10;
reverse=reverse*10+remainder;
n=n/10;
}
return reverse;
}
int main() {
int nums;
cout<<"Input Desired Number: ";
cin >>nums;
if(pals(nums)) {
cout <<nums<<" palindrome";
}
els... | Your problem is because you are returning a number from the function and casting it to a Boolean so every number will truncated to a True value.
You should check inside the function whether it’s a palindrome or not and return a 1/0 result or even better a Boolean value.
A thorough explanation on the behavior described ... |
65,592,506 | 65,592,781 | Storing thread in vector member variable triggers breakpoint | I have a class called Executor with a vector<thread*> as a member variable. the submit(const std::function<void()>& f) member function is supposed to start the passed lambda as a thread and add it to the vector. The destructor joins all threads stored in the vector.
The first lambda prints the result, but after that my... | In threads.push_back(&t); the pointer &t is only valid until the end of the scope which t is declared in. This causes 3 problems:
At the end of the scope inside submit the thread is destructed without calling join causing std::terminate to be called
In the destructor of Executor ->join is called on a dangling pointer
... |
65,592,604 | 65,593,402 | Is 'Class' against the rule of 'separation of concern'? | For a 'class' in modern programming languages, e.g. Java/C#/C++/Python..., it contains both data and logic in one place. However, according to 'separation of concern', it seems that we shouldn't mix data with logic. I know both are right, but how to explain the two seemingly conflicting ideas?
|
... according to 'separation of concern', it seems that we shouldn't mix data with logic ...
That's just false. We don't consider "data" and "logic" to be concerns in the first place. Nothing in the linked article suggests that anyone does or ever has considered this.
Consider the first example given in your own link... |
65,592,750 | 65,592,947 | c++ making struct with unknown size array (with memory location intact) for passing buffer data | So, I need the memory to be lay out in a specific way:
struct aPacketWithMoreData{
double x;
int16 h;
int16 noNeedToBePassedToTheBuffer;
double y;
}
struct aPacket{
double x;
double y;
int16 h;
}
struct bufferData{
int32 something;
uint64 anotherthing;
aPacket arrayOfData[]; //wi... | That's not for compatibility with C, that's an extension outside of standard. There is no way to represent undetermined size of array, not at least defined in standard. In C or C++ type is know on compile time, which means it memory layout is known: size of type and offsets\memory locations of every element.
Some plat... |
65,592,773 | 65,593,011 | Do we only have to have a deallocation when we have an allocation in C++? | I have this example from an official site:
char* variable1;
variable1=getenv ("PATH");
if (variable1!=NULL)
{
printf("variable1=%s",variable1);
}
//Shouldn't this be here to avoid memory leak?
//delete variable1;
Or we can say that the pointer variable get its value in an equation and there is no need for deallocatio... | To quote the man page of getenv() :
As typically implemented, getenv() returns a pointer to a string
within the environment list. The caller must take care not to modify
this string, since that would change the environment of the process.
The implementation of getenv() is not required to be reentrant.
The string poin... |
65,592,908 | 65,592,999 | What is better way to storage configuration variables (for example states of program) in program? |
to make them as global variables or to storage them in some class?
I'm not sure that implementing of singleton in this case is proper solution.
| Make a Singleton that handles all the configuration
|
65,592,913 | 65,593,027 | Are the answers of this C++ quiz correct? | In the university I had a quiz today. The quiz is over but I can't understand some of its questions are their correct answers.
Note: I am not asking this to solve my quiz. Quiz is over I am just confused in some questions.
Question 1:
Consider the following variable declarations:
int catHeight = 6;
int dogHeight = 7;
... | 3 errors in question 2:
missing ( ) around the if condition
in the second part of the if condition there must be double ==
{ } are missing
To be a valid code it must be set like this:
if (numNeighbors >= 3 || numNeighbors == 4)
{
++numNeighbors;
cout << "You are dead" << endl;
}
else
--numNeighbors;
|
65,593,177 | 69,947,763 | How to build libtorch on mac arm? | i downloaded libtorch and make these files on macbook pro ARM:
example-app/
build/
libtorch/
CMakeLists.txt
example-app.cpp
then i used these commands for build torch:
cmake -DCMAKE_PREFIX_PATH=/path-to-example-app/example-app/libtorch
make
and i get this error:
building for macOS-x86_64 but attem... | I was able to build libtorch library from source on my Mac M1 and run the C++ example-app project that you are looking at
(https://medium.com/@albertsundjaja/installing-pytorch-c-api-d52c722f47ec)
I did it with the following steps:
% git clone -b master --recurse-submodule https://github.com/pytorch/pytorch.git
% mkdir... |
65,593,313 | 65,593,846 | I am trying to write this program but it keeps on displaying an a error everything is mentioned below can anyone check | Question:
Write a C++ program that stores and siplays following employee data of
a company in structures:
Employee ID (int)
Employee Name (string)
Email (string)
Designation (char)
Salary (float)
Projects (array of strings)
Your code must contain following:
Pointer to structure
Array of Structure
Structure variable... |
The first three errors indicate you're trying to brace-initialize the float member without C++11 compilation. Either enable C++11 compilation or change:
float salary{};
To
float salary;
The final two errors indicate you're incorrectly attempting to index something with [i]. Change:
cout<<(*E).Eid[i]<<(*E).Ename[i... |
65,593,362 | 65,593,524 | Is iteration through a shared object thread safe? | I have a parallel C++ algorithm that looks somewhat like this:
void recursiveFunction(int p, std::unordered_set<int> localSet) {
vector<someStruct> toCall;
if (p > SOMEINT) {
return;
}
#pragma omp parallel for schedule(dynamic, 1) shared(localSet, someGlobalVector, someOtherGlobalVector)
for... |
Is iteration through a shared unordered_set thread safe?
No, an unordered_set is not thread-safe by definition. However, this does not necessarily imply one's code has a race condition when using such structures; For instance, if one only reads the data structure, even concurrently, then one is on the safe side. This... |
65,593,449 | 65,593,811 | using loop for only if statement and then print else statement |
Check whether if the entered character is consonant or vowel?
I almost got the result but I just need else statement to be out of loop.
Is it possible to use else out of loop? Here I tried adding {} but didn't help me. How do I do so
?
I have solved this program in many ways but I want to clear my concepts of if and ... | Loop for( statement expression; action ) body loop is just a while loop
{
statement;
while ( expression )
{
body
label_for_continue:
action;
}
}
So you can see that everything declared inside will have its life ending outside of for. You can use break to stop loop prematurely and continue to ... |
65,594,155 | 65,594,315 | MISRA C++ 2008 Rule 5-2-3 Advisory: Casts from a base class to a derived class should not be performed on polymorphic types | In the following example:
class A
{
public:
A();
virtual ~A();
int getID() const;
private:
int m_ID;
};
Class B : public A
{
public:
B();
virtual ~B();
int getBid() const;
private:
int m_Bid;
};
bool test(const A* const p_A)
{
if(5U == static_cast<const B* const>(p_A)->getBid())
... | The MISRA checker is right. You should not do a static_cast.
You need to understand Polymorphism better. When calling your function
bool test(const A* const p_A)
also a pointer to the derived class can be used. And, by using the vtable, the correct function will be used. So, do not downcast.
But, you must update your ... |
65,594,231 | 65,594,453 | C++ deleteting object in constructor? | i want to make class which has one string atributte. But if string has length more then 50 characters i dont want create object. What should i do?
{
if (paSlovo.length() <= DLZKA_SLOVA)
aSlovo = paSlovo;
else
delete this;
} ```
| Instead of doing this trough the constructor you can do this with a function that will either provide you with the object if the criteria is met or you get a nullptr.
Make sure to correctly delete the object when done or make use of smart ptrs
//create object
bar* TryCreateMyObj(string const& paSlovo) const
{
//onl... |
65,594,612 | 65,595,121 | Why is [[maybe_unused]] in captured list not possible? | I wonder why I can't use the [[maybe_unused]] attribute in the capture list of a lambda. Is there a reason that variables of a captured lists can't be marked as [[maybe_unused]]? This would avoid to capture all variables, means [&], in cases like this:
auto lambda = [&x, [[maybe_unused]] &y](){
if constexpr( x >= ... | I asked the same on the mailing list. The answer from Arthur O'Dwyer was:
Ah, yes, that would be a place where [[maybe_unused]] might apply.
However, for now, you can easily write
(void)a;
to suppress the warning: https://godbolt.org/z/7ZHSYz That's less
cluttering to the code (thus easier to read and maintain), and ... |
65,594,651 | 65,596,985 | myComboBox->Dismiss(); not working under wxEVT_TEXT and wxEVT_COMBOBOX_DROPDOWN | My objective:
During wxEVT_COMBOBOX_DROPDOWN load up a choiceDialog and set the choice as combo box value and finally close the combobox using dismiss().
What I tried:
void Class_Scheduler_FNFrame::myComboBoxDropdown(wxCommandEvent& event)
{
SingleChoiceDialog1->ShowModal();
int i = SingleChoiceDialog1->G... | You're trying to do something rather weird: have you ever seen a modal dialog show while the combobox dropdown is opened? I haven't and, generally speaking, there should be only a single modal element shown at each moment.
So why do you have this objective? What is the point of showing the dialog whenever a combobox is... |
65,594,842 | 65,594,927 | How to pass the name of a template class to a template argument? | I know we can do the following,
template <class CONTAINER>
void f(CONTAINER *c){}
int main(){
std::vector<int> v;
f(&v);
std::set<int> s;
f(&s);
}
Then, I want an alternative (convenient for my project), like the following,
template <class CONTAINER>
void f(CONTAINER<int> *c){} // the CONTAINER is the... | You are looking for a template template parameter:
#include <set>
#include <vector>
template<template<typename> typename CONTAINER>
void f(CONTAINER<int> *){}
int main(){
std::vector<int> v;
f(&v);
std::set<int> s;
f(&s);
}
"Matching template template parameters to compatible arguments" is a C++17 fe... |
65,594,892 | 65,598,435 | Construct a tuple by passing a the same variable number of constructor arguments to each element | I am trying to construct a tuple by passing the same constructor arguments to each element.
For illustrative purposes, I have 2 classes which can take any number of constructor arguments:
struct Foo
{
template<typename... Args>
Foo(Args... args)
{
std::cout << "Foo " << (... << args) << '\n';
}
};... | It would be:
template <typename... Args>
Storage(Args... args) : storage(Ts(args...)...) {}
|
65,594,993 | 65,595,543 | Not all invocations running | I am attempting to implement a simple compute operation of multiplying all values in a buffer by a push constant.
This shader:
#version 450
layout(local_size_x = 1024, local_size_y = 1, local_size_z = 1) in;
layout(binding = 0) buffer Buffer { float x[]; };
layout(push_constant) uniform PushConsts { float a; };
void ... | Problem originated with setting the size of the VkBuffer and VkDescriptorBufferInfo to the number of values rather than the number of bytes.
Making these changes fixes it:
bufferCreateInfo.size = size; -> bufferCreateInfo.size = sizeof(float)*size;
bindings[i].range = size; -> bindings[i].range = VK_WHOLE_SIZE;
|
65,595,216 | 65,596,438 | Sorting vector using custom function that will accept vector of any type and std::less/std::greater as comparator | I'm trying to sort a vector(in this particular case containing std::make_unique<std::string> but it should be able to work with different types as well). Here is the code that I was provided:
template <typename T>
void print_vector_of_pointers(const std::vector<T>& vec) {
for (const auto& ptr : vec) {
std::cout << *p... | You claim to use C++17 (since you used its tag). Most probably you have not enabled it in your project. Just add a flag that enables it, e.g. -std=c++17 for Clang or GCC, or /std:c++17 for MSVS.
If you are using CMake, you can just use set(CMAKE_CXX_STANDARD 17).
|
65,595,414 | 65,595,740 | _free_dbg(block, _UNKNOWN_BLOCK); exception when I want to delete[] variable initiated with new | I was searching for the solution but found nothing what could help me with my problem.
EDIT I cannot use stl library in this project (so std::string, std:vector, std::cout etc. are out)
I am initiating my 2 dimension array of chars like that:
char** string = new char*[MAX_MENU]; // MAX_MENU is 3 in my case
for (int i =... | As per the comments, the following statement...
string[0] = "Start";
actually assigns the pointer associated with the string literal "Start" to string[0] and the original chunk of 20 chars allocated for and pointed to by string[0] is lost/leaked.
If you really can't use std::vector, std::string etc. then you can still... |
65,595,671 | 65,599,239 | How to explicitly call the specified overload function? | #include <cstdio>
#include <string>
constexpr char str[] = "/home/qspace/etc/client/mmkvcfgsvr_test_byset_cli.conf";
void test(bool a)
{
printf("b=%d",a);
}
void test(const std::string& s){
printf("s=%s",s.c_str());
}
int main()
{
test(str);
return 0;
}
Like this code, the C++ compiler will convert char*... |
How to explicitly call the specified overload function?
Convert the argument at call site: test(std::string(str));
Take expected address of overload function: static_cast<void(*)(const std::string&)>(print)(str);
Is there any way to prevent the compiler from performing type conversions that I don't want?
You migh... |
65,595,876 | 65,596,293 | How to do a parallel bilinear interpolation | I tried this but I don't know if it is right, and to calculate the time of execution sometimes it gives me 0
in the code.
I firstly created a structure to stock all the coordinates of the point to be interpolated I have a table of points to be interpolated, so I used pragma parallel for to execute the for section to i... | #pragma omp parallel for
for(i=0;i<N ; i++)
{
R1 = BilinearInterpolation(Table[i].x1, Table[i].Q11,Table[i].x2, Table[i].Q21,Table[i].x);
R2 = BilinearInterpolation(Table[i].x1, Table[i].Q12, Table[i].x2, Table[i].Q22,Table[i].x);
P = BilinearInterpolation(Table[i].y1, R1, Table[i].y2, R2, Table... |
65,596,382 | 65,599,410 | Is there a way to pass a void function with any type and amount of arguments as an argument in a method and store it in a data member? (C++) | I ran into a problem while passing a function as a parameter in a method. My problem is that I want to be able to pass any void function with any type and amount of arguments and then store it in a data member. What I currently do is an overload for a void function without arguments and an overload for a void function ... | From what I understand, you want to call a function void(), where caller might register other function type with bind parameters. You might do it with std::function:
class ExampleClass {
public:
void saveFunction(std::function<void()> f) {
this->f = f;
}
void call() { f(); }
private:
std::functi... |
65,596,590 | 65,597,775 | How do I specify the amount of random numbers in my code in C++ | I tried reading other questions to find the answer to my question but I got tired of seeing the answer being in a different coding language. I want to change the amount of numbers in my random error code. I am genuinely new to this so please no rude comments.
#include <iostream>
#include <ctime>
#include <cstdlib>
usi... | How i would do it:
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(time(NULL));
int j[3];
for (int i = 0; i < 3; ++i)
j[i] = rand(); //sets every index of the array to rand()
cout << "Error code: ";
for (int i = 0; i < 3; ++i)
cout << j[i] << '\n'; //outputs all values fr... |
65,596,879 | 65,600,221 | How to get rid of left-over characters when using \r in C++? | Assume I have the following code which is an infinit counter :
#include <iostream>
int main() {
short int counter = 0;
while(true)
cout << "This is a counter: " << counter++ << " and I'll keep counting!\r";
return 0;
}
When you run the code with the carriage return, it will overwrite the exist... | Continuing from the comments above, if you are outputting to a VT compatible terminal (most are), you can use ANSI Escape sequences to control clearing to end-of-line (and various other cursor movements and visibility).
A short example working with lines terminated with a carriage-return, you can use \033[K to clear to... |
65,596,996 | 65,598,007 | How to create .ui file with hand code in an existing class | I have a Qt Creator C++ project which doesn't have .ui file to design the interface. The .ui was hand coded and now I need to assign this .ui file to the project.
Is there a way to assign this .ui file to the project without having conflicts?
| To handcode .ui files in Qt, you need to right click in the file, on the project explorer, click on Open With and next on Plain Text Editor. Now you can copy and paste the .ui file that you already have!
It's importantly you specific the same name of all classes, objects, among other things, between the files and besid... |
65,597,292 | 65,597,495 | How to solve 'No known conversion' in this code? | First of all I have to say that i have no experience with C
My problem is I needed to write a make file to seperate 2 functions wrote like this before ;
#include <math.h>
#include <iostream>
using namespace std;
int main()
{
float A,B,x,y;
int z;
x=-0.62;
y=0.82;
z=25;
A = pow(y, cbrt(double ... | I think this is what your looking for. There were multiple errors. Ill comment them out for you.
#include <math.h>
#include <iostream>
using namespace std;
// You dont need to pass variable pointers to a function like this.
float A(float x, float y, int z) {
// When declaring a variable, make sure that you specify... |
65,597,467 | 65,598,041 | Installing ccls through Homebrew outputs caveats messages related to libffi and llvm | I'm trying to set my neovim C++ development environment, and want to use ccls as my coc language server.
When I installed ccls using Homebrew, it installs libffi and llvm as dependencies.
It seems like ccls is installed successfully, but it seems like I need to configure PATH variable,LDFLAGS and CPPFLAGS.
But I don't ... | libffi is only a library. And llvm is a compiler infrastructure.
And libc++ is the C++ standard library of the LLVM Project. You can use the LLVM library or the GNU (libstdc++) one. It depends on your software project (or your personal preferences) what library you use.
Since macOS does already deliver a llvm installat... |
65,597,681 | 65,599,284 | Specification rule of "definition of a static data member is in the scope of its class" with a templated base class | The C++ specification (e.g. C++17 [class.static] §2) says:
The definition of a static data member is in the scope of its class.
With an example (taken from C++14 spec):
int g();
struct X {
static int g();
};
struct Y : X {
static int i;
};
int Y::i = g(); // equivalent to Y::g();
The exact wordin... | GCC and Clang are both correct.
Particularly, from [temp.dep]/3 [emphasis mine]:
In the definition of a class or class template, the scope of a
dependent base class is not examined during unqualified name lookup
either at the point of definition of the class template or member or
during an instantiation of the class t... |
65,597,949 | 65,598,354 | copying a value into the address of a pointer in an assembly function called from c++ (nasm) | I'm trying to learn x86-64 assembly, and I found the book "Modern X86 Assembly Language Programming: Covers x86 64-bit, AVX, AVX2, and AVX-512", but it uses MASM and Visual C++ and I use Linux. So I'm trying to convert some of the programs in it to NASM-syntax, but I encountered a problem with storing the result of a c... | First, the calling conventions are different between Windows and Linux.
https://en.wikipedia.org/wiki/X86_calling_conventions
It appears you incompletely changed this..
Second, while you can mostly use 32-bit registers, you must treat addresses as their full 64-bit values.
Finally, you are also modifying esi then usi... |
65,598,017 | 65,609,521 | Is this ray tracing function that runs on the GPU, GPU safe? | I have tried to write a simple ray tracer in the fragment shader.
I have this function that is supposed to create a diffuse sphere as follows :
Here is the function :
vec3 GetRayColor(Ray ray)
{
Ray new_ray = ray;
vec3 FinalColor = vec3(1.0f);
bool IntersectionFound = false;
int hit_times = 0;
for (int i = 0; i < RA... | All spheres are white most likely because ClosestSphere.Hit in GetRayColor function is always true.
I think the problem is in your IntersectSceneSpheres function.
In CPU code you return HitAnything which is defaulted to false. At the same time in the fragment shader you return struct ClosestRecord that remains uninitia... |
65,598,138 | 65,598,209 | Is it really UB to access an object whose user-defined destructor has started, but not finished? | The question arose due to a discussion on Reddit, where a user told me, citing the standard's rules on object lifetime:
I'm pretty certain that it is technically UB to access an object, while it is being destructed.
I rely on this, for example, with classes that manage a background thread; I have their destructors si... | No, it's well-defined.
If it were UB to access the object at all while its destructor is executing, that destructor would itself not be able to do anything with its own object.
During execution of your destructor:
bases have not been destructed yet
the "current" object itself has not been destructed yet (and neither... |
65,598,225 | 65,598,874 | Can I get tuple of pairs of "var's name" and "var's value" with the help of the macros? | So my problem... I have a logger class, that prints a logger messages, that creates with the help of macros. It prints different info such as function name, line number, etc.
My message have a tuple of pairs, that contain a name of the var and its value.
using namespace std;
std::string ThisThreadGetIdString() {
s... | With hard coded limit, you might do
#define TAKE_11(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
#define COUNT(...) TAKE_11(__VA_ARGS__ __VA_OPT__(,) 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#define IDENTITY(N) N
#define APPLY(macro, ...) IDENTITY(macro(__VA_ARGS__))
#define F_0(F)
#define F_1(F, a) F(a)
#define ... |
65,598,674 | 65,609,492 | cmake - Header files of shared library not found | I am making a custom library that I want to be installable for users. However, when I try to use my own library in a cmake executable, I get a build error saying that the library headers were not found.
The library CMakeLists.txt:
cmake_minimum_required(VERSION 3.16)
project(mylibrary)
include(GNUInstallDirs)
set(CMA... | When a shared library target is namespaced in the config file you need to reference it with the full name in the downstream packages when using find_package, i.e. you need to use
target_link_libraries(myexecutable PUBLIC mylibraryConfig::mylibrary)
Alternatively, remove the namespace from the install by replacing
inst... |
65,599,317 | 65,599,436 | Rename Win32 Functions for Security on C++ | Is there a way to rename a win32 function like GetVolumeInformationW() using #define ?
For example:
#define abc(LPCWSTR a, LPWSTR b, ...) GetVolumeInformationW(Some argumments..)
Why do that? I want to hide the function name on debbuger programms like IDA, is there some way to did that?
Language: C++
| There is no point in using #define for this, as this will have no effect on the contents of the binary executable. Using preprocessor macros will only affect what you as a programmer will see, but it won't affect what the compiler or linker will see. See this link for information on how the C++ preprocessor works and i... |
65,599,567 | 65,615,734 | Adding custom TensorFlow OP | I am trying to use the Tensorflow implementation of compact bilinear pooling by ronghanghu since it's used in the implementation of the "Learning Rich Features for Image Manipulation Detection" paper. ronghanghu uses TensorFlow version 1.12.0 with CUDA 8.0 and g++ 5.4.0 to build sequential_batch_fft.so. However, they d... | Turns out the problem was with the tensorflow_framework.so. Was able to fix this by creating a symbolic link ln -s libtensorflow_framework.so.2 libtensorflow_framework.so in ../site-packages/tensorflow. Also, I think my project path was not suitable as it contains spaces. Not so sure about this one but when I used Tens... |
65,600,107 | 65,601,168 | How to access templatized static variable of a class in multiple places in c++ | I am working on a functional simulator project in c++. My aim is to store last 50 debug log statements in a rolling buffer and display them whenever there is a error in the simulator. This will help be debug faster. Else I will have to note down the cycle when there is a error and re-run the simulator with logs enable... |
One way to solve this problem is whenever I push to last_50_logs, I can store log statements as std::string instead of template T and U inside Logging structure. But this is really really slow as string operations are expensive.
Well, you can't store the log events as some unknown type T, because ... then you don't k... |
65,600,141 | 65,600,384 | intializing a std::array of objects that don't have default constructor from another constexpr std::array | Is it possible to initialize an array of objects whose members are initialized from another constexpr array of trivial objects. For example I have the following
struct X
{
X(int y): _x(y){}
int _x;
};
struct Z
{
static constexpr std::array<int, 4> arr = {1,6,0,4};
// How does one implement make_array below... | With std::index_sequence:
template <typename T, typename U, std::size_t N, std::size_t ... Is>
constexpr std::array<T, N> make_array(const std::array<U, N>& a, std::index_sequence<Is...>)
{
return {{T(a[Is])...}};
}
template <typename T, typename U, std::size_t N>
constexpr std::array<T, N> make_array(const std::a... |
65,600,150 | 65,602,582 | Access to QCheckBox from QWidgetAction | Please consider the bellow codes:
QMenu* menu_ = new QMenu(this);
QWidgetAction *checkableAction = new QWidgetAction(menu_);
QCheckBox* checkBox1 = new QCheckBox("Sample1", menu_);
QCheckBox* checkBox2 = new QCheckBox("Sample2", menu_);
checkableAction->setDefaultWidget(checkBox1);
checkableAction->setDefaultWidget(c... | This answer is based on code snippets provided by question. However i am not sure if the intention was to use "checkable" feature of base class QAction.
If you want to use the checkbox you set as QWidgetAction default widget to trigger your slot then you have to use connect(checkBox2, &QCheckBox::toggled, this, &MenuPu... |
65,600,207 | 65,600,780 | How to get content of array from C++ dll in C# | I want to use functions from DLL in C++ with C#.
I store string data in a vector.
My C++ file contains:
#include "stdafx.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
extern "C" __declspec(dllexport) std::vector<std::string> GetProduct();
std::vector<std::string> GetProduct()
{
std::vector<std::stri... | My favourite way for passing an array of strings C++-->C# is by using a delegate.
C#:
// If possible use UnmanagedType.LPUTF8Str
// or under Windows rewrite everything to use
// wchar_t, std::wstring and UnmanagedType.LPWStr
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void AddAnsi([MarshalAs(Un... |
65,601,167 | 65,601,429 | Problems assigning string into another string inside IF statement | I'm trying to assign one string to another inside a if statement, basically how it works is, when the program starts the String is NULL, when I assign a new value to it on the console, the main string receives the value, and I created a temporary string to receive the value too. If I insert the temporary_string = main_... | The problem is that last_wifi_name is a local variable. You are setting it with
last_wifi_name = wifi_name;
but at the end of the loop iteration it's destroyed and at the beginning of the next loop iteration a new empty variable is created.
|
65,601,385 | 65,604,764 | Segmentation fault when using prim_minimum_spanning_tree in boost | I want to run prim on a graph from a file, but with certain inputs prim_minimum_spanning_tree gives me a segmentation fault.
The segfault doesn't occur when i run it with valgrind, but valgrind indicates that there are errors ("Invalid read of size 8"), but it only shows them on certain graphs.
Im very new to using bo... | Like the commenter said, fix your valgrind errors. Most likely you're doing stuff out-of-bounds in the readin function.
You are operating on far too many raw pointers. This is not C, so why pretend that it is?
Here's my take on it, without using manual allocation, and without potentially getting wrong bounds. Note that... |
65,601,687 | 65,790,968 | Can an Excel xll function indicate that the return value should be displayed as a date and not a number? | Excel "dates" are doubles under the hood, and the XLOPER structure does not seem to have any concept of date, only xltypeNum (unlike Variants in VBA).
I have a simple XLL with a function that takes no arguments returns today's date as an LPXLOPER (type "P"). I have other functions that usually return dates but could al... | To my knowledge, following the TODAY() approach of setting the date format via a callback is the only way to signal to Excel that the value you're returning from an XLL function is a date. However, it does have a few drawbacks:
Performance (for very large numbers of calls, although I haven't checked this)
Requires sp... |
65,601,998 | 65,607,696 | Copying all files in CD Rom and saving them in a folder at a different location using win32 c++ | Is there a way in win32 C++ that I can copy all the files inside a CD Rom and save them in a folder located somewhere else (where the folder location will be specified)? Is there a win32 C++ function to do this? The docs show the function SHFileOperationA() but can this copy all the files in a CD Rom?
|
CopyFile() wants you to specify the name of the file being copied
though. What if you don't know the name of the files
You can use FindFirstFile and FindNextFile combine with CopyFile.
Assume your CD ROM drive is E:, you can try the following example to see if it helps.
WIN32_FIND_DATA fData;
HANDLE searchHdl = FindF... |
65,602,052 | 65,602,308 | template b-tree c++ implementation | I am trying to code a template class for b-tree in c++ so it can work with any type char or integer, and i faced this error when i am trying to insert to the tree, in the line 49 , 76 , and 12 so if anyone can help code is below check it out, the code is only for insertion and print only.
template<typename t,int order>... | Add a forward declaration of the BTree before the Node class and swap the friend class BTree; with friend class BTree<t, order>;. Also swap the NULL with nullptrs. It'll solve the issue.
|
65,602,182 | 65,614,770 | Understanding comment from the errata about Item 41 of EMC++ | In Item 41, Scott Meyers writes the following two classes:
class Widget {
public:
void addName(const std::string& newName) // take lvalue;
{ names.push_back(newName); } // copy it
void addName(std::string&& newName) // take rvalue;
{ names.push_back(std::move(newName)); } // move it; ..... | In the second scenario, when a const std::string lvalue is passed to the template
template<typename T>
void addName(T&& newName)
{ names.push_back(std::forward<T>(newName)); }
the instantiation results in the following (where I've removed the std::forward call as it is, in practice, a no-op)
void addName(const... |
65,602,672 | 65,603,235 | Is There performance difference between this three function return ways (c++) | A Function1()
{
return {1};
}
A Function2()
{
return A{1};
}
A Function3()
{
A a{1};
return a;
}
i tried three ways. they all call just one assignment constructor.
i question There can be performance difference depending on which complier to use?
| There are subtle differences:
Function1 requires non explicit A's constructor.
construct A "in place" (even before C++17). so copy/move A's constructor might even be marked as = delete, and program is well formed.
pre-C++17, Function2 will use move/copy constructor which might be elided (return value optimization: RV... |
65,603,144 | 65,603,276 | How to get coverage for tests with CMake and Catch2 | I'm trying to print coverage with lcov on a C++ project that is using Catch2 for tests. I'm able to run my tests and get results. However, I'm unable to get any coverage. This is the error that is shown.
Capturing coverage data from .
Found gcov version: 9.3.0
Using intermediate gcov format
Scanning . for .gcda files .... | I believe you forgot to add appropriate flags
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fprofile-arcs -ftest-coverage")
set(CMAKE_CXX_FLAGS " ${CMAKE_CXX_FLAGS} -fprofile-arcs -ftest-coverage")
|
65,603,474 | 65,604,913 | Dispatching from a runtime parameter to different overloads | Suppose I have a set of types :
constexpr std::tuple<int,double,string> my_types;
a set of values to identify them:
constexpr std::array<const char*,3> my_ids = {"int","double","string"}; // const char* instead of string to be constexpr-compatible
and an overload set
template<class T> bool my_fun(my_type complex_obje... | Leverage variant.
template<class T>struct tag_t{using type=T};
template<class T>constexpr tag_t<T> tag={};
template<class...Ts>
using tag_enum = std::variant<tag_t<Ts>...>;
now tag_enum is a type stores a type at runtime as a value. Its runtime representation is an integer (!), but C++ knows that integer represents a... |
65,603,560 | 65,604,076 | Issues with CreateProcess and incorrect parameters | This may be 2 questions, but they're broadly both revolving around CreateProcess and it not quite functioning right.
I've been working on an application that gathers together files, processes them, and then zips them as a final step, renaming the zipped file with the hash of the directory that I had zipped. To accompli... | When using both the lpApplicationName and lpCommandLine parameters of CreateProcess(), the lpCommandLine should include the EXE path as the 1st token in the command line. This is even stated in the CreateProcess() documentation:
If both lpApplicationName and lpCommandLine are non-NULL, the null-terminated string point... |
65,603,808 | 65,610,505 | How to compile custom cpp files on Google Colab | I'm trying to replicate the result of this github repo using Google Colab since I don't want to install all the requirements on my local machine and to take advantage of the GPU on Google Colab
However, one of the things I need to do (as indicated in the repo's README) is to first compile a cpp makefile. The instructi... | You can install the required version of Cuda in google colab. For eg.
For Cuda 9.2 you can try
!apt-get --purge remove cuda nvidia* libnvidia-*
!dpkg -l | grep cuda- | awk '{print $2}' | xargs -n1 dpkg --purge
!apt-get remove cuda-*
!apt autoremove
!apt-get update
!wget https://developer.nvidia.com/compute/cuda/9.2/Pr... |
65,604,343 | 67,416,055 | N_API How to send int value parameters to Napi::CallbackInfo | This My first node.js and n_api. I have been using PHP/APACHI. But I need the c++ library for my web And I decided to using n_api.
The problem is that the value sent by ajax is always 0 in c++.
I don't know what is problem.
ex) I using a vscode.
const testAddon = require('./build/Release/firstaddon.node');
var http = ... | You need to cast it to the number with the help of the Napi::Number::Int32Value call. (You can also use Napi::Number::Int64Value for bigger numbers)
Try this.
int file_id = info[0].ToNumber().Int32Value();
Also unrelated to the question, but worth mentioning that when you are doing ThrowAsJavaScriptException() the act... |
65,604,657 | 65,604,859 | Displaying all the files in a folder using win32 C++ | I have a folder with about 9 files in it and I am trying to get my code to display Messageboxes for each file in the folder with the name of the file, when a button is pressed. For some reason, it only displays a messagebox for the very last file in the folder and then gives me the error: "Error finding files." which i... | Your while statement has an erroneous ; on it:
while (FindNextFile(hFind, &FindFileData) != 0); // <-- here
Thus, you loop without processing FindFileData until FindNextFile() fails, AND THEN you process the last FindFileData data that was reported. And that display ends up wiping out the error code that the failed F... |
65,604,886 | 65,605,485 | How do I avoid warnings about c++Future-extensions when using feature test macros and Clang? | I have some code targetting C++14 which could make use of C++17's [[nodiscard]] attribute. It seemed natural to me to use feature-test macros to accomplish this:
#ifdef __has_cpp_attribute
# if __has_cpp_attribute(nodiscard)
# define NODISCARD [[nodiscard]]
# else
# define NODISCARD
# endif
#else
# ... | You can temporarily disable diagnostics with the pragma clang diagnostic:
#ifdef __has_cpp_attribute
# if __has_cpp_attribute(nodiscard)
# ifdef __clang__
# define NODISCARD \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") ... |
65,604,982 | 65,605,110 | Visual Studio 2017: build tools for v142 cannot be found error, even though Platform Toolset is set to v141 | I'm building an openFrameworks project (using the project generator which generates VS2017 solutions) but am receiving the "build tools for v142 cannot be found" error. Answers across Stack Overflow say to go into Project > Properties > Configuration Properties > General and set Platform Toolset to v141 in order to do... | As @dxiv mentioned in the comments: "The error references one project, but the Property Pages refer to another." Every project in the solution (there should be two for OF projects, yourProjectName and openframeworksLib) needs to be individually downgraded. Instead of going to Project > Properties via the top toolbar, r... |
65,605,146 | 65,605,246 | Issue with nested #define for defining a function with variadic arguments | How can I define a nested #define into a macro with variadic arguments
#ifndef MY_PRINTF
#define MY_PRINTF(f_, ...) { \
#ifdef USE_WRITE_DEBUG_INFO \
char buff[200]; \
sprintf(buff, (f_), __VA_ARGS__); \
WriteDebugInfo(buff); \
#else \
printf((f_), __VA_ARGS__); \
#endif \
}
#endif
Visual studio comp... | You can't use preprocessor directives while defining a #define. This means that your #ifdef USE_WRITE_DEBUG_INFO won't work.
For this case, use a function rather than a macro:
#include <cstdarg>
void my_printf(const char* format, ...) {
#ifdef USE_WRITE_DEBUG_INFO
char buff[200];
va_list args;
va_start(a... |
65,605,791 | 65,605,866 | How To Print Specific Value Using For Loops | I have a function to print the array like this:
void letter_function(char cards[]) {
for (int i = 0; i < 6; i++) {
cout << "\n" << "|" << letters[i] << "|";
}
cout << endl;
}
char letters[6] = {'A','B','C','D','E','F'};
I'm trying to print specific values from this function. For example, The function wil... | So, I believe what you are wanting to do is to be able to print anywhere from a single letter, to the entire array. So you could do something like this:
void letter_function(char cards[], int start, int end) {
for (int i = start; i < end; i++) {
cout << "\n" << "|" << letters[i] << "|";
}
cout << endl;
}
... |
65,606,463 | 65,606,655 | How to add slashes to the end of a TCHAR buffer[] using Win32 C++ | I am trying to add two slashes "\" to the end of a TCHAR buffer[] using wsprintf() in my Win32 C++ app.
The variable "buffer" holds a file path: C:\Users\nayub\Desktop\Folder1\Hello. I want to add two slashes to the end of this file path so did the following code:
wsprintf(filename_buff, buffer, L"\\");
MessageBox(hWnd... | You are using wsprintf() incorrectly. It needs to look more like this instead:
wsprintf(filename_buff, L“%s\\”, buffer);
Or, you can use PathAddBackslash() instead:
wcscpy(filename_buff, buffer);
PathAddBackslash(filename_buff);
However, you tagged your question as c++, so just use std::wstring instead:
MessageBox(hW... |
65,606,539 | 65,606,554 | Move capture of parameter in lambda | MCVE : http://coliru.stacked-crooked.com/a/ef442eca9b74c8f1
I want to move parameter in lambda function by following a tutorial in Move capture in lambda.
#include <string>
#include <iostream>
#include <functional>
class B{};
void f(B&& b){}
int main(){
B b;
auto func_lambda=[b{std::move(b)}](){
//f(std... | Move semantics only work on mutable objects. You will need to make your lambda mutable:
auto func_lambda = [b = std::move(b)]() mutable {
f(std::move(b));
};
However you can only call such lambda once. If you want to call it multiple time, you'll have to generate values or use std::exchange(b, B{})
|
65,606,779 | 65,607,346 | static and reinterpret casting - defined behavior? | First off, I come from a "managed" land, so be gently. I'm trying to create a messaging system and before I put too much effort into it, I want to make sure my understanding of casting is correct.
Say I have a pod type called header and place that header into another pod type message, can I safely static_cast the messa... |
can I safely static_cast the message to header
No. Such static cast is ill formed. Similar reinterpret cast would be well defined though... As long as your stated preconditions are true. If you assume them wrongly, then behaviour of the program is undefined.
As pointed out in a comment, your code example static casts... |
65,607,148 | 65,607,165 | Proper way of returning a functor in C++ | Consider we have an add function declared like this:
int add(const int a, const int b);
If we were to return this add function from foo...
std::function<int(const int, const int)> foo()
{
return add;
}
std::function<int(const int, const int)> foo()
{
return &add;
}
Which one of the above is the correct way o... | Both code snippets are identical (as far as the language is concerned).
std::function can be constructed from any callable object (whether it be a lambda, pointer-to-function, etc). In both examples, you are constructing the std::function with a function pointer.
In the first example, add denotes the name of a functio... |
65,607,160 | 65,608,262 | Can I get name / reference to specialization value inside template specialization? | My code:
enum class list{one, two};
template <list T> class Base;
template <> class Base <list::one>{
A a{list::one};
B b{list::one};
C c{list::one};
};
template <> class Base <list::two>{
B b{list::two};
C c{list::two};
D d{list::two};
};
But I would like to avoid duplicating code, and use ref... | In the following example I'm using SFINAE to make T available in the definition of Base. Specifically I have done the following:
added one dummy type parameter to the primary template,
made the two specialization partial by not specifying the parameter T (and specifying the second dummy type parameter),
specified the ... |
65,607,482 | 65,607,624 | Applying stl algorithms to multidimensional vectors (vector<vector<T> >) | How, generally, can an stl algorithm be applied to a multidimensional vector (i.e. a vector<vector<T> >)?
For example, if I wanted to fill some vector, myVector, with values according to some function, myFunc(), I might use something like:
std::generate(myVector.begin() myVector.end(), myFunc())
Suppose now that myVec... | The generator passed to std::generate() needs to return a type that is assignable to the element type of the container. So, in your example, the element type of myVector is another vector, so myFunc() would need to return a whole vector, eg:
template<typename T>
vector<T> myFunc()
{
vector<T> v;
// populate v ... |
65,607,534 | 65,652,931 | getting error in installing Prerequisites wxWidgets "E: Unable to correct problems, you have held broken packages." | i'm following https://wiki.wxwidgets.org/Compiling_and_getting_started install guide for wxWidgets.
when i'm installing Prerequisites getting error:
command:
sudo apt install libgtk2.0-dev
error:
The following packages have unmet dependencies:
libgtk2.0-dev : Depends: libglib2.0-dev (>= 2.27.3) but it is not going t... | run
sudo apt-cache search libwxgt*
it output some packages name.
than try to install one by one all the packages.
output
libwxgtk-media3.0-gtk3-0v5 - wxWidgets Cross-platform C++ GUI toolkit (GTK 3 media library runtime)
libwxgtk-media3.0-gtk3-dev - wxWidgets Cross-platform C++ GUI toolkit (GTK 3 media library develop... |
65,607,622 | 65,608,068 | Desktop Elements with Winapi | I'm trying to get the elements in the desktop (icon shortcuts) using winapi, but for some reason I'm getting nothing. Am I doing it wrong? (I'm very new to this)
BOOL CALLBACK EnumChildWindows(HWND hwnd,LPARAM lParam) {
char str[256];
GetWindowTextA(hwnd, str, 200);
OutputDebugStringA(str);
return true;... | You used the EnumChildWindows function by mistake:
BOOL CALLBACK EnumChildProc(HWND hwnd, LPARAM lParam) {
char str[256]{};
GetWindowTextA(hwnd, str, 200);
OutputDebugStringA(str);
return true;
}
int main(int argc, const char* argv[])
{
HWND hDesktop = GetDesktopWindow();
EnumChildWindows(hDeskt... |
65,607,661 | 65,607,726 | unpack multiple parameter packs to initialize a 2d array | I'm trying to unpack multiple parameter packs so that arr[i][j] = X(i,j). However I get the following error with the current approach below. Are there approaches to achieve the above using C++14/17?
// Non copyable and default constructable
struct X
{
X(const X&) = delete;
X(int x, int y) : _x(x), _y(y)
{}
... | I would do this
template<std::size_t... XIs, std::size_t... YIs>
std::array<std::array<X, sizeof...(XIs)>, sizeof...(YIs)> make_2d_array(std::index_sequence<XIs...>, std::index_sequence<YIs...>)
{
return {
[](auto YI) -> std::array<X, sizeof...(XIs)> {
return {getX(XIs, YI)...};
}(YIs)..... |
65,607,682 | 65,609,505 | How to implement wrapper for lambda with capture? | std::function can wrap lambdas with capture list but how std::function implemented? We don't know what is the type of it, it can be assigned to void* but then it is not possible to call lambda
| Disclaimer: this is incomplete, possibly incorrect and doesn't follow std::function api and conventions (e.g. it is not copyable). This is just an example to show one way of how the type erasure of a std::function like type can be implemented, striped down to the bare minimum to understand the type erasure technique.
I... |
65,607,802 | 65,607,864 | I can't find where the error occurred when using vector | When I run this code, I can get the Debug Assertion Failed error.
"Expression: vector erase iterator outside range"
I can't find where the error occurred.
for (int i = 0; i < comb.size(); i++) {
if (couple.size() != 0 && couple.size() == mate * 2) {
vector<int>::iterator iter = couple.begin();
... |
Let's assume couple.size() == 6.
Let's assume rad == 5.
Then rad will be transformed to 6.
Then you will call erase() on an iterator past the end of the array. Which is illegal.
I'm going to guess that you should have done:
rad = (rad % 2 == 0 ? rad : rad - 1);
But it's hard to say since you never explained what you... |
65,607,884 | 65,639,359 | Call cuda library on windows | I am trying to use cuda to parallelize a Go project.
I've read Golang calling CUDA library many times.
I'm trying to do the same thing on Windows and having trouble. (I'm assuming this OP was using Linux because of the .so files)
I have successfully compiled/run the following test program involving no cuda code to make... | Thanks to the direction from @talonmies comments I found that at least in simple cases I could call the dlls created by cl.exe and nvcc.exe from cgo by defining a header file that looks like this:
#ifdef __cplusplus
extern "C" { // only need to export C interface if
// used by C++ source code
#endif
_... |
65,607,925 | 65,610,986 | How to check if a string contains unescaped regex control characters? | I am writing code that uses the C++ standard library's Basic RegEx pattern matching. The pattern matching as used is currently a bottleneck, and I want to optimize the common case of a simple string (with no special RegEx characters). How can I check if a given string contains unescaped RegEx special characters? I am a... | There are 12/13 special characters for regex:
\ [ { ( ) ^ $ . * ? | + / ]
so any pattern including one of the above would not be usable (directly) as search string (even if escaped).
If your pattern only contains regular characters and escaped special char, you might transform that pattern in regular string (foo\(\) ->... |
65,608,517 | 65,608,862 | connect QPushButton to a function inside a the same class | I want to connect QPushButton to a function inside the same class. the class is just a QGridLayout that making ui via code. I don't know what to do. actually I don't know what to put in for reciever argument in QObject::connect.
I don't want to use bunch of h and cpp files so that the code be as simple and readable as ... | If you are using Qt <= 15.2, i think you should start at reading Qt resources with signals and slots. link
Simple answer is that:
your class should inherit from Qobject,and you should put QObject makro in top and private section of this class.
class example : public QObject
{
Q_OBJECT
public: ...
public slots: .... |
65,608,994 | 65,609,789 | getting an runtime error of reference binding to null pointer of 'std::vector<std::pair<int, int>' | I am solving Cheapest Flights Within K Stops on Leetcode and I am getting a Runtime error of
runtime error: reference binding to null pointer of type
'std::vector<std::pair<int, int>, std::allocator<std::pair<int,
int>>>' (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer
Why this error is occurring?
My code:
class S... | initialize the vector of pair like this: Here 10000 is the size of the vector.
vector<pair<int, int>> graph (10000,make_pair(0, 0));
|
65,609,107 | 65,609,178 | strip - file format not recognized with Qt creator on Release but not Debug | Using qmake on Qt creator
I want to add some parameters and data files to the build directory, so I added this to my pro file
wordlists.path = $$OUT_PWD/WordLists
wordlists.files += $$PWD/WordLists/*
INSTALLS += \
wordlists
and added a make install step at the end of the build steps.
On debug, this works perfectl... | Solution found rather quickly...
Due to an error of mine, the files in WordLists where executable. I removed the +x flag and the warning is gone.
|
65,609,123 | 65,609,516 | mutable object referred by std::any | Is only the way to modify, not replace, an object stored as std::any is to declare changeable data mutable? E.g. to avoid creation and copy of class S instances:
#include <iostream>
#include <vector>
#include <any>
#include <string>
struct S {
mutable std::string str;
S(S&& arg) : str(std::move(arg.s... | You can any_cast with non-const reference:
std::any_cast<S&>(container[0]).str = "Test 2";
Demo
or
std::any a = 40;
std::any_cast<int&>(a) += 2;
std::cout << std::any_cast<int>(a) <<std::endl;
Demo
|
65,609,813 | 65,610,229 | The direct base class of private inheritance prevents the derived class from defining the object of the indirect base class | like this code
class Try
{
public:
Try() = default;
int i = 0;
};
class B1 : private Try
{
public:
B1() = default;
using Try::Try();
using Try::i;
};
class C1 : public B1
{
public:
Try a; //tell me:'Try' is a private member of 'Try'
void print()
{std::cout << i << std::endl;}
... |
the Try a is a local object , not a part of C1, why error?
By writing Try a; in the context of class C1, the name lookup will generally always scan from local to global scope. The first match thus will be B1::Try, which is, due to the private inheritance, inaccessible for C1.
The fix is easy, just hint the compiler t... |
65,609,954 | 65,610,225 | Error reading characters of string error in malloc()ed object. Why? | I'm working with C++ in Visual Studio.
I have a problem when using this structure:
struct TreeNode
{
string info;
TreeNode* left, * right;
};
typedef struct TreeNode* ExpTree;
like in this function:
ExpTree createNode(string info)
{
TreeNode* temp;
temp = (TreeNode*)malloc(sizeof(TreeNode));
if (te... | I think that the proposed duplicate technically does answer the question.
But here is some specifics on how that explains the problem here.
C "strings", which is not actually a thing there, are only memory containing char, usually terminated with '\0'. What ever is done with them, is done by functions which expect noth... |
65,610,268 | 65,610,314 | Why it gives an error of Segmentation Fault but for only some runs of code(or we can say for some input cases)? | Why does it show segmentation Fault for only 1 test case out of 15 test cases.
The next and the head pointers are accessible, i didn't even alter any of the in-editable pointers.
Error - Program terminated with signal SIGSEGV, Segmentation fault.
#0 0x0000000000401364 in compare_lists (head2=,
head1=0x192f5b0) at Solu... | Before assigning a node to its next neighbor, you should check it for null.
if (temp->next != nullptr)
temp = temp->next;
if (temp2->next != nullptr)
temp2 = temp2->next;
Little update: That doesn't seem to be the problem, I thought you were checking temp and temp2 themselves for null in your loop condition.... |
65,610,554 | 65,611,737 | Return any / unknown type c++ | I am attempting to implement msgpack (a json alternative) in c++, and am creating an Iterator class to loop over my byte array, which is separated based on certain headers. So how would the iterator construct and return any type, Eg. vector<int>, map<int, string> etc. Is std::any or std::variant the only way to do this... | There are different approaches for what you want to do and each one has its own requirements and drawbacks.
Solution 1: The user knows at compiletime what the serialized data looks like
Just write a template function that takes a type and try do deserialize into it. Check the runtime type info of the binary blob and th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.