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 |
|---|---|---|---|---|
71,490,658 | 71,490,708 | Detect Nvidia's NVC++ (not NVCC) compiler and compiler version | I am using Nvidia's HPC compiler nvc++.
Is there a way to detect that the program is being compile with this specific compiler and the version?
I couldn't find anything in the manual https://docs.nvidia.com/hpc-sdk/index.html.
Another Nvidia-related compiler nvcc has these macros
__NVCC__
Defined when compiling C/C... | __NVCOMPILER __NVCOMPILER_MAJOR__ __NVCOMPILER_MINOR__
Found them accidentally in a random third-party library https://github.com/fmtlib/fmt/blob/master/include/fmt/core.h
#ifdef __NVCOMPILER
# define FMT_NVCOMPILER_VERSION \
(__NVCOMPILER_MAJOR__ * 100 + __NVCOMPILER_MINOR__)
#else
# define FMT_NVCOMPILER_VERSIO... |
71,490,765 | 71,491,587 | Searching a set<> via Custom Criterion | Language Version
I am using a version of the GNU C++ compiler that supports C++17 (though I am not yet familiar with all that was added in C++11/14/17).
The Problem
In the code below, I have found that I can insert into a set<> using a custom sorting criterion, but I cannot test for the presence of an element using set... | Your comparator takes two arguments of type const node_sp_t&, so you must have a node_sp_t object to compare against.
In C++14, you can use a transparent comparator, allowing you to compare against a different type (in this case, char)
class node_comp_t
{
public:
inline bool operator()(char lhs, const node_sp_... |
71,490,784 | 71,491,818 | Vector iterator does not start at index 0 | I'm new to vectors and iterators. How come the iterator in the second for-loop does NOT start at index 0?
int main() {
PS1Solution instance;
std::vector<int> result;
std::vector<int> testCase = {2, 7, 11, 15};
int target = 9;
result = instance.twoSum(testCase, target);
for (auto it = result.b... | An Iterator is not an index.
An iterator acts like a pointer to a specific element. Dereferencing an iterator gives you the value it refers to, not the index of the value. So, using result[*it] is wrong, it should be just *it by itself, eg:
for (auto it = result.begin(); it != result.end(); it++)
printf("%d\n", *it... |
71,490,817 | 71,495,503 | How do you link libraries in Qt? | I have a project that I've written in VS2017 that has a lot of static libraries and I've got to the point where I want to start refining the gui. To make sure I can use Qt I made a test subdir program using the tips in https://www.toptal.com/qt/vital-guide-qmake, the https://wiki.qt.io/SUBDIRS_-_handling_dependencies e... | You have this:
INCLUDEPATH *= $${BASEDIR}/include
But you don't have directory named include anywhere, it seems. So probably remove the /include part from above.
|
71,490,966 | 71,515,128 | How to call org.jdom.Element APIs using JNI C++ | New to JNI. I am trying to call Element::getChild and Element::getChildText APIs (java org.jdom.Element) to get the version number of a system that is stored in "settings.xml" This xml file is archived in JAR file. Assuming the root element is available, here is what I am doing:
jstring fileNameStr = env->NewStringUTF(... | Using JNI, here is what worked for me that uses org.jdom.Element. My settings.xml file looks like this:
<?xml version="1.0">
<settings>
<about>
<version>1.0</version>
</about>
</settings>
JNI C++:
jstring fileNameStr = env->NewStringUTF("settings.xml");
// assuming xmlRootElement_mid is known
jobject element... |
71,491,330 | 71,491,504 | if constexpr std::is_same under VS 2022 | I have converted one of my projects from VS 2019 to VS 2022 and the following conditional compilation template doesn't compile properly anymore:
struct T_USER;
struct T_SERVICE;
template<typename T>
class system_state
{
public:
system_state();
};
template<typename T>
system_state<T>::system_state()
{
if con... | The code is ill-formed because for constexpr if:
Note: the discarded statement can't be ill-formed for every possible
specialization:
template <typename T>
void f() {
if constexpr (std::is_arithmetic_v<T>)
// ...
else
static_assert(false, "Must be arithmetic"); // ill-formed: invalid for ever... |
71,491,613 | 71,493,966 | How to sort non-numeric strings by converting them to integers? Is there a way to convert strings to unique integers while being ordered? | I am trying to convert strings to integers and sort them based on the integer value. These values should be unique to the string, no other string should be able to produce the same value. And if a string1 is bigger than string2, its integer value should be greater. Ex: since "orange" > "apple", "orange" should have a g... | You are almost there ... just a minor tweaks are needed:
you are multiplying by 26
however you have letters (a..z) and empty space so you should multiply by 27 instead !!!
Add zeropading
in order to make starting letter the most significant digit you should zeropad/align the strings to common length... if you are usi... |
71,491,721 | 71,495,414 | void pointer subtraction can't compile in C++, but can compile in C, what's the reason for the difference? | int arr[10];
void* p1 = arr;
void* p2 = arr + 10;
size_t sz = p2 - p1;
The same code, on the C++ side, it doesn't compile. But on the C side, it compiles. And the result sz is 40.
I know why it doesn't compile on C++ side, because void does't have size so it can't do subtraction. But what's for the C side?
I ... | GCC defines an extension to the C language in which addition and subtraction with void * acts like arithmetic on char *.
This makes the compiler non-conforming to the C standard in its default mode because the standard requires the compiler to issue a diagnostic for addition and subtraction on a pointer to an incomplet... |
71,491,967 | 71,492,042 | default copy move constructor efficiency different | if default copy constructor provider by compiler only make a shallow copy(copy the pointer of a member in heap to target object's corresponding member field), what is the difference between default copy constructor and default move constructor?
I think default move constructor should not be more more efficient than def... |
what is the difference between default copy constructor and default move constructor?
A default copy constructor does memberwise copy of the data members while a default move constructor does memberwise move of the data members. That is, the default move constructor steal resources instead of copying them from the pa... |
71,492,830 | 71,494,895 | QProcess Backup Database on QT C++ | I want to backup my database with qprocess in QT program, the code is as follows, but 0kb occurs when backing up and when I look at the error Qprocess: Destroyed while process("mysqldump.exe") is still runnuing.
QProcess dump(this);
QStringlist args;
QString path="C:/Users/mahmut/Desktop/dbbackupfile/deneme.sql";
args<... | Your program terminates before process finished, you need to either use static bool QProcess::startDetached(program, arguments, workingDirectory) or add dump.waitForFinished(); to the end.
Also, you dont need to add ">" to arguments. You already redirected output with dump.setStandardOutputFile(path), ">" does not work... |
71,493,678 | 71,493,736 | Why doesn't the optimizer optimize this code? | Compiling and running this code with the maximum optimization settings seems to give the same result.
#include <stdio.h>
class A
{
public:
A() { }
const int* begin() const { return a; };
const int* end() const { printf("end\n"); return a + 3; };
bool isTrue() const { return true; }
int a[4];
};
co... |
Why does "B called" get printed twice?
For starters, because you reference b[0] twice in main. And because the printf statement inside the operator function dictates that there's a side effect for accessing b[0]. So the compiler can't assume that your printf is just for debugging - it has to invoke it once for each ... |
71,493,740 | 71,494,150 | Can reference be compared with pointer? | I'm studying Copy assignment in C++. If you see the line 5 at the code below, there is "this == &rhs". Is this expression legal? this is a pointer to an obejct and rhs is an reference to object. So it is different.
Or Can reference be compared with pointer?
Thank you.
class Mystring{
//class
};
Mystring& Mystring::o... |
there is "this == &rhs". Is this expression legal?
Yes.
this is a pointer to an obejct and rhs is an reference to object. So it is different.
Yes.
Or Can reference be compared with pointer?
Potentially yes (if the reference is to a class type with an operator overload for comparing with a pointer), but that's not... |
71,494,090 | 71,502,909 | Define and use MOCK_METHOD with gtest and gmock | I am new to googletest/googlemock and I have following questions:
First question: I have this DatabaseClient class which has a method query_items which I want to mock. I`m unable to find the syntax to do it. Here is my attempt:
class DatabaseClient {
public:
// constructors
DatabaseClient();
DatabaseClien... | Somehow you need to tell your TestService class to use the mock object instead of the real object.
Currently you instantiate the DatabaseClient in create():
TestService::create() {
DatabaseClient* databaseClient = new DatabaseClient();
//...
}
You should tell it to use MockDatabaseClient instead. This can ... |
71,494,610 | 71,495,139 | Statically link all dependences so that the end user will never be asked to install vc_redist.exe | I'm building a Windows executable with VS 2019. When I run it on my machine, it works, but I'm not 100% sure it will work for end users who don't have vc_redist.x64.exe version 2019. (Especially users on Win7 - it's in a niche where users still use this version).
How to statically link everything so that the end user w... | Add a specific ClCompile property for the compilation configuration:
<Project DefaultTargets="Build" ToolsVersion="16.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
...
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<RuntimeLibrary>... |
71,494,809 | 71,495,018 | Why is header including sufficient for definitions? | as far as i understood; headerfiles declare things. Now including header files like #include iostream includes the header file iostream.h. This is telling the compiler for example „there is something called: cout“.
QUESTION: How does the compiler get to the definition of cout (or all the other functions)? In my underst... | Actually: It doesn't. It needs to know how the objects look like, what interfaces they offer (so for std::cout that's a some std::ostream stream object, apparently a subclass of) and that such objects do exist somewhere. That's it. What the compiler then does is adding placeholders for that object – right as it does fo... |
71,494,909 | 71,495,306 | Is it possible to check if two classes have the same members | struct Test1 : public Base {
enum { type = 1 };
int a;
char ch;
virtual void func1();
};
struct Test2 : public Base {
enum { type = 2 };
int a;
char ch;
virtual void func1();
};
I'm developing a project with C++14. For some compatibility reason, I have to declare two classes as above, ... | I don't like the premise of this question because it is essentially asks for a way to keep code duplication. However in practice shit happens and if someone wants two classes with the same content the better idea would be not to declare two classes and then check them for compatibility, but to declare them just once. T... |
71,495,222 | 71,501,051 | Boost Graph Library: Adding vertices with same identification | How can I represent file path using BGL?
Consider path like: root/a/a/a/a/a
Corresponding graph would be 'root'->'a'->'a'->...
Is it possible to add multiple vertices sharing the same name?
Could not find clear answer.
| Sure. As long as the name is not the identifier (identity implies unique).
The whole idea of filesystem paths is that the paths are unique. So, what you would probably want is to have the unique name be the path to the node, and when displaying, choose what part of the path you want to display.
For an elegant demonstra... |
71,495,508 | 71,497,810 | Error using llvm-11 in combination with standard library headers from gcc-11 compiling with -std=c++2a | I am trying to use clang together with gcc standard library headers as follows:
/opt/rh/llvm-toolset-11.0/root/usr/bin/clang -MD -MF bazel-out/k8-fastbuild/bin/external/com_google_googletest/_objs/gtest/gtest-typed-test.d '-frandom-seed=bazel-out/k8-fastbuild/bin/external/com_google_googletest/_objs/gtest/gtest-typed-t... | The gtest-port.h file includes a file with #include <regex.h> (see here for the code). It expects the file to be the POSIX regex.h which is normally installed directly under the prefix /usr/include. As you can see in the error message, the compiler instead tries to include the /usr/include/c++/11/bits/regex.h which is ... |
71,495,536 | 71,495,823 | How can I minimize both boilerplate and coupling in object construction? | I have a C++20 program where the configuration is passed externally via JSON. According to the “Clean Architecture” I would like to transfer the information into a self-defined structure as soon as possible. The usage of JSON is only to be apparent in the “outer ring” and not spread through my whole program. So I want ... | I'd go with the constructor approach, however:
// header, possibly config.h
// only pre-declare!
class json;
struct Config
{
Config(json const& json_config); // only declare!
bool flag;
int number;
};
// now have a separate source file config.cpp:
#include "config.h"
#include <json.h>
Config::Config(j... |
71,495,789 | 71,495,907 | C++ - Making an HTML Validator using Stack | I received an assignment from my lecturer to make an HTML Validator using stacks. I fail to wrap my head around the algorithm to do so, since stacks can only do LIFO, what am I supposed to do to check if a tag has been closed or not? Is it possible? Any answer would be helpful, since I've been stuck for a few days now.... | In a stack you push new elements on top and remove them by popping the most recent element. So you could push opening tags on the stack until there is a closing tag, then check the element on the top of the stack if it matches the closing tag. If another opening tag appears after the closing tag, simply push it on the ... |
71,495,807 | 71,503,419 | error: nested name specifier for declaration does not refer into a class, class template or class template partial specialization | Why error about "error: nested name specifier 'h::TYPE::' for declaration does not refer into a class, class template or class template partial specialization" show is only mark place?
#include <iostream>
namespace h
{
enum TYPE
{
A, B, C
};
struct test
{
test(TYPE type = B) { std::cout << type << ... | As I found out from my colleagues. C++ is a pretty funny language. Mainly due to its long history.
The meaning of the compilation error is that the problematic line of code: h::test (h::TYPE::A);
The compiler parsed as "creating a variable of type h::test with the name h::TYPE::A". And then the compiler goes crazy, bec... |
71,495,886 | 71,496,373 | Error when compiling source file which includes stb_image.h | I get this particular error when compiling a C++ source file which includes stb_image.h.
In file included from /home/zeux/Documents/Projects/cube-game/./lib/stb/stb_image.h:723,
from /home/zeux/Documents/Projects/cube-game/src/core/stbi_impl.cpp:2:
/usr/lib/gcc/x86_64-pc-linux-gnu/11.2.0/include/emmint... | There seems to be a problem with your compiler configuration for SIMD instruction generation. You should first disable SIMD:
#define STBI_NO_SIMD
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
If the program works correctly, you can try and investigate SSE2 support and add a compiler option -msse2.
|
71,496,512 | 71,497,041 | How to avoid controls flickering in a CDialog (MFC C++ ) | Hello i've been looking for a couple of days now how to avoid controls themselves from flickering in a CDialog.
I am using CMemDC and erasing the background to draw some basic shapes with GDI+
void CCustomDialog::OnPaint()
{
CPaintDC pDC(this);
CMemDC dc(&pDC);
Gdiplus::Graphics graphics(dc.GetSafeHdc());
... | You can set the style WS_CLIPCHILDREN in the dialog resource, for example:
IDD_STEP_DLG DIALOGEX 0, 0, 344, 215
// here:
STYLE DS_SETFONT | DS_FIXEDSYS | WS_MAXIMIZEBOX | WS_POPUP | WS_CLIPCHILDREN | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME
CAPTION "Dialog"
FONT 8, "MS Shell Dlg", 400, 0, 0x1
BEGIN
LTEXT "... |
71,497,336 | 71,501,389 | Trigraphs not compiling with MS compiler? | I have a C++14 project withe the Microsoft compiler in Visual Studio 2019 and I'm trying to understand Digraphs and Trigraphs, so my code is a bit weird:
#include "Trigraphs.h"
void Trigraphs::assert_graphs()
??<
// How does this ever compile ????/
ouch!
??>
Reading about the /Zc:trigraphs switch
Through C++... | MSDN also says:
The /Zc:trigraphs option is off by default
and that seems to apply for C++14 already. Although that results in a non 100% conformant C++ compilation, most programmers will actually prefer not dealing with the strange symbols of C++ trigraphs.
|
71,497,344 | 71,497,770 | no matching function for call to <unresolved overloaded function type> | I can't relate with similar questions. That's my MRE, basically I'd like to overload fun with a version accepting a template reference. It all works until std::thread enters in the game. It seems I'm missing something from its constructor.
Error shown on g++-10 is
error: no matching function for call to ‘std::thread::t... | My guess is that the constructor of std::thread cannot resolve which overload of fun you're trying to call. No idea why though.
Having only one version of fun such as
template <typename T, typename sem>
void fun(const std::string&, std::shared_ptr<sem>)
{
...
}
Allows you to construct t1 fine (but t2 will obviousl... |
71,497,660 | 71,504,284 | Can I implement this kind of profiling code with a macro? | Not an expert on preprocessor macro tricks, so if the problem here is just that I'm not familiar with some common macro idiom I'd be happy with just a term to Google. X macros are about as far as I've got before and I'm pretty sure I can't do anything with them.
Right now I do some stuff like this in code:
std::size_t... | I am assuming you do not want to have any dynamic memory management involved? Because otherwise you could simply use a std::vector and do a push_back() for each result...
Otherwise, I do not think this can be achieved easily by just using standard language elements. But MSVC, clang and gcc support __COUNTER__, which is... |
71,498,406 | 71,498,667 | VSCode Makefile no longer creating executable, which fails when make is invoked | So I was practicing with a tutorial series on C++ projects for Linux. In order to create the makefile I did CTR+SHIFT+P to go into Palet, searched for make file, selected the correct option, and selected C++ project. In the tutorial, the person changed src in the make file to a static path ie: pwd. That worked. When he... | The error message tells you exactly what the problem is, if you learn the compiler-ese to interpret it:
main.cpp:...: multiple definition of `List::List()'; obj/list.o:list.cpp:...: first defined here
Here it's saying you have defined the constructor twice: once in main.cpp and once in list.cpp.
And, as is the case 99... |
71,498,522 | 71,498,695 | class's friend function are incompatible? | IDE throws warning that the class's friend function are not compatible with the function's declaration outside of class.
What is the cause for the warning?
namespace CommonUtility
{
Interface::CellType Foo(int);
}
// when placed as friend of class Interface
class Interface
{
public:
static enum class CellType
... |
For Interface::CellType Foo(int); the Interface::CellType is unknown at that point and should result in a compiler error.
static enum class CellType would also result in a compiler error, because static is not correct here.
And finally:
The declaration of Interface::CellType CommonUtility::Foo(int); has to exists bef... |
71,498,764 | 71,502,739 | How can I prevent this memory leak? | Below is a stripped-down version of the problem I'm hitting with memory management in relation to using the Python interpreter from C++.
The code as it is below will run properly, but its memory footprint will gradually grow over time. I added a line to manually invoke the Python garbage collection; this didn't solve... | The problem is neither in Python nor its interface to C++. The problem is in Box2D, which is used by some of the OpenAI Gym environments.
I can repeat the above code while creating a different environment that doesn't use Box2D (such as "CartPole-v1") and let it run endlessly without any memory leak. As soon as I put... |
71,498,932 | 71,499,018 | Decide which member function to call by ternary operator | If I want to call function foo on an object thisThing (in C# jargon, this is called the "receiver", so I'll call it that here too) and pass the argument myStuff, I'll do it like this:
thisThing.foo(myStuff);
Super simple, nothing surprising going on here.
If I want to change the argument to yourStuff if a bool value b ... | You can use member function pointers, but you need special syntax to call the function via the pointer:
struct X {
void foo() {}
void bar() {}
};
int main() {
X thisThing;
bool b = false;
(thisThing.*(b ? &X::foo : &X::bar))();
}
However, I would not recommend to actually use it like this (unless ... |
71,498,992 | 71,499,960 | How can I use sub-projects in Qt? | I'm trying to move onto Qt to rewrite a win32 project that has a lot of static libraries so as a preliminary test project I tried creating a subdir project following the instructions in https://www.toptal.com/qt/vital-guide-qmake. I've seen plenty of other examples, and similar questions on this site, but none of them ... | To use library you need to setup two things: append INCLUDEPATH, and LIBS, you can do it in pri file, and then include in app, if error says "file *.h not found" it means INCLUDEPATH is incomplete.
Here's how you can do it:
Project structure
project/
├── app
│ ├── app.pro
│ └── main.cpp
├── library
│ ├── library.... |
71,499,092 | 71,499,607 | Generic function to accurately round floating-point to the nearest multiple of X | I am trying to write a generic function which rounds a double input value to the nearest multiple of X.
Due to floating-point precision reasons, the naive approach of just scaling and rounding can fail:
double round(double in, double multiple)
{
return std::round(in / multiple) * multiple;
}
For example, since 0.1... | Your round function is working correctly. The value of 0.14999999999999999445 is rounded downwards, just as you woudl expect it to be. The problem you face is that double values can not represent arbitrary values due to the limited precision. Now consider the following program with your round() function:
double x = 0.1... |
71,499,177 | 71,499,386 | Template specialization for constructor based on type | I've been looking for this for quite a while, and I maybe I just don't know what words to use to find it.
I have a template class that accepts a type, and would like the constructor to be different depending on if that type is a pointer or not. Here is some code to explain what I mean.
template <class T> class Example
... | You can either specialize the whole class:
template <class T> struct Example {
bool choice;
Example() : choice{false} {}
};
template <class T> struct Example<T*> {
bool choice;
Example(bool choice) : choice{choice} {}
};
int main() {
Example<int> e;
Example<int*> f(false);
}
Or via std::enab... |
71,499,436 | 71,499,721 | Why does selects-behaviour differ when trying to read and write sockets? | Lets say we have a client file-descriptor accepted with accept()
client_socket = accept(_socket, (sockaddr *)&client_addr, &len)
We now set this file-descriptor in a read and write fd_set:
fd_set readfds;
fd_set writefds;
//zero them
FD_ZERO(readfds);
FD_ZERO(writefds);
//set the client_socket
FD_SET(client_socket, ... | The purpose of select() is to not return until there is something for your program to do. That way your program can sleep inside select() until I/O is ready, wake up immediately to do the I/O, and then go back to sleep as quickly as possible afterwards.
So the question is, how does select() know when to return? The a... |
71,499,469 | 71,500,139 | Strange behavior in std::make_pair call with CRTP class | Problem
I have a simple CRTP-pattern class BaseInterface, and two classes, derived from this class: test_dint and test_dint2.
Difference between test_dint and test_dint2 - in test_dint dtor explicitly declared as ~test_dint() = default;.
I'm try make std::pair with types <std::intptr_t, test_dint> by calling std::make... | It's because when you declared the destructor, you prevent the compiler from generate a move constructor, so test_dint is not moveconstructable (nor copyconstructable since it's base) anymore.
explicitly declare it would make it work.
test_dint(test_dint&&)=default;
|
71,499,571 | 71,499,766 | Why are deques used as the underlying container for stacks by default, when vectors would do the trick? | As I understand, any container that supports push_back(), pop_back() and back() can be used as the underlying container for stacks, but by default, deques are used. I understand the pros of deques over vectors generally (possibility to add elements at the beginning as well as at the end), but in the case of stacks, I d... |
I don't see any reason to prefer deques.
A reason to prefer deque that applies to the stack use case is that individual push back has worst case constant complexity compared to vector whose individual push back is linear in worst case (it has amortised constant complexity over multiple push backs). This was particula... |
71,500,261 | 71,506,382 | Converting ctype float to python float properly | I am receiving a ctype c_float via a C library that I would like to convert to a regular python float.
The problem is that ctype uses 32 bit precision while python uses 64 bit precision.
Say a user enters the number 1.9 into the C user interface. The number is represented as 1.899999976158142. When I print it on the C ... | People have pointed out that the number converted to float64 from float32 is exactly the same value stored in C and you need knowledge of the original number to meet your definition of more precise, but you can round the resulting number to the same number of decimal places as C (or what you think the user intended) an... |
71,500,440 | 71,500,698 | How to deduce a return type in C++ | I want to create some kind of Variant in C++. Actually I want to use templates as less as possible. The idea is to store the value in union both with the type of the variable and return the value according to the stored type.
So the test code looks like following:
#include <iostream>
#include <vector>
#include <cstring... | As per @UnholySheep's comment, what you're trying to do is have a function whose return type is deduced at runtime, which is simply not possible. The return type has to be known at compile time. So you're going to have to change your API. There are a few different options here.
This seems similar to std::variant, whose... |
71,501,272 | 71,501,877 | Fence Post Errors When Displaying Arrays | I am currently using C++ on a program called CodeZinger for one of my classes. I was asked to make a program that will output an array with input that the program gives me.
See screenshot below.
The issue is that the program outputs an extra space at the end of my array, which is making the program say that I have not... | Have the inner loop iterate until j < cols - 1 and then write one more output line after it ends, without a space (e.g.: std::cout << arr[i][cols-1];) –
UnholySheep
|
71,501,516 | 71,504,659 | How to implement user input in a linked list? | For this code I need to be able to use user input of books they have read and put them in a linked list. I have most of the code done but when I try putting books in the list the code isn't adding the books to the list. How can I fix this?
this is the function.cpp file
void displayMenu()
{
cout << "[1] Add Book\n"
... | OK got it
In deleteLast
if (head->next == NULL)
{
delete head;
return;
}
You forgot to update head
if (head->next == NULL)
{
delete head;
head = NULL; <<<<=====
return;
}
also in the delete function you don't update tail, you need
Book* ptr = head;
while (ptr->next->next != NULL)
ptr = ptr->ne... |
71,501,540 | 71,501,646 | How to join a number of threads which don't stop in C++ | In C++ I have an std::vector of threads, each running a function running forever [while(true)].
I'm joining them in a for loop:
for (auto& thread : threads)
{
thread.join();
}
When the program finishes I'm getting a std::terminate() call inside the destructor of one of the threads. I think I understand why that h... | If the threads cannot be joined because they never exit then you could use std::thread::detach (https://en.cppreference.com/w/cpp/thread/thread/detach). Either way before joining you should always check std::thread::joinable (https://en.cppreference.com/w/cpp/thread/thread/joinable).
The std::terminate is indeed most l... |
71,502,101 | 71,502,217 | Can i cast method pointer to long(int, size_t) | My problem is i need to represent a pointer to class's method like integer number. So it's not problem with functions, for example void (*func)() easy cast to number, but when i trying to cast void (&SomeClass::SomeMethod) to integer with any ways compiles says it's impossible
C-style cast from 'void(ForthInterpreter:... | A pointer-to-member is not just a simple pointer, it is much more complex. Depending on compiler implementation, it could be 2 pointers, one to the object and one to the method. Or it could be an object pointer and an offset into a method table. And so on.
As such, a pointer-to-member simply cannot be stored as-is i... |
71,502,700 | 71,503,863 | cannot run code (error: no such file or directory) but can compile file C++ VSCode | File structure in folder /home/cyan/proj10
fst
| -- include
| |-- fstlib
| |-- fst_reader.h
|
| -- lib
|-- libfst.so
include
| -- A.h
| -- B.h
src
| -- A.cc
| -- B.cc
main.cc
CMakeLists.txt
fst folder is a library I added.
CMakeList.txt
cmake_minimum_required(VERSION 3.0.0)
project(R... | Okay
First
Try use CMake extension
Second
Run Code does one simple thing - it compiles and runs the program from your current file.
cd "/home/cyan/proj10/" && g++ main.cc -o main && "/home/cyan/proj10/"main
Compilation at this point knows nothing about your CMake project, compilation flags, include paths, etc.
If you'... |
71,503,147 | 71,503,289 | Linked list SIGSEGV, Segmentation fault | I was doing a practice problem using linked lists (I wanted to practice them a bit more) and I got the following error
Program received signal SIGSEGV, Segmentation fault.
0x0000555555555888 in LinkedList::getLink (this=0x0) at main.cpp:24 24
return link;
I can't tell what the problem with this method is,since lookin... | In
void freeLinkedLists(LinkedList *start)
{
LinkedList *helper=start->getLink(); // fails immediately if start is null
while(start!=nullptr)
{
delete start;
start=helper;
helper=helper->getLink(); // too late. Helper may already be null.
// This wo... |
71,504,035 | 71,668,051 | how to working with files in c++ in this sample code? | in this project, we can add product information and save them into a file <product.txt>.notice that the file name can include space and it can be muluti_piece -->Ex)Samsung air conditioner.
but for reading the name from file in the 'edit' Function I have to use getline function. but when I use getline in edit function ... | the way to solve this problem is put a Product_For_read.ignore(); on top the problem line .
|
71,504,552 | 71,504,654 | Split variadic template params up to use as single template parameters for other classes | I'm trying to figure out how to give arbitrary template parameters to a class, then have that class use each of those parameters to instantiate a bass class. Something along these lines:
template<class T>
SingleParamClass;
template<class ... TYPE_LIST>
MultiParamClass : SingleParamClass<TYPE_LIST[0]>, SingleParamClass... | You can expand the parameter pack like so:
template<class T>
struct SingleParamClass {};
template<class ... TYPE_LIST>
struct MultiParamClass : SingleParamClass<TYPE_LIST>... {};
|
71,504,735 | 71,505,204 | template template parameter deduction with C++ class templates | Is there a way, without partial template specialization, to determine the template parameter of a template parameter that a class is templatized with, assuming that a class can only be templatized with a template parameter that itself is a template?
To make things concrete, here's an example:
template <typename T>
stru... | It is for situations like this why standard containers expose a value_type member, eg:
template <class T>
struct A {
// Needed: a function to print the size of the template parameter
// that "T" is templatized with, e.g. "char" in the example
// below
void printSize() const { cout << sizeof(typename T::... |
71,504,813 | 71,505,031 | C++: algorithmic complexity of std::next and std::nth_element for std::multiset | What is the algorithmic (time) complexity of std::next and std::nth_element for a std::multiset in C++? I am interested in the latest gcc implementation, in particular, if it matters. I have a set of numbers in std::multiset and I need to compute their median. I have a feeling that it should be possible to do it in O(l... | std::next is O(k) in the distance you move.
There is no other way to get the median, practically, if you have a multiset.
It is possible to write a more efficient advance operation on containers like this, but std does not contain it.
You could keep around two multisets and balance them using splicing operations such t... |
71,505,155 | 71,505,217 | C++ and MSVC #define directive with optional arguments | I'm having trouble trying to get a macro that I'm writing to function correctly. I've read the docs and can't find anything online to help with what I'm looking for.
I am attempting to write a macro that is used for info and debugging purposes. The exact macro should look like:
INFODUMP("Some format string here with a ... | That's not how printf() works.
Your macro expands:
INFODUMP("%d", 42);
To:
std::printf("INFO: %s\n", "%d", 42)
You need:
#define INFODUMP(s, ...) std::printf("INFO: " ## s ## "\n", __VA_ARGS__)
Which will then expand:
INFODUMP("%d", 42);
To:
std::printf("INFO: %d\n", 42)
|
71,505,162 | 71,505,277 | Clicking on command window seeming halts program execution, how to prevent this? | I just started a simple text program in C++ (MSVS) that outputs to the command window, it is a simple timer that counts up by 1 every second. When I click on the command window (inside of it, on the blank text) it appears to halt the program execution, until I stroke a key, click off the window, or the title bar. Is it... | You have selected text in the window, the window is expecting you to do a copy operation. The console window stopped accepting new info from the app while you have stuff selected. It does this trying to be helpful, (if you are copying text you dont want to have to chase it round the screen)
People also use this as a qu... |
71,505,316 | 71,505,369 | Does this downcasting lead to undefined behavior? | Given this sample:
class Base
{
public:
void foo() {};
};
class Derived : public Base
{
};
int main()
{
Base b;
Derived* d = static_cast<Derived*>(&b);
d->foo();
}
I just have three cases: when void foo():
is member of Base,
and when it is member of Derived,
and... | From the C++ standard §7.6.1.9.11
A prvalue of type “pointer to cv1 B”, where B is a class type, can be converted to a prvalue of type “pointer to cv2 D”, where D is a complete class derived from B,
...
If the prvalue of type “pointer to cv1 B” points to a B that is actually a base class subobject of an object of type... |
71,505,585 | 71,506,689 | How to get the expiration date based on week code not on current date using c++ | How will I get the expiration date of an item, which is based on week code? Whenever I run the code that I made, the program reads the current date and disregards the week code. For example:
Week Code: 2138 (2021 week 38)
Shelf_life : 6 months
CTime weekcode = CTime::GetCurrentTime();
CTimeSpan shelf_no = CTimeSpan(a... | Here's how I would do it using Howard Hinnant's free, open-source, header-only date library:
#include "date/iso_week.h"
#include "date/date.h"
#include <chrono>
#include <iostream>
int
main()
{
using namespace date;
int weekcode = 2138;
int shelf_life = 6;
iso_week::year y{weekcode / 100 + 2000};
... |
71,506,169 | 71,506,322 | Passing an entire group of variables as one argument to a function C++ | I'm trying to simulate a system that requires multiple variables and parameters and requires multiple nested functions. I was wondering if there was a way to pass them as a group so I can just pass one or two arguments without having to itemize each parameter and variable within each function and trying to keep track o... | Write a struct with the parameters.
The multiple nested functions either need an override taking such a struct, or be rewritten to consume it as their argument.
Now you can pass parameters around in a bundle.
If the set of parameters is not uniform, you might be out of luck. You also might be able to solve it using in... |
71,506,213 | 71,566,954 | How Can I implement MSAA on DX12? | I Searched many other questions and samples, but I still can't understand what I must do.
What I know about this process is
Create a Render Target for msaa. - Different from SwapChain's Backbuffer.
Draw everything (like meshes) on msaa render target.
Copy the contents of the msaa Render Target to the current BackBuffe... | These samples demonstrate using MSAA with DirectX12:
https://github.com/microsoft/Xbox-ATG-Samples/tree/master/PCSamples/IntroGraphics/SimpleMSAA_PC12
https://github.com/microsoft/Xbox-ATG-Samples/tree/master/UWPSamples/IntroGraphics/SimpleMSAA_UWP12
I also cover this (among other topics) in this blog series.
Per the ... |
71,506,421 | 71,506,442 | How to overload function template function inside a class template? | How can I overload the Contains function template in class template Range?
When I run this code , I get an error as below:
template <typename T>
class Range {
public:
Range(T lo, T hi) : low(lo), high(hi)
{}
typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type
Contains(T value, ... | You need to make Contains themselves template too. E.g.
template <typename X>
typename std::enable_if<!std::numeric_limits<X>::is_integer, bool>::type
Contains(X value, bool leftBoundary = true, bool rightBoundary = true) const
{
// do sth
return true;
}
template <typename X>
typename std::enable_if<std::n... |
71,506,510 | 71,506,542 | How to resolve the error: called object type 'char' is not a function or function pointer | So, in a program I was trying to print a pair from a stack. The code is as follows:
#include <iostream>
#include <stack>
#include <utility>
using namespace std;
int main()
{
stack<pair<char, int>> deleteOperations;
stack<pair<pair<char, char>, int>> replaceOperations;
deleteOperations.push(make_pair('a', 1... | std::pair<>::first is a member variable, not a function, just use deleteOperations.top().first; and replaceOperations.top().first.first
|
71,506,554 | 71,506,842 | SetTokenInformation fails with 24, but the length is correct | I'm trying to create a elevated SYSTEM token, but the code below fails:
#include <windows.h>
#include <stdio.h>
BOOL Elevate()
{
PSID pSID = NULL;
HANDLE hToken = NULL, hToken2 = NULL;
SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_AC... | Per the TOKEN_INFORMATION_CLASS documentation
TokenIntegrityLevel
The buffer receives a TOKEN_MANDATORY_LABEL structure that specifies the token's integrity level.
Where TOKEN_MANDATORY_LABEL is defined as:
typedef struct _SID_AND_ATTRIBUTES {
#if ...
PISID Sid;
#else
PSID Sid;
#endif
DWORD Attributes;
} SID_A... |
71,506,735 | 71,506,782 | C++ How to add two arrays of unequal sizes using the for loop? | So the aim is to take two arrays as shown below
int x[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int k[4] = {1, 2, 3, 4};
and add each element of k to each element of x in a loop as shown
1 2 3 4 5 6 7 8 9 10
+1 +2 +3 +4 +1 +2 +3 +4 +1 +2
This should give us a final array [2, 4, 6, 8, 6, 8, 10, 12, 10, 12].
An... | Loop through the indexes of the larger array, using the modulus (%) operator to wrap-around the indexes when accessing the smaller array.
int x[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int k[4] = {1, 2, 3, 4};
int res[10];
for (int i = 0; i < 10; ++i) {
res[i] = x[i] + k[i % 4];
}
Online Demo
|
71,507,110 | 71,507,571 | Is it Undefined behavior to not having a return statement for a non-void function in which control can never off over the end? | I am learning C++ using the books listed here. In particular, I read that flowing off the end of a non-void function is undefined behavior. Then I looked at this answer that says:
In C++ just flowing off the end of a value returning function is always undefined behavior (regardless of whether the function's result is ... | The two statements are in no way contradictory.
The first statement is about what happens when control flow exits a non-void function without executing a return statement. The second statement is about what happens when control flow does not exit the function at all. Calls to functions like exit or std::terminate do no... |
71,507,133 | 71,507,163 | What does this line mean?, can we assign something to an object other than attribute? | Greetings this is my first question here.
I'm really new to C++, and to Object Oriented Programming as well.
So, my tasks currently need to wrap this C++ library, the code is:
#include "cavc/polylineoffset.hpp"
int main(int argc, char *argv[]) {
(void)argc;
(void)argv;
// input polyline
cavc::Polyline<... | The line in question is calling a function named parallelOffset, that was declared in a namespace called cavc. The function returns an object of type std::vector<cavc::Polyline<double>>, so the line is declaring an object of that type and setting it equal to the value retuned by the function.
The syntax is the same as... |
71,507,970 | 71,514,472 | Is bitshifting from an unsigned to a signed smaller type portable? | I have a unsigned short (which is 16 bit on the target platforms)
It contains two 8-bit signed values, one in the lower byte, one in the higher byte.
#include <vector>
#include <iostream>
int main() {
unsigned short a = 0xE00E;
signed char b = a & 0xFF;
signed char c = ((a >> 8) & 0xFF);
std::cout << (i... | Disclaimer: I am no language lawyer
Is this portable, or am I relying on platform dependent behaviour here?
Since there is no version specified, I used last draft.
So what did we need to check:
Can unsigned short hold 0xE00E and signed char can hold 8 bits?
How a & 0xFF and ((a >> 8) & 0xFF) are transformed into sig... |
71,508,125 | 71,508,173 | OpenCV: Unable to get a red line in Hough transform | I have written a simple code to perform Hough transform and display the lines. The code is as follows,
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int lowThreshold=0;
int const max_lowThreshold = 100;
int k... | You are drawing Hough lines on the gray image of canny.
|
71,508,298 | 71,508,447 | Access mouse.button variable in QML | I was trying something to strengthen my experience with C++ and QML.
I have a MouseArea item. I want to pass the "onPressed" , "onReleased" and "onPositionChanged" events to the backend side that I am trying to write in C++. Actually I want this for clean and simple code. I can do whatever I want by writing in QML.
The... | I looked at the documentation here. https://doc.qt.io/qt-6/qt.html#MouseButton-enum I solved it by working directly with the unsigned integer.
void Viewer::mousePressEvent(double x, double y, quint32 button) {
qDebug() << "Viewer::mousePressEvent()";
qDebug() << "x: " << x << " y: " << y << " button: " << butt... |
71,508,553 | 71,512,833 | Backup the database file as sql inside the zip file on QT C++ | I want to backup my database by creating a zip file with qprocess in the QT program, in the code below it does it as a sql file. How can I make a backup inside the zip file?
QProcess dump(this);
QStringlist args;
QString path="C:/Users/ali/Desktop/dbfile/db.sql";
args<<"-uroot"<<"-proot"<<"denemesql";
dump.setStandardO... | The easy way is perform it in two steps: dump and then zip
bool dump1() {
QString path = "C:/Users/ali/Desktop/dbfile/db.sql";
QString zipPath = "C:/Users/ali/Desktop/dbfile/db.zip";
QProcess dump;
dump.setProgram("mysqldump.exe");
dump.setArguments({"-uroot", "-proot", "denemesql"});
dump.setS... |
71,509,342 | 71,514,771 | Why does static_cast conversion speed up an un-optimized build of my integer division function? | ... or rather, why does not static_cast-ing slow down my function?
Consider the function below, which performs integer division:
int Divide(int x, int y) {
int ret = 0, i = 32;
long j = static_cast<long>(y) << i;
while (x >= y) {
while (x < j) --i, j >>= 1;
ret += 1 << i, x -= j;
}
return ret;
}
This... | Widening after the shift reduces your loop to naive repeated subtraction
It's not the run-time of cdqe or movsxd vs. mov that's relevant, it's the different starting values for your loop, resulting in a different iteration count, especially for pathological cases.
Clang without optimization compiled your source exactly... |
71,509,445 | 71,522,528 | How do I get rid of the default macOS menu items in wxWidgets? | "Toggle Sidebar" is the only item I have added, how do I remove the other items which I don't really need? I'm stuck
I'm on macOS 12.2 with wxWidgets v3.1.5
here's the code I used to add the menu:
wxMenuBar *mainMenuBar = new wxMenuBar();
wxMenu *viewMenu = new wxMenu();
viewMenu->Append(wxID_ANY, "Toggle Sidebar");
ma... | As said in the comments, calling SetMenuBar() on the frame first and then appending the menus fixed the issue.
|
71,509,586 | 71,509,670 | usage of import with plain header files | Is it good practice to get rid of #include and only use the import keyword instead even for headers (like <span> or "Foo.h")? Are there any benefits to this? Any possible downsides? Does it add to the length of build time?
cppreference has an example in which it says this:
import <set>; // imports a synthesized header... |
Are there any benefits to this?
Importing synthesised header units instead of including the header may satisfy a style guide that wants to use one type of directive for both modules and headers.
Any possible downsides?
It won't work in pre-C++20 code, nor compilers that haven't yet implemented importing header file... |
71,509,935 | 71,511,394 | How does mixing relaxed and acquire/release accesses on the same atomic variable affect synchronises-with? | I have a question about the definition of the synchronises-with relation in the C++ memory model when relaxed and acquire/release accesses are mixed on one and the same atomic variable. Consider the following example consisting of a global initialiser and three threads:
int x = 0;
std::atomic<int> atm(0);
[thread T1]
... | Because you use relaxed ordering on a separate load & store in T2, the release sequence is broken and the second assert can trigger (although not on a TSO platform such as X86).
You can fix this by either using acq/rel ordering in thread T2 (as you suggested) or by modifying T2 to use an atomic read-modify-write operat... |
71,510,209 | 71,510,324 | SFINAE still produces error while using exception | I am learning about SFINAE in C++. So after reading about it, i am trying out different examples to better understand the concept. Below i have given 2 snippets out of which 1 i can understand but the second one where i have used noexcept in the declaration i can't understand.
Example 1: I am able to understand this.
#... | The problem is that exception specification do not participate in template argument deduction(TAD). This is explained in more detail below. Source: C++ Templates: The Complete Guide Page No. 290
Case 1
Here we consider example 1. In this case, since there is no func the error in the declaration of the function template... |
71,510,249 | 71,511,141 | Different char values require different sizes in file | I have this code snippet to write a buffer to a file
int WriteBufferToFile(std::string path, const char* buffer, int bufferSize) {
std::ofstream ofs;
ofs.open(path);
if (!ofs) {
return 1;
}
ofs.write(buffer, bufferSize);
if (!ofs) {
return 2;
}
ofs.close();
r... | I'm going to take a wild guess and say that you're running this code on a Windows system.
Here's what I think is probably happening.
ofs.open(path) is opening the file in text mode. On Windows, text mode means that every newline character (1 byte) will be replaced by a CRLF sequence (2 bytes). Your buffer contains 1 mi... |
71,510,298 | 71,510,384 | Dangling reference solution | T&& operator[](std::size_t n) && noexcept {std::cout<<"move"<<std::endl; return std::move(vec[n]); }
I cannot get the expected result in this part.
I predict a dangling reference happens.
T operator[](std::size_t n) && noexcept {std::cout<<"move"<<std::endl; return std::move(vec[n]); }
This works well.
Why doesn't T&& ... | For auto&& vec = my_vector<int>{1, 2, 3}[0];, the reference isn't bound to the temporary (i.e. my_vector<int>{1, 2, 3}) directly, its lifetime won't be extended.
In general, the lifetime of a temporary cannot be further extended by "passing it on": a second reference, initialized from the reference variable or data me... |
71,510,314 | 71,522,125 | How to wrap a class derived from vector in swig | I want to wrap a class derived from std::vector with some extend functions into csharp with swig. the functions from vector are also needed like push_back to add new item into the class (which named Add in csharp).
I tried with default setting with swig, IntArray is valid in csharp .But, vector's functions are invalid.... | SWIG is picky about order of declarations. Below correctly wraps your example code and can call the sum function. I'm not set up for C# so the demo is created for Python:
test.i
%module test
%{
// Code to wrap
#include <vector>
#include <numeric>
namespace test
{
struct ScalarTest {
int val;
};
... |
71,510,678 | 71,510,789 | Static class variable initializing to 100 by itself | This is my first question on here, so excuse me if I've formatted everything in a wrong way.
So, to get to the problem - this is s university assignment of mine. The goal is to create a class called Student, which has a few fields, and store the instances in an array of Student objects. One of the tasks is to have a st... | The global declaration Student students[100]; calls the default Student constructor 100 times, before main is reached. According to your comment (you don't supply the constructor implementation), that constructor increases amount by 1.
A solution here is to remove Student::amount and instead use
std::vector<Student> st... |
71,511,313 | 71,511,413 | Qchart Remove the line point from bottom | I am new in QT, I want to build a chart. In the chart, i want to show only line. You can see the picture with is attached. How can i remove this point?1 Thank you.
| you should hide legends.
chart->legend()->hide();
For example :
QChart *chart = new QChart();
chart->addSeries(series);
chart->setTitle("Simple areachart example");
chart->createDefaultAxes();
chart->axes(Qt::Horizontal).first()->setRange(0, 20);
chart->axes(Qt::Vertical).first()->setRange(... |
71,512,488 | 71,512,538 | Only Printing the First Value of Linked List | I have no idea why display function is not displaying anything other than the first node's data. I've tried switching the While(p!=NULL) to while(p->next!= NULL but when I do that instead of only the first node's data displaying no data is being displayed.
#include <iostream>
using namespace std;
class Node {
public:... | In the while loop, it should be
while (p->next!= NULL) {
p = p->next;
}
p->next = n;
Traverse until the end of linked list is reached and then, add the new entry.
|
71,512,649 | 71,512,930 | "Failed to specialize alias template" errors for the most simple SFINAE bool condition | I'm trying to implement simple condinional implementation and failing tremendously... A tried this:
template<class T, bool COND=0> class A
{
public:
template< typename TT=T >
std::enable_if_t<!COND> METHOD() const { };
template< typename TT=T >
std::enable_if_t<COND> METHOD() const { };
};
and... | What about as follows?
template<class T, bool COND=0> class A
{
public:
template< bool CC=COND >
std::enable_if_t<!CC> METHOD() const { };
template< bool CC=COND >
std::enable_if_t<CC> METHOD() const { };
};
I mean... if you want enable/disable a method of a class through std::enable_if, you h... |
71,512,973 | 71,513,105 | Usage of decltype in return type of function template removes error due to exception specification | I saw an answer to a question here. There the author of the answer made use of the fact that
exception specifications do not participate1 in template argument deduction.
In the answer linked above it is explained why the following doesn't compile:
#include <iostream>
template<typename T>
void timer(T a) noexcept(fun... | Here since there is no func, so during the substitution of the template argument(s) in the return type of the function template, we get substitution failure and due to SFINAE this function template is not added to the set. In other words, it is ignored.
Thus the call timer(5); uses the ordinary function timer since it ... |
71,513,265 | 71,515,300 | Visual Studio Code: Theme One Monokai: Change / Custom Highlight Color for C/C++ `const` | I am using the (amazing) One Monokai theme in visual studio code. One thing that bothers me is that variable modifers like const and control flow like for, if, while, ... are displayed using the same color. Based on this tutorial, I tried a custom coloring by adding to settigs.json:
"editor.semanticTokenColorCustomizat... | With the comment pushing me into the right direction and this tutorial, the working code is
"editor.tokenColorCustomizations": {
"[One Monokai]": {
"textMateRules": [
{
"scope": "storage.modifier.specifier.const.cpp",
"settings": {
"foreground"... |
71,513,853 | 71,514,308 | Segmentation fault when using threads on function with large arrays -C++ | I am using threads for the first time and came across a weird segmentation error whenever the called function takes very large arrays.
#include <iostream>
#include <thread>
#include <cmath>
const int dimension = 100000; // Dimension of the array
// Create a simple function of an array
void absolut(double *vec) ... | double p* = new double[dimension];
double v* = new double[dimension];
I think this compiles because of the compiler defined size limits maybe using dynamically allocation.
|
71,514,176 | 71,514,236 | Initialization of member variable via parentheses doesn't work | For the following codes, can anyone explain why we can't initialize the variable data by parentheses?
#include <iostream>
using namespace std;
class X
{
private:
int data(1); // wrong here
public:
void print()
{
cout << data << endl;
}
};
int main()
{
X temp;
temp.print();
return 0;... | There isnt actually much to explain, its just not valid syntax. Default member initializers are
class X
{
private:
int data{1}; // ok
int data2 = 42; // also ok
public:
void print()
{
cout << data << endl;
}
};
While int data(1); is not valid syntax for a default member initializer. Se... |
71,515,071 | 71,515,245 | Accessing entries of multidimensional variables using the gams-c++ api | I am generating the following gams program with my c++ program
variable x(*) /1.lo = -1,1.up = 1,2.lo = -1,2.up = 1/;
variable obj; equation eqobj; eqobj.. obj =e= x['1']+x['2'];
parameter ms, ss, lbd, ubd, cpu;
model mod /all/;
option decimals = 8;
solve mod minimizing obj using minlp;
lbd=mod.objest; ubd=obj.l;
ms=mo... | I guess you want to iterate over all records of x? There is actually an example in the tutorial for a two dimension variable doing this:
for (GAMSVariableRecord rec : m_job.outDB().getVariable("x"))
cout << "x(" << rec.key(0) << "," << rec.key(1) << "):" << " level=" << rec.level() << " marginal=" << rec.marginal()... |
71,515,127 | 71,516,243 | D3D11CreateDeviceAndSwapChain Fails With E_ACCESSDENIED When Using Same HWND | If I create a window and pass the HWND to D3D11CreateDeviceAndSwapChain, it works. However, after I release the device, context, swapchain, etc and try to repeat the process using the same HWND, D3D11CreateDeviceAndSwapChain fails with E_ACCESSDENIED. This tells me something must be holding onto the HWND, but what? I r... | While D3D11CreateDeviceAbdSwapChain does not mention why this is happening in the documentation, it is essentially just a wrapper around creating a D3D11Device and swap chain. The documentation for IDXGIFactory2::CreateSwapChainForHwnd does go into detail on why this is happening.
Because you can associate only one fl... |
71,515,356 | 71,515,571 | c++ doesn't set some of the array elements to nullptr | Inside of int main() i declared double* arr = new double[2]; (an array that its items should be set to double or to nothing)
then i tried to change the values of the array elements from another function void func(double* arr_pointer[2]) by setting them to
arr_pointer[1] = nullptr;
arr_pointer[0] = nullptr;
but after i... |
double* arr = new double[2];
(an array that its items should be set to double or to nothing)
arr is a pointer to a double. It points to the first element of an array of 2 doubles. The elements are double objects; they cannot be "nothing" objects. Furthermore, the array doesn't contain any pointers.
Sidenote: Avoid ... |
71,515,602 | 71,515,744 | Random number generator generating low numbers more frequently than high numbers C++ | So, I have made a program that simulates things and in it I noticed that the c++ function rand() seemed to generate low numbers too often, so I tried to test it.
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <vector>
#include <cstdlib>
#include <time.h>
#include <cfloat>
#include <iomanip>
using ... | For a uniformly distributed random variable E in the open interval [0, 32767]
the probability of mod(E, 10000) < 2800 is around 34%. Intuitively you can think of mod(E, 10000) < 2800 as favouring the bucket of numbers in the range [30000, 32767]: that bucket modulo 10000 is always less than 2800. So that has the effect... |
71,515,992 | 71,517,984 | rapidjson schema how to get the keyword from the error | I'm making a physical software and we deploy a json solution and I wanted to used json schema. So, when I had a wrong key typical looking a "length" in the schema and the user gives somethings wrong like "length2". I don't know how to get it with rapidjson actually, I obtained these results
Invalid schema: #/propertie... | So I found my answer by following the schemavalidator.cpp example in rapidjson folder.
I provide here the example in my case :
https://github.com/faudard/rapidjson_scheme
I use the "CreateErrorMessages" same to the example.
|
71,516,283 | 71,516,362 | Do I need to delete pointer in stack, which is created in heap? | int *createInt()
{
int *a = new int;
return a;
}
int main()
{
int *x = createInt();
*x = 10;
cout << *x << '\n';
delete x; // do I need this?
return 0;
}
DO I need delete x? If i don't, will it cause a memory leak problem?
| You appear confused about the distinction between a pointer and the pointed at object. a and x are pointers. Think of a piece of paper with a party address written on it.
int *a = new int; allocates a new object on the heap and assigns the address to the pointer a. This is like starting a party at a house, and then wr... |
71,516,427 | 71,517,869 | Is it possible to detect WASM compiler in code via compiler directives? | Is there a standard #define I can detect within my own C++ code that would indicate if WASM is compiling the code?
In C++ on Android I can use #ifdef __ANDROID__ but I'm not sure for Web Assembly ? I'm actually using emcc compiler so maybe there's a standard #define for EMCC compiler...
Thanks
| You can use __wasm__ to detect the Wasm architecture in general or __wasm32__/__wasm64__ to be more precise. Or you can use __EMSCRIPTEN__ to specifically detect the emscripten target.
|
71,517,035 | 71,517,111 | Accept and return lambda (lock wrapper) | I want to accept any lambda, so that it can perform some operation safely under the lock_guard and then return anything, but using as shown below throws an error:
#include <iostream>
#include <functional>
#include <mutex>
#include <memory>
class Test {
public:
template<typename Ret>
Ret DoLocked(st... | This is easily solved by getting rid of std::function and making the function parameter a template parameter. That would look like
template<typename Func>
auto DoLocked(Func func) -> decltype(func(*this)) {
std::lock_guard<std::mutex> lock(*mtx);
return func(*this);
}
The reason it doesn't work with the std::... |
71,517,342 | 71,517,560 | vtkDelaunay3D::SetAlpha() does not accept values below 0 | I'm trying to use VTK's Delaunay3D() to get a minimal bounding surface on my data using the alphaShapes algorithm. The particular dataset I'm working on is generally toroidally- or cylindrically-shaped, so by my understanding I should be trying to find a value < 0 for alpha. The class, however, does not seem to be able... | It looks like your code is doing 3D Delaunay triangulation, not alpha shapes.
From the documentation for Delaunay3D:
For a non-zero alpha value, only verts, edges, faces, or tetra contained within the circumsphere (of radius alpha) will be output.
In this implementation of Delaunay triangulation, alpha is a radius th... |
71,517,568 | 71,520,419 | What's the best way to get a list of all the macros passed as compiler arguments? | I'm working on a code base that uses quite a bit of conditional compilation via macros passed as arguments to the compiler (i.e. gcc -DMACRO_HERE file.cpp). I would like to have a way to get a list of all the macros defined this way within the code so that I can write out all the used macros to the console and save fil... | Here's an outline of a possible solution.
The request is not well-specified because there is no guarantee that all object files will be built with the same conditional macros. So let's say that you want to capture the conditional macros specified for some designated source file.
On that basis, we can play a build trick... |
71,517,790 | 71,518,704 | Cannot Convert in_addr to Unsigned Int in Socket Programming for Linux | I'm building a reverse echo server in TCP using c++.
My problem occurs when I run my client.
When I compile my client.cpp, I get this error:
error: cannot convert ‘in_addr’ to ‘in_addr_t {aka unsigned int}’ in assignment
serverAddress.sin_addr.s_addr = *((struct in_addr*)host->h_addr);
This is my code for creating a... | You are trying to assign a whole in_addr struct instance to a single integer. That will not work.
The sockaddr_in::sin_addr member is an in_addr struct, and the in_addr::s_addr member is the actual IP address. Just drop the s_addr part to assign the whole in_addr struct as-is:
serverAddress.sin_addr = *((struct in_ad... |
71,518,089 | 71,518,117 | A reference to a class member | A reference to a class member is kind of an offset relative to the class. If I understood everything correctly. But why is 1 always output here?
#include <iostream>
struct user
{
int id;
double name;
std::string last;
};
template<class V>
void kek(V b)
{
std::cout << b << std::endl;
}
int main()
{
kek(&us... | &foo::bar is a pointer-to-member. There are no references-to-members.
cout can't print member pointers directly, the closest thing it can print is bool. Your pointer was converted to bool, and since it was non-zero, you got true.
If you want to get an offset from a pointer-to-member, you could try std::bit_casting it t... |
71,518,200 | 71,518,785 | How to get timestamp from date time format in C++? | I would like to get timestamp from date time format in C++. I wrote C style solution, but this->cache_time doesn't promise \0 at the end because it is std::string_view.
std::time_t client::get_cache_time() {
struct tm time;
if(strptime(this->cache_time.data(), "%a, %d %b %Y %X %Z", &time) != N... | I don't know if this solution is clean and memory efficient, but it works.
std::time_t client::get_cache_time() {
std::tm time;
std::istringstream buffer(std::string(this->cache_time));
buffer >> std::get_time(&time, "%a, %d %b %Y %X %Z");
if(!buffer.fail()) {
return timelocal(&ti... |
71,518,396 | 71,519,613 | Is it okay to delete an object that is created in the app from dll | I have a dll with a class that uses an abstract class for customizing the behaviour and it also has an implementation defined in dll
With this the app allocates a Child object and passes it into the class A which it deallocates the object when it is deleted
Can deleting an object that is created in the app from the dll... | MS says this:
The DLL allocates memory from the virtual address space of the calling process (docs)
And in this answer you can see:
If your DLL allocates memory using C++ functions, it will do so by calling operator new in the C++ runtime DLL. That memory must be returned by calling operator delete in the (same) C++... |
71,518,890 | 71,518,981 | Couldn't resolve LNK2019 on VS | while coding I got the following error: 1>giochino.obj : error LNK2019: riferimento al simbolo esterno "public: void __thiscall entity::print_Pv(int,int)" (?print_Pv@entity@@QAEXHH@Z) non risolto nella funzione _main 1>C:\Users\tomma\source\repos\giochino\Debug\giochino.exe : fatal error LNK1120: 1 esterni non risolti ... | Your implementation file is wrong, you need
#include "your.h"
void entity::print_Pv(int pv_now, int pv_max) {
char pv_bar[10];
int pv_perc = ( pv_now / pv_max) * 10;
for (int i = 0; i < 10; i++) {
if (i <= pv_perc) {
pv_bar[i] = '*';
}
else if (i > pv_perc) {
... |
71,519,156 | 71,519,409 | How can i make it display 5 different asterisk using functions | I need to make a program to that display five different asterisk using functions C++ for a test and currently, its saying too many arguments and also cant take one arguments
#include <iostream>
using namespace std;
void asterisk();
int main()
{
int k;
int i;
// Asking the user to input 5 random between 1 ... | If i have not understood wrong you are looking something like this
#include<iostream>
#include<vector>
using namespace std;
void display(int a);
vector<uint> asterisks = vector<uint>(5);
int main()
{
// Asking the user to input 5 random between 1 to 30
cout << "Enter "<<asterisks.size()<<" numbers between 1... |
71,519,706 | 71,519,998 | Appending to vector of union | I have a union, defined like so:
union CellType {
std::string str;
int i;
double d;
Money<2> m; // Custom class for fixed-decimal math.
};
Then, I have a vector of such unions.
std::vector<CellType> csvLine;
My question is, how do I append a value to the end of the vector? I normally use push_back fo... | There is no clean way to do this for the simple reason that given an arbitrary instance of this union there is no authoritative way for a generic, template-based function/method, like std::vector::push_back to know which member of the union is active, in order to execute the member-specific copy/move operation, when at... |
71,519,720 | 71,520,044 | On acquire/release semantics not being commutative to other threads | The gcc wiki here provides an example on memory ordering constraints.
In the below example, the wiki asserts that, if the memory ordering in use is an acquire/release, then thead-2's assert is guaranteed to succeed while thread-3's assert can fail.
-Thread 1- -Thread 2- -Thread 3-
y.store (20)... |
and since y can be 10 if and only if x is 10,
And that's the part that is incorrect.
An acquire/release pair works between a releasing store operation and an acquiring load operation which reads the value that was release-stored.
In thread 1, we have a releasing store to x. In thread 2, we have an acquiring load from... |
71,519,972 | 71,520,227 | Constructor with exception handling for invalid input c++ | I'm trying to create a constructor that validates input and throws an exception if the input is invalid.
Let's say I have a constructor that only accepts values in mod 12 for int a, values of mod 16 for b, and values greater than 0 for c. I'm trying to use the std::invalid_argument. How would I implement the exception ... |
How would I implement the exception handler?
By NOT implementing it in the constructor that is throwing. Implement it in the code that is trying to pass invalid input to the constructor, eg:
Mod(int a, int b, int c){
if (a > 11 || a < 0 || b > 15 || b < 0 || c < 0 ) {
throw std::invalid_argument("Invalid Ar... |
71,520,009 | 71,522,920 | OMP for loop condition not a simple relational comparison | I have this program that isn't compiling due to error: condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', '>=', or '!=') of loop variable 'i', referring to for (size_t i = 2; i * i <= n; i++). How can I modify and fix it without affecting performance? Is this an issue due to having an old Ope... | Loop after the #pragma omp parallel for have to be a canonical form to be confirming. In your case the problem is with the test expression, which should be one of the following:
var relational-op b
b relational-op var
So, you have to use what was suggested by @Yakk: calculate the sqrt of n and compare it to i:
const s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.