question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
73,938,115 | 73,942,084 | boost::process environment not being propagated | I am trying to run an external command which uses environment variables to authenticate.
For this I am using boost::process:
namespace bp = boost::process;
std::string exec_bp(const std::string& cmd)
{
bp::ipstream pipe;
bp::child c(cmd, bp::std_out > pipe, boost::this_process::environment());
return std:... | To mimic the search-path behaviour of a shell, use boost::process::search_path.
To mimic a shell, use e.g.
bp::child c("/usr/bin/bash",
std::vector<std::string>{"-c", "aws s3 ls s3://foo/bar"},
// ...
Note this is typically bad for security. Instead, consider the more direct
bp::child c("/usr/local/bin/aws",
... |
73,938,303 | 73,938,788 | error: type/value mismatch in template parameter list for std::variant | The following code doesn't work if class some_class is templated. So my guess is that I have to put the template specifier in front of something, but I don't really know where? I tried putting it in front of state::base and state::error types within the variant definition, but this doesn't work. Where do I put it and w... | The compiler considers state::base and state::error to be dependent (on the template arguments), in which case they would require prefixing with typename so that they are considered types while parsing the class template definition.
However, intuitively these names/types seem like they shouldn't be dependent. Although ... |
73,938,329 | 73,942,752 | Why is this loop seeming to change the value of a variable? | The following code is meant to calculate 7 terms: tcapneg, tcappos, tneg1, tneg2, tpos1, tpos2, tzcap (only the calculation of tpos1 and tpos2 is shown here), and determine the entry that satisfies the condition of being the smallest positive non-zero entry.
int hitb;
double PCLx = 2.936728;
double PCLz = -0.016691;
do... | Your array double tlist[7] is in double with 7 elements. sizeof(double) is 8, so sizeof(tlist) is 8*7 = 56. While sizeof(int) is 4, so your size = sizeof(tlist) / sizeof(int) is 56/4 = 14. Your loop goes beyond number of elements in the array. It counts 7 more double values after the array in memory, because the array ... |
73,938,344 | 73,993,883 | How qt find <Qxxx/qxxx.h>? | In Qt 6.4.0, we can use such code to include qt components:
#include <QtCore/qchar.h>
#include <QtCore/qbytearray.h>
#include <QtCore/qbytearrayview.h>
#include <QtWidgets/qtwidgetsglobal.h>
But I found that the real paths of those .h file are NOT under such folder like QtCore, QtWidgets etc. , actually most of them a... | It's been solved: This phenomenon only shows on MacOS since MacOS uses "framework" to organize a set of lib and headers, which can be parsed by the clang-module name to the realpath.
|
73,938,523 | 73,938,581 | C++ Generic Addition Method | I have struct like this
template <typename T>
struct container
{
T norm() const
{
T sum = 0;
for (unsigned int i = 0; i < length; i++)
{
sum += value[i];
}
return sum;
};
private:
T *value{nullptr};
unsigned int length{0};
};
I have a norm() method th... | To initialize a T, the way to do that in the template function is to use the brace-initializer:
T sum = {};
This will initialize sum to whatever the type T would be equal to if you default construct (for classes such as std::string) or value-initialize (for types such as int, double, etc.). For integer types, double, ... |
73,939,922 | 73,939,932 | How do I make pass and fail count work in c++? | I'm working on this function for one of my classes and my pass count works just fine, however, my fail count ALWAYS prints out 12. I've been reading my code top to bottom and just can't seem to find the problem.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
string passAndFailCount(... | Your problem are uninitialized variables.
int pass_count = 0;
int fail_count = 0;
and you're set.
For an explanation. Non-global variables (which automatically get initialized to 'default' (0) as per the standard), automatic and dynamic variables (like the one you are using), assume the value of 'whatever was in memor... |
73,939,959 | 73,942,023 | Why does std::pmr::polymorphic_allocator not propagate on container copy construction? | Why does std::pmr::polymorphic_allocator not propagate on container
copy construction?
See the Notes section here
Allocators do propagate on move construction, so this behavior seems to be inconsistent.
Also, with copy elision, this behavior can be somewhat odd. Depending on whether a copy ctor is elided or not, the co... | From looking into the various standard proposals, I can find no explanation for making polymorphic allocators not propagate the memory resource on copy construction. The very first proposal (pdf) includes this language, and every version thereafter keeps moving it forward.
However, in searching around for the purpose o... |
73,940,236 | 73,940,398 | C++ How to include a third party library into your library without compiling it? | I am building my first C++ library (header-only) and I want to include a third party library like Crypto++. Now I believe I am supposed to compile the Crypto++ library and put the compiled archive inside the ./lib directory and pass the linker commands when compiling my library. But since I do not want to compile the 3... | You are developing a header-only, platform-independent C++ library that happens to depend on a traditional (i.e. not header-only) C++ library, but which is also portable to a wide range of target platforms.
What you need to tell your users is that your library depends on that other library (crypto++ in this case), and ... |
73,940,416 | 74,534,596 | VSCode GDB debugging Internal error while converting character sets | While debugging like normally (before I didn't have this kind of problem) GDB returned message :
Internal error while converting character sets: No error.
Only for viewing string or char kind of variables.
I have tried to disable Windows beta UTF-8 engine, tried additional commands from here StackOverflow
Unfortunat... | Unfortunately I couldn't find any logical answer to my question. The only thing that helped was deleting MSYS2 with gdb and gcc installed and installing it once again.
Now I can't reproduce this issues so maybe in the future I'll comeback with the same error. Will see.
|
73,940,961 | 73,941,091 | Confused about std::is_standard_layout type trait | Standard-layout class describes a standard layout class that:
has no non-static data members of type non-standard-layout class (or array of such types) or reference,
has no virtual functions and no virtual base classes,
has the same access control for all non-static data members,
has no non-standard-layout base class... | The cppreference description is a little confusing.
The standard (search "standard-layout class is") says:
A standard-layout class is a class that:
has no non-static data members of type non-standard-layout class (or array of such types) or reference,
has no virtual functions (10.3) and no virtual base classes (10.1)... |
73,941,068 | 73,941,077 | How to define a type dependent on template parameters | I have a class that has methods that will return Eigen::Matrix types. However, when these will be 1x1 matrices, I want to just return double, as treating scalars as Eigen::Matrix<double, 1, 1> is a bit nasty. Essentially, I want something like this:
template <int rows, int cols>
class foo
{
using my_type = ((rows =... | Use std::conditional_t<cond, TThen, TElse>:
template <int rows, int cols>
class foo
{
using my_type = std::conditional_t<rows == 1 && cols == 1, double, Eigen::Matrix<double, rows, cols>>;
};
If you don't yet have std::conditional_t<>, you might try std::conditional<>::type (with typename prefix).
|
73,941,082 | 73,941,126 | I don't know what cause segmentation fault(core dumped) | void hexdump(void* ptr, const int buflen)
{
unsigned char* buf = (unsigned char*)ptr;
int i, j, d, hex = 0;
short* ins;
string op;
for (i = 0; i < buflen; i += 16) {
for (j = 0; j < 16; j += 4) {
if (i + j < buflen) {
cout << buflen << endl;
cout << "inst " << (i+j) / 4 << ": ";
I ... | tldr: The variable ins is pointing to a random memory because the code never assigns it to anything valid. Hence, you have undefined behavior (crashing being the most likely outcome) when dereferencing this pointer and writing to it's address.
short* ins; // THIS POINTER NEVER GETS ALLOCATED OR ASSIGNED TO VALID ME... |
73,941,558 | 73,941,962 | Parallelizing for-loop inside another loop efficiently with OpenMP | I have a problem writing the parallel instructions for a code that work like this:
// every iteration depends on the previous one
for (int iter = 0; iter < numIters; ++i)
{
#pragma omp parallel for num_threads(numThreads)
for (int p = 0; p < numParticles; ++p)
{
p_velocity_calculation(...);
}
... | First of all: the thread pools are not destroyed, only suspended.
Next: Have you timed this and found that creating the threads is a limiting factor in your application? If not, don't worry.
Or to put it constructively : I have timed it and unless you have an extremely short omp parallel for and you call it tens of tho... |
73,941,872 | 73,941,989 | Copying an array of Object Pointers | What would be the correct way to copy an array of pointers pointing to a certain object into another object through the constructor?
Assuming that:
// ClassA.h
class ClassA {
ClassB** m_classBs{};
public:
ClassA(const ClassB* classBs[], size_t cnt);
}
ClassA::ClassA(const ClassB* classBs[], size_t cnt) {
m_c... | You have to use use the correct type:
class ClassA {
const ClassB** m_classBs;
public:
ClassA(const ClassB* classBs[], size_t cnt);
~ClassA() { delete[] ClassB; }
};
ClassA::ClassA(const ClassB* classBs[], size_t cnt) : m_classBs(new const ClassB*[cnt]) {
for (size_t i = 0; i < cnt; i++) {
m_classBs[i] = c... |
73,941,895 | 73,942,807 | Why in my code cpp compare_exchange_strong updates and return false | The problem:
So I'm pretty new to CPP and i was trying to implement a simple comparison code using some atomicity concepts.
The problem is that I'm not getting a desired result, that is: even after the compare_exchange_strong function updates the value of the atomic variable (std::atomic), it returns false.
Below is t... | TL:DR: race condition between another thread modifying it vs. the debugger getting control and reading memory of the process being debugged.
Or the value had been Action::Status::CANCEL for a long time, not expected = App::Action::Status::PENDING;, in which case a single thread running alone could have this behaviour. ... |
73,943,280 | 73,943,399 | Expanded from macro & Expected unqualified-id Errors | I'm currently studying global - local variables in C++. From what I understand, we can use the same variable name as global and local variable in the same program (in my program I've used 'g' as the same variable name). However, when I tried to use the same variable name as definition (#define) I got an "expanded from ... | #define does not define a variable. It defines a macro that is replaced as a sequence of tokens in the rest of the code before any of the code is actually compiled. There is no scope to them.
There is literally a translation step (called the preprocessor) which will replace the g with 5 everywhere in the rest of the co... |
73,943,439 | 73,943,566 | Comparing String (.substr()) to Character (.back()) in C++ | I am trying to compare whether the last letter of the word "A", and the next letter of the word "B" is the same.
I'm iterating over "B"; and comparing within an if statement:
string A = ""
string B = "XYZTTTTLMN"
for (long i = 0; i < B.length(); i++) {
if ( A.back() != B.substr(i,1) ) { ... }
}
I receive an err... | In C++, a string having size=1 is not same as a character.
This is the reason you are getting error as string and character cannot be compared as you did.
To solve this you can use below code:
for (long i = 0; i < B.length(); i++) {
if ( A.back() != B.at(i) ) { ... }
}
OR
for (long i = 0; i < B.length(); i... |
73,944,851 | 73,946,794 | How to paint image inside of the entire QScrollArea? | Steps to reproduce using Qt Designer:
1- Add a "Grid Layout"
2- Right click in the MainWindow background and
Lay out -> Lay out in Grid
3- Add a "Scroll Area"
4- Add a "Frame"
5- Right click in the "Scroll Area" and
Lay out -> Lay out in Grid
6- Add a "Label" into the "Frame" and right click it
and Lay o... | Widget's geometry is not the problem. If your widget is inside layout, then you do not need to care about geometry at all because it is automatically calculated by the layout. You only may need to care about the geometry of the whole window, but not child widgets.
The blank space around your widget is determined by lay... |
73,945,008 | 73,945,320 | How can i transfer elements from queue to stack? | A queue Q containing n items and an empty stack s are given. It is required to transfer all the items from the queue to the stack so that the item at the front of queue is on the TOP of the stack, and the order of all other items are preserved.
I tried coding it but it only prints the elements of queue.
#include <iostr... | Your transfer function (Stack) is wrong. The exercise it to use the queue and the stack to:
Empty the queue by pushing each element on to the stack.
Empty the stack by popping each element and pushing it into the queue
Empty the queue by pushing each element on to the stack.
The result will produce a stack whose top ... |
73,945,017 | 73,949,085 | Contradictory SFINAE on constructor using std::is_constructible | Why is the following code behaving as commented?
struct S
{
template<typename T, typename = std::enable_if_t<!std::is_constructible_v<S, T>>>
S(T&&){}
};
int main() {
S s1{1}; // OK
int i = 1;
S s2{i}; // OK
static_assert(std::is_constructible_v<S, int>); // ERROR (any compiler)
}
I get that f... | Your first code example is undefined behaviour, because S is not a complete type within the declaration of itself. std::is_constructible_v however requires all involved types to be complete:
See these paragraphs from cppreference.com:
T and all types in the parameter pack Args shall each be a complete
type, (possibly ... |
73,945,190 | 73,945,279 | Can I inherit from std::array and overload operator []? | The question is rather straightforward. I'm trying to define a custom array class which has all the features of a normal std::array, but I want to add the ability of using operator [] with a custom type defined in my codebase.
One option is to wrap my class around the std::array, something like:
using MyType = double; ... | The inheritance itself is legal, as long as you don't try to delete the derived class through a pointer to the base class, which lacks the virtual destructor.
The problem is that return std::array<T, Size>(*this)[abs(round(var))]; creates a temporary std::array and returns a reference to its element, which immediately ... |
73,945,612 | 73,945,719 | c++ - How can I delete a undeclared pointer? | If the new operator was written in a function argument or constructor argument like:
Foo* f = new Foo(new Baz(0, 0));
// how to delete "new Baz(0, 0)"?
delete f;
I know it can be written to:
Baz* b = new Baz(0, 0)
Foo* f = new Foo(b);
delete b;
delete f;
But it became complicated, is there any better way?
Should I do... | Following my own recommendation about the rule of zero and using std::unique_ptr, I would do something like this:
class Foo
{
public:
Foo(int a, int b)
baz_{ std::make_unique<Baz>(a, b) }
{
}
private:
std::unique_ptr<Baz> baz_;
};
And
auto foo = std::make_unique<Foo>(0, 0);
With this the foo ... |
73,945,659 | 73,945,891 | Question about array new placement in C++ | I have question about new placement of array in c++.
below code is a sample code that i made.
#include <vector>
#include <iostream>
class Point
{
int x,y;
public:
Point():x(0), y(0){std::cout<<"Point() : "<<this<<std::endl;}
void print(){std::cout<<x<<":"<<y<<std::endl;}
Point(int a, int... | I would simplify this way:
First, just allocate the array with a low level function like malloc() or mmap(), brk() and dispose of it accordingly. It helps to keep the two worlds separated.
Second, when calling placement new you do not necessarily need to take that pointer if you already have it.
And last it looks like... |
73,946,196 | 73,946,387 | Visual Studio compiles with CMake in x64-Debug mode but in x64-Release mode "could not find any instance of Visual Studio" | I'm using Visual Studio to open a CMake C++ project. When I set it to x64-Debug mode at the top and compile, it works fine. However, when I change it to x64-Release, it suddenly tells me:
CMake Error at CMakeLists.txt:5 (project):
Generator
Visual Studio 16 2019
could not find any instance of Visual Studio.
I'm litera... | It turns out that deleting all Visual Studio generated files/folders and setting up a new x64-Release configuration solved the problem.
|
73,946,197 | 73,947,962 | Does boost asio strand run all handlers on the same thread? | The boost asio documentation talks about executors but I can't see if that implies the same thread.
The reason I'm curious about this is that the purpose of a strand seems to be to allow the developer not to have to worry about multithreading issues. If that is the case then I see two options for a strand, assuming mo... | No.
All that is guaranteed is that
all handlers are invoked on a thread that is invoking run[_one] or poll_[one] on the execution context. This is is true for handlers on any executor
strand executors add the guarantee that handlers are only invoked sequentially (non-concurrently) and in the order they were posted (se... |
73,946,484 | 73,947,166 | is there a null stream? optional printing | I use functions like
void doStuff(type thing, bool print = false, std::ostream& S = std::cout)
{
thing++;
if(print)
S << "new thing: " << thing << '\n';
}
so that I can use the same function and decide on call if I want it to print documentation of what is happening and if I wish I can print that on se... | Writing own streams is not difficult and can be found in good books.
I created a "NULL" stream class for you.
Please see the very simple example below.
#include <iostream>
// This is a stream which does not output anything
class NullStream : public std::ostream
{
// streambuffer doing nothing
class NullBuffer ... |
73,946,791 | 73,946,996 | Macro for nested maps in C++ | Is it possible to create simple interface to create nested std::maps in C++? If this is possbile, can I go advanced and make it with different nested maps/vectors
CreateMaps(4); returns std::map<int,std::map<int,std::map<int,std::map<int,int>>>>>
CreateMaps(3); returns std::map<int,std::map<int,std::map<int,int>>>>
I... | Yes you can, even without macros, but by using recursive templates. Here is what it could look like:
// Recursive definition
template<typename T, size_t N>
struct NestedMap {
using type = std::map<T, typename NestedMap<T, N - 1>::type>;
};
// Termination condition for the recursion
template<typename T>
struct Nest... |
73,947,153 | 73,951,888 | Visual Studio 2022 behaving wierdly in C++, not showing errors in code | I'm currently learning C++ and encountered a strange behavior of VS. Errors are not showing up in code (even though IntelliSense is enabled - I checked settings) and the lines in error list are probably wrong too.
main.cpp:
#include <iostream>
#include <string>
#include "fraction.h"
using namespace std;
int main()
{
... | The reason for the code for not compiling was not writing std::string or using namespace std at the top in fraction.h as @molbdnilo has pointed out. What confused me, was that VS highlighted the code and knew I ment to write std::, but the compiler did not.
Also, I would like to point out my mistake (which has nothing ... |
73,948,048 | 73,948,102 | Is there a function for moving the contents of a char array a certain amount of addresses back in C++? | I have the following code for Arduino (C++). This is for a checksum consisting of 2 characters forming a base 16 value between 0 and 255. It takes int outputCheckSum and converts it to char outputCheckSumHex[3].
itoa (outputCheckSum, outputCheckSumHex, 16)
if (outputCheckSum < 16) { //Adds a 0 if CS has fewer than 2 ... | You should be able to use memmove, it's one of the legacy C functions rather than C++ but it's available in the latter (in cstring header) and handles overlapping memory correctly, unlike memcpy.
So, for example, you could use:
char buff[5] = {'a', 'b', 'c', '.', '.'};
memmove(&(buff[2]), &(buff[0], 3);
// Now it's {'a... |
73,949,214 | 73,952,297 | Libtorch C++: Efficient/correct way for saving/loading Model and Optimizer State Dict for retraining | I am looking for the correct and most efficient way of saving, loading, and retraining a model in Libtorch (C++) with both the model and optimizer state dict. I believe I have everything correctly set (however this may not be right for saving and loading optimizer state dicts, only the model state dict I am absolutely ... | To answer my own question, the model state dict needs to be loaded and then parameters put into the optimizer object. Then load the state dict into the optimizer object.
My use case was a little more complicated as I was aggregating gradients from multiple nodes where training was happening and doing an optimizer step ... |
73,950,786 | 73,951,445 | How to create a view over a range that always picks the first element and filters the rest? | I have a collection of values:
auto v = std::vector{43, 1, 3, 2, 4, 6, 7, 8, 19, 101};
Over this collection of values I want to apply a view that follows this criteria:
First element should always be picked.
From the next elements, pick only even numbers until ...
... finding an element equal or greater than 6.
This... | With range-v3, you can use views::concat to concatenate the first element of the range and the remaining filtered elements, for example:
auto v = std::vector{43, 1, 3, 2, 4, 6, 7, 8, 19, 101};
auto r = ranges::views::concat(
v | ranges::views::take(1),
v | ranges::views::drop(1)
| ranges::views::filter([](const... |
73,950,891 | 73,950,982 | C++ code example that makes the compile loop forever | Given that the C++ template system is not context-free and it's also Turing-Complete, can anyone provide me a non-trivial example of a program that makes the g++ compiler loop forever?
For more context, I imagine that if the C++ template system is Turing-complete, it can recognize all recursively enumerable languages a... | While this is true in theory for the unlimited language, compilers in practice have implementation limits for recursive behavior (e.g. how deep template instantiations can be nested or how many instructions can be evaluated in a constant expression), so that it is probably not straight-forward to find such a case, even... |
73,951,046 | 73,951,244 | Collect positive floats & output the average when negative integer is input | I'm trying to write a program that reads in positive float numbers from the user and then when the user's is a negative number, gives the average of the numbers, excluding the negative.
#include <iostream>
using namespace std;
int main() {
float av_number, total = 0, input;
do {
for (int i = 1; i >= 1; i = ++i) {
... |
you don't need the for loop, you just need some iterator to count the number of entered numbers, so you can delete that for loop and use a counter variable instead.
also, you are breaking in the loop without checking if the input < 0, so you can write this
if (input < 0)
break;
also, you shouldn't calculate av... |
73,951,141 | 73,952,940 | "Must construct a QApplication before a QWidget" error, but only on Windows builds? | I am working on a CMAKE C++ project which uses the QT Libraries. (For me, 5.15.3, for others 5.12.x)
In this project, there is a class Vtk3DViewer : public QWidget. In its constructor, it tries to create one of its member variables, which is of type QVTKOpenGLNativeWidget. This is from the VTK libraries. (Located in in... | The issue was that VTK was built in RELEASE, while our project was built in DEBUG.
(I did not see this as an issue, since we would never need to step into/debug VTK's code)
It appears this cryptic/incorrect error message will appear under these circumstances. Ensuring VTK and the project it includes are compiled the sa... |
73,951,626 | 73,957,272 | Understand to which constrained edge a Steiner point belongs in constrained conforming triangulation CGAL | I followed the example reported here: https://doc.cgal.org/latest/Mesh_2/index.html (at paragraph "1.3 Example: Making a Triangulation Conforming Delaunay and Then Conforming Gabriel") to create a conforming constrained Delaunay triangulation using CGAL.
Making the triangulation conforming may introduce in the triangul... | If you use the Constrained_triangulation_plus_2 with your current triangulation as base triangulation, you will have a notion of subconstraints that will give you access to vertices in the middle of original constraints. However, if you have intersection between your input constraints, the intersection vertices will al... |
73,951,667 | 73,951,711 | How to define a C++ concept for a range to a std::pair of reference wrappers? | See the code below (also here https://www.godbolt.org/z/hvnvEv1ar). The code fails to compile if I uncomment the constraint for either rng or pair. I feel like I am missing something trivial, but I can't figure out why the constraint is not satisfied.
#include <vector>
#include <ranges>
#include <utility>
template <... | The compound requirements { expression } -> type-constraint requires that decltype((expression)) must satisfy the constraints imposed by type-constraint, since decltype((t.first)) will be treated as an ordinary lvalue expression, it will result in a const lvalue reference type.
You might want to use C++23 auto(x) to ge... |
73,951,944 | 73,957,219 | how to use Point_set and k_neighbor_search in cgal? | I am trying to make the orthogonal_k_neighbors _search (or any kdtree based search) in cgal with points defined in a Point_set object.
The idea would be to fetch a point and associated vector near a given point. However I am having issue about the correctness of the Traits adaptation for this specific case.
I think The... | You should write:
Traits traits(pSet.point_map());
Tree tree(pSet.begin(), pSet.end(), Splitter(), traits);
Point_3 query(0.1, 0.15, 0);
K_neighbor_search search(tree, query, 3, 0, true, Distance(pSet.point_map()));
Basically, you have to pass the point map to the traits and to the distance. The default poi... |
73,952,129 | 73,958,825 | A number K and an Array of size N is given, check whether we can get the sum of any two elements of array equal to K | I tried to solve the problem but my code still contains some bugs. Why isn't it running?
Here is the link of the question website: https://www.hackerearth.com/practice/data-structures/hash-tables/basics-of-hash-tables/practice-problems/algorithm/pair-sums/?
#include <iostream>
#include <bits/stdc++.h>
usin... | The problem is that while hsh[A[i]] is always valid, hsh[hsh[A[i]] is not.
Consider the following input:
1 1
10000
This does the following:
A[0] = 10000;
...
hsh[10000] = 1 - 10000; // = -99999
...
if (hsh[10000] == 1 - hsh[-99999]) {...}
So your code is reading out of bounds of the array hsh[]. Make sure you check f... |
73,952,462 | 73,952,816 | pass string variable as a table name in an SQL query | My program takes in a string as a parameter, and attempts to create a table in an SQL database with the passed string parameter as the name of the table.
I have experience with SQL, but I'm new when it comes to implementing it in C++.
class logger {
public:
string name; //name of application to be lo... | You can't build a C string the same way you build a C++ std::string.
Instead, make sql be a std::string, build the string, then use its c_str() method to get a C string pointer from it.
string sql;
...
rc = sqlite3_exec(db, sql.c_str(), callback, 0, &zErrMsg);
|
73,952,909 | 73,953,099 | Two different Arrays are referencing each other in C | I am very new to C / C++ and I am learning the basics. I want to write a program that prints the number of vowels as vowCount in a person's name that is an input. I have two char arrays, name[20] to hold the string input from the user and vowels[] to hold vowels.
I want vowCount to increase by 1 if two chars match betw... | This array
char vowels[] = {'a','e','i','o','u'};
does not contain a string: a sequence of characters terminated by the zero character '\0'.
As a result this for loop
for(uint8_t i =0; vowels[i] != '\0'; i++){
invokes undefined behavior because neither element of the array vowels is equal to '\0'.
Instead you could d... |
73,953,329 | 73,953,377 | Non macro based unit test frameworks | Bjarne Stroustrup said in a video on CppCon that, one of his desires for the future of the language is to remove the preprocessor ecosystem from the standard.
I am looking for a unit test that is design is not macro based, but I am unable to found anything decent.
Does anyone knows about one?
| No decent ones currently exist, because there are still some things that are impossible to do in C++ without macros (e.g. getting a stringified version of an assert expression). Before we can remove our usage of macros, the C++ language needs to evolve. Check back in 10 years.
In the meantime, I recommend Catch2.
|
73,953,724 | 73,953,805 | c++ How do write a number sequence separated with comma's correctly? | The sequence consists of all numbers from 1 to N (inclusive), n(1<=n<=100). All the odd numbers are listed first, then all the even numbers. For example you input 8 and the code prints this: 1,3,5,7,2,4,6,8. Although when I input an odd number it adds a comma in the end. It's my first time here, no idea how to post it ... | My pattern.
The comma doesn't get postfixed. It gets prefixed on everything but the first item.
// print odd
for (int i = 1; i <= n; i += 2)
{
if (i != 1)
{
cout << ",";
}
cout << i;
}
for (int i = 2; i <= n; i += 2)
{
cout << ",";
cout << i;
}
Or simplified:
for (int i = 1; i <= n; i += 2)
{
... |
73,953,768 | 73,954,845 | Addressing stack variables | As far as I understand, stack variables are stored using an absolute offset to the stack frame pointer.
But how are those variables addressed later?
Consider the following code:
#include <iostream>
int main()
{
int a = 0;
int b = 1;
int c = 2;
std::cout << b << std::endl;
}
How does the compiler know w... | The location (relative to the stack pointer) of stack variables is a compile-time constant.
The compiler always knows how many things it's pushed to the stack since the beginning of the function and therefore the relative position of any one of them within the stack frame. (Unless you use alloca or VLAs1.)
On x86 this... |
73,953,783 | 73,954,224 | "Cannot form reference to void" error even with `requires(!std::is_void_v<T>)` | I'm writing a pointer class and overloading the dereference operator operator*, which returns a reference to the pointed-to object. When the pointed-to type is not void this is fine, but we cannot create a reference to void, so I'm trying to disable the operator* using a requires clause when the pointed-to type is void... | In addition to the Nelfeal's answer, let me give an alternative solution. The problem is not in the dependence of requires condition on T, but is in the return type T&. Let's use a helper type trait:
std::add_lvalue_reference_t<T> operator*()
requires(!std::is_void_v<T>)
{
...
}
It works because std::add_lvalue_... |
73,953,890 | 73,953,970 | How to validate bad input from a file stream? | I want to handle input validation in my such small program.
I have a file containing integer values separated by white spaces. But sometimes there's invalid values, for example letters or any other non-digit characters. So, I want to ignore those invalid values and push only the valid ints in a vector of integers.
Here... | Your input file has everything on 1 line, so what do you think will happen when v is encountered and then in.ignore() is called to ignore everything up to the next '\n' (line break)? That's right, it will ignore the rest of the file!
When using cin, your input values are on separate lines, so calling ignore() with '\n'... |
73,954,022 | 73,954,084 | Import C++ library that hasn't .dll or .lib files inside | So I have two examples of these libraries for printing nice tables. First and second.
I've watched MANY videos on "How to install/include/import a library into your C++ project" and each one talks about changing Visual Studio solution properties like C/C++ -> General -> Additional Include Directories, Linker -> General... | libfort has a README.md that describes how to integrate it with your project (a step that does not actually require prior compilation, as it is not a "lib" but merely some additional source files to be added to your project directly).
bprinter requires prior compilation / installation, and comes with a CMakeLists.txt c... |
73,954,645 | 73,954,933 | Can I use a map's iterator type as its mapped type? | I have a tree whose nodes are large strings. I don't really need to navigate the tree other than to follow the path from a node back to the root, so it suffices for each node to consist of the string and a pointer to its parent. I also need to be able to quickly find strings in the tree. The nodes of the tree themse... | You can wrap the iterator in a type of your own and reference that type instead to avoid the recurisve type problem.
struct const_iterator_wrapper {
using iterator_type = map<string, const_iterator_wrapper>::const_iterator;
iterator_type iter;
const_iterator_wrapper() {}
const_iterator_wrapper(iterato... |
73,954,725 | 73,954,769 | Is std::string an array of two iterators? | I do not understand the behavior of the following snippet.
How could this be happening?
#include <bits/stdc++.h>
using namespace std;
int main() {
string s = "apple";
string foo = {s.begin(), s.end()};
cout << foo << endl;
}
output:
apple
| Don't confuse how an object is constructed over what it fundamentally is.
A constructor can, and will, take in all kinds of things. Quite often these arguments are converted in some way, transformed into the form that's a more natural fit for the class in question.
In this case you're constructing a string out of a ran... |
73,954,974 | 74,019,802 | Gitlab CI/CD yml variables for CMake Windows build | I am writing CI/CD pipeline for Windows Gitlab runner installed on my local machine:
variables:
RT_VERSION: "0.1"
build-win64:
tags:
- "win64"
stage: build
script:
- echo $RT_VERSION
- mkdir build
- cd build
- cmake ../ -G "Visual Studio 16 2019" -DRELEASE_VERSION=$RT_VERSION -DCMAKE_BUILD... | The solution was found!
$RT_VERSION should be enclosed in quotation marks.
There is a correct gitlab.yml:
variables:
RT_VERSION: "0.1"
build-win64:
tags:
- "win64"
stage: build
script:
- echo $RT_VERSION
- mkdir build
- cd build
- cmake ../ -G "Visual Studio 16 2019" -DRELEASE_VERSION="$RT... |
73,955,065 | 73,955,340 | How to read all integers into array from input file in C++ | So let's say I have a file like this:
1 23
14
abc
20
It will read the numbers 1, 23, 14, but I also want it to read the value 20 into the array.
How can I accomplish this?
#include <iostream>
#include <fstream>
using namespace std;
int main(){
const int ARRAY_SIZE = 1000;
int numbers[ARRAY_SIZE], count = 0;
... | Here's how I would do it. I added comments to the code to explain the intent and used a std::vector<int> instead of an array with a hardcoded size since you didn't mention any restrictions and I feel it is a better way to handle the problem. If you must used a statically sized array you should be able to adapt this.
#i... |
73,955,616 | 73,956,209 | Iterate std::tuple indices with lambda | There are a lot of approaches how to iterate trough std::tuple. And it is similar to range-based-for loop. I want to do something like this, but with indices of tuple, to get access to elements of various tuples.
For example I have tuple of different types, but all of them has same free functions / operators std::tuple... | One convenient way in C++20 I use to iterate tuples is to create a constexpr_for function that calls a lambda with a std::integral_constant parameter to allow indexing, as described in my Achieving 'constexpr for' with indexing post.
#include <utility>
#include <type_traits>
template<size_t Size, typename F>
constexpr... |
73,956,613 | 73,957,506 | QMap Datatype in QML basic usage? | Assume I have a simple QMap declared and Initialized with values inside C++ and correctly exposed to QML.
C++
QMap<QString, QMap<QString, QString>> airflow_buttons_;
//simple getter
[[nodiscard]] QMap<QString, QMap<QString, QString>> airflow_buttons() const;
QML
console.log(ClimateModel.airflow_buttons);
prints t... | You should be using a QVariantMap all the way:
QVariantMap airflow_buttons = {
{"left", QVariantMap{
{"top_air", "NOT ACTIVE"}}}
};
btw, in QML you can also do this if you fancy:
console.log(ClimateModel.airflow_buttons.left.top_air)
|
73,956,788 | 73,956,966 | Parse error in valid JSON data with nlohmann's C++ library | i have the following JSON data in a .json file:
[
{
"Type":"SET",
"routine":[
{
"ID":"1",
"InternalType":"Motorcycle",
"payload":"2"
},
{
"ID":"12",
"InternalType":"Chair"
}
]
},
{
"Type":"GE... | json::accept(streamOfFile) reads from the input stream till the end.
json::parse(streamOfFile) can't read after the input stream end.
This has nothing to do with the JSON library, it's a general feature of streams, once have been read, they come to the end of file state.
You might want to reset the stream to the zero f... |
73,957,225 | 73,957,305 | Implement a swap function to get a move constructor in own container class | In all standard containers like std::map or std::vector there is a move constructor and a move assignment to avoid copying. I want to build my own Wector class with the same functionalities. My class declaration looks as follows:
class Wector{
public:
~Wector();
Wector();
Wector(std::size_t s);
Wecto... | You can just swap the pointers themselves (and, of course, the sizes). It doesn't matter which instance allocated the storage and which deletes it, it'll only belong to one instance at a time.
|
73,957,435 | 73,961,342 | Why gRPC client side cancellation only works when both client and server run on the same process? | I have an async server that streams data to a single async client. I would like to be able to cancel the streaming from the client side and have the server stop streaming.
Currently, I run both client and server on 2 separate processes on my local Windows 10 machine. But I have tried running the client on a separate ma... | After investigating this further, I think I found the issue. It seems to be some undocumented aspects regarding the behavior of a CompletionQueue.
I was using a single thread for the whole server program.
So the completion handlers are invoked on the same thread that calls a AsyncNext. Like so:
while(server_active)
{
... |
73,958,351 | 73,958,656 | Why does using double instead of float gives a wrong result in this double integration code? | I found the following code in this page to compute a double integral. Whenever I run it with all variables being declared as float, it gives the right result for the example integral, which is 3.91905. However, if I just change all float variables to double, the program gives a completely wrong result (2.461486) for t... | Due to numeric imprecisions, this line:
ny = (uy - ly) / k + 1; // 'ny' is an int.
Evaluates to 5 when the types of uy, ly and k are float. When the type is double, it yields 4.
You may use std::round((uy - ly) / k) or a different formula (I haven't checked the mathematical correctness of the whole program).
|
73,959,099 | 73,959,232 | how to initialize sockets in linux environemnt | I have a code snippet to initialize a sockets in windows. How would I initialize the socket in Linux environment.
WSADATA wsa
if(WAStartup(MkeWORD(2,2), $wsa) !=0 )
{
exit(0);
}
| On Linux you don't initialize a network environment like WSA. Sockets can be used out of the box.
See https://man7.org/linux/man-pages/man2/socket.2.html for documentation.
|
73,960,414 | 73,960,808 | Is there a 'requires' replacement for 'void_t'? | void_t is a nice hack to detect compilability of certain expressions, but I wonder if there is some way to do that check with requires (or requires requires ) since I really do not like void_t from the readability perspective.
For example, for a certain type I want to check if some expression is fine (i.e. compilable)... |
my real motivation is to check that something does not compile, for example that my nontemplated type does not have operator <
This is possible with concepts, perhaps I am misunderstanding?
template<class T>
concept has_less_than = requires(const T& x, const T& y)
{
{x < y} -> std::same_as<bool>;
};
struct Has_Le... |
73,962,524 | 73,990,758 | Is it possible to use istringstream to read in more than one parameter of a stream function? | Instead of writing a new istringstream argument, can I add another parameter inside nameStream? I have what I think below, and if this method is elligible, then can I tell the input stream to read in a space or endline to separate the two fullnames?
#include <iostream>
#include <string>
using namespace std;
string la... | No, that will not work.
As you can see in the definition of std::istringstreams constructor, it will not take 2 std::strings as parameter. So, you cannot do in this way.
You have to concatenate the 2 strings before and then handover to the constructor.
Please see below some example for illustrating what I was explainin... |
73,963,381 | 73,963,910 | high precision Sleep for values around 5 ms | I am looking for solution which would give me most accurate Sleep of a function for small values. I tried this code below to test it:
#include <thread>
#include <chrono>
#include <functional>
#include <windows.h>
using ms = std::chrono::milliseconds;
using us = std::chrono::microseconds;
using ns = std::chrono::nanose... | Well, sleeping exactly for a very short time cannot be guaranteed on standard desktop operating systems.
Also, you must deal with 2 aspects:
Time Measuring: If you measuring method has a low time resolution you may get completely wrong results when measuring.
The time resolution of the sleeping function itself.
Then,... |
73,964,025 | 73,964,842 | Polymorphic Smart Pointer Array as Argument | I want a static 2D array that takes an interface class pointer.
Using raw pointer Base* rawr[5][5] works fine but I want to work with smart pointers and only pass the raw pointer as an argument.
How can I make the code work without changing the args to smart pointers?
class Base {};
class Child : public Base {};
void... |
How can I make the code work without changing the args to smart pointers?
You can't pass around an array of smart pointers where an array of raw pointers is expected. However, you can have 2 separate arrays - an array of smart pointers, and an array of raw pointers that point to the objects that the smart pointers a... |
73,964,853 | 73,965,551 | ARM64 inline assembly BL BLR BR instructions | I am in the middle of a problem that I can't seem to figure out. It involves testing the instruction set using c++ and inline assembly for the arm64. My current problems are with BL, BLR and the BR instructions. My current code looks as follows:
#include <stdio.h>
#define LDRARRAYLENGTH (4)
__asm __volatile
(
"... | You need to tell the compiler about all registers you clobber, but you don't. The compiler doesn't see your changes to x0 and x30, the latter of which is presumably the reason why your program never returns from BranchingModes.
Haven't tested it, but this should work:
__asm __volatile
(
"mov x0, #0 ... |
73,965,388 | 73,974,658 | Where is my 'concepts' library for C++20 concepts? | I can successfully compile code that uses the concept keyword, but not anything that includes <concept> or <concepts>.
// #include <concepts> // fatal error: 'concepts' file not found
template<class T>
concept Adds = requires(T a, T b) { a+b; };
template<class T>
concept Subs = requires(T a, T b) { a-b; };
template<cl... | I compiled the following on Godbolt using Clang++ 15 and libc++. It proves that <concepts> is visible, that concepts can be applied and used, and that there are no linker errors.
#include <iostream>
#include <concepts>
#include <typeinfo>
template<class... T> using And = std::conjunction<T...>;
template<class... T> us... |
73,965,533 | 73,965,683 | std::vector of structs: How are the member of structs saved in memory | I have the following class:
struct xyzid{
uint16_t i;
uint16_t z,y,x;
};
std::vector<xyzid> example;
(...) // fill example
uint16_t* data = reinterpret_cast<uint16_t*>(example.data());
Can I now be sure that my pointer data is basically such that the first 16 bits refer to i, then z, y, x, before moving t... | The vector contains an allocated array of structs. The data pointer points at the 1st struct in the array. The structs in the array are stored sequentially in memory. And the fields of each struct are also stored sequentially in memory, in the order that they are declared. So yes, the array will consist of the 1st ... |
73,966,165 | 73,970,258 | When WINAPI calls my code and an exception is thrown, should I catch it and return an HRESULT instead? | I have implemented IThumbnailProvider which gets compiled to a dll and then registered using regsvr32.
Within the code, I make use of STL containers such as std::vector:
std::vector<double> someRGBAccumulatorForDownsamplingToThumbnail = std::vector<double>(1234567);
Because the STL containers are largely built around ... | IThumbnailProvider is a COM interface. The Component Object Model is a language-agnostic protocol that describes (among others) the binary contract between clients and implementers of interfaces. It establishes a boundary (the Application Binary Interface, ABI) with clear rules1.
Since the protocol is language-agnostic... |
73,966,205 | 73,971,745 | Implementing a "virtual" method returning *this (covariant return type) | I'm writing a hierarchy of classes of C++, let's say A, B inheriting A, C inheriting A, and D inheriting B.
Now, all of these classes must have a method bar() &, whose body is:
{
A::foo();
return *this;
}
It's the exact same code, doing the exact same thing - except for the type of the return value - which ret... | As Raymond Chen commented, c++23 would have deducing this which allows code like:
struct A
{
template <typename Self>
Self& bar(this Self& self) // Here self is the static type which calls bar
// so potentially the derived type
{
self.A::foo(); // or self.foo();
... |
73,966,725 | 73,993,212 | Does reinterpret_cast<unsigned long long> of an int64_t value really break strict aliasing? | I'm attempting to write a generic version of __builtin_clz that handles all integer types, including signed ones. To ensure that conversion of signed to unsigned types doesn't change the bit representation, I decided to use reinterpret_cast.
I've got stuck on int64_t which unlike the other types doesn't seem to work wi... | If you have a signed integer type T, you can access its value through a pointer/reference to the unsigned version of T and vice-versa.
What you cannot do is access its value through a pointer/reference to the unsigned version of U, where U is not the original type. That's undefined behavior.
long and long long are not ... |
73,967,019 | 73,967,060 | My program skips any digit that ends with a 9 | When I build it and run I noticed that my program sets dig1 to 0 as soon as it hits 9. So the output looks like this: 00, 01... 08, 10.
I searched on stackoverflow and cplusplus.com for a possible solution but I couldn't find it.
Here's the code in question:
#include <iostream>
using namespace std;
int main()
{
... | Just replace (dig1=='9') with (dig1>'9') as in
#include <iostream>
using namespace std;
int main()
{
int i;
char dig1 = '0', dig2 = '0';
for(i = 0; i < 90; i++)
{
cout << dig2 << dig1 << endl;
dig1++;
if(dig1 > '9')
{
dig1 = '0';
dig2++... |
73,967,750 | 73,967,779 | How do I limit the amount of digits accepted from the user? | I currently have this and I can't seem to make my else work so the whole program doesn't limit the input successfully. (Sorry for my English I speak French).
cout << "Veuillez entrer votre nombre de 6 chiffres : ";
cin >> val;
if (val < 100000);
{
cout << "Erreur! Veuillez recommencez avec un nombre a 6 chiffres. ... | Firstly, a semicolon between the ) and { of an if statement creates an empty if statement body, followed by an unconditional block, which is not what you want.
To check if a number has more than a certain number of digits, try comparing against negative 999999 instead.
The code should be made shorter by using logical o... |
73,968,056 | 74,029,119 | Module loading and unloading when calling createwindow | I am trying to create a simple dropdown menu in a dialog box. Here is the bit of code that actually does it:
BOOL CALLBACK Remove(HWND hDlgc, UINT message, WPARAM wParam, LPARAM lParam)
//message handler for remove category box
{
//UNREFERENCED_PARAMETER(lParam);
HINSTANCE current = GetModuleHandle(NULL);
... | Solution was simple. just put this code:
HWND dd_Hand = CreateWindow(WC_COMBOBOXW, _TEXT(""), CBS_DROPDOWNLIST | CBS_HASSTRINGS | WS_CHILD | WS_OVERLAPPED | WS_VISIBLE,
20, 20, 200, 200, hDlg, NULL, NULL, NULL);
and the code that loads the combobox so it runs only once. No more problems. Also another even simp... |
73,968,547 | 74,011,263 | Slide animated text on hover | .h
class myButton : public QPushButton
{
Q_OBJECT
public:
QPropertyAnimation* anim;
struct WidgetPos { int x = 0; int y = 0; int w = 0; int h = 0; };
WidgetPos wp;
void CreateAnimation(QByteArray propertyName)
{
if (propertyName == "geometry")
{
anim = new QPrope... | I think the reason for the issue you are having is because when you are leaving the widget you set the start animation to the maximum width the button could take instead of starting it from the current width. I've implemented my own QPushButton subclass in the following way which seems to achieve the result you need. I... |
73,968,622 | 73,968,833 | How to create a runtime variable-size array efficiently in C++? | Our library has a lot of chained functions that are called thousands of times when solving an engineering problem on a mesh every time step during a simulation. In these functions, we must create arrays whose sizes are only known at runtime, depending on the application. There are three choices we have tried so far, ... |
Create a cache at startup and pre-allocate with a reasonable size.
Pass the cache to your compute function or make it part of your class if compute() is a method
Resize the cache
std::vector<double> fields;
fields.reserve( reasonable_size );
...
void compute( int n, std::vector<double>& fields ) {
fields.... |
73,968,826 | 73,968,982 | C++ constructor on unnamed object idiom? | I have a C++ class that works like the Linux "devmem" utility for embedded systems. I'll simplify and give an outline of it here:
struct DevMem
{
DevMem(off_t start, off_t end)
{
// map addresses start to end into memory with mmap
}
~DevMem()
{
// release mapped memory with munmap
... | Yep, completely valid. You create the object, use it and then the destructor kicks in. Your compiler will probably generate the same assembly in your whatever example if whateverhas a reasonable scope.
I don't know any names for this construct though. As well as I wouldn't call this an idiom.
|
73,968,947 | 73,968,961 | How to use struct declared in header file from source file c++? | I have a header file (abc.hpp) as bellow:
#include <iostream>
#include <stdio.h>
#include <vector>
using std::vector;
class ABC {
public:
struct BoxPoint {
float x;
float y;
} ;
vector<BoxPoint> getBoxPoint();
Then, in the source file (abc.cpp):
#include "abc.hpp"
vector... | the symbol BoxPoint was only known inside ABC scope, outside you have to add the ABC scope, so ABC::BoxPoint:
#include "abc.hpp"
vector<ABC::BoxPoint> ABC::getBoxPoint(){
vector<BoxPoint> boxPointsl;
BoxPoint xy = {box.x1, box.y1};
boxPointsl.push_back(xy);
return boxPointsl
}
Inside the function you can u... |
73,969,326 | 73,969,701 | Using C++20 Ranges to Avoid Loops | I was assigned a task where I need to solve a problem given several constraints. The point is to enforce the use of STL algorithms, iterators, and new c++20 functionality including things like ranges. However I've been reading on ranges for hours and I still can't figure out how I can implement the problem given all th... | If you simply want to transform every shape to an enum, all you need is:
auto colors = input | transform([](const Shapes& s){return s.size > 20 ? RED : GREEN;});
colors can then be looped through in a for-loop:
for (const auto& c : colors)
Or be made into a new vector:
std::vector<Color> colorEnums{colors.begin(), col... |
73,969,827 | 73,971,588 | How can I solve the error LNK2019: unresolved external symbol u_erroraName_58 referenced in function " public? | I am new at DCMTK and Visual Stadio .I get this error, and I don't know how to fix it. I'm using Visual Studio 2022.
This is my code:
#include <iostream>
#include "dcmtk/config/osconfig.h"
#include "dcmtk/dcmdata/dcfilefo.h"
#include "dcmtk/dcmdata/libi2d/i2d.h"
#include "dcmtk/dcmdata/libi2d/i2djpgs.h"
#include "dc... | You are probably missing some essential DCMTK libraires.
You can check those by :
1/Right Click on your project -> Properties.
2/Under "Configuration Properties" find Linker ->Input -> Additional Dependencies.
Check if you have all the necessary libraries in the right order.
You might need to add netapi32 or wsock32 or... |
73,970,426 | 73,970,682 | Using iterators but with same amount of loc? | One can loop over a list by both:
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<int> alist{1, 2, 3};
for (const auto& i : alist)
cout << i << endl;
list<int>::iterator i;
for (i = alist.begin(); i != alist.end(); i++)
cout << *i << endl;
return 0;
}
... |
Mostly I don't use iterators because of the extra line of code I have to write, list<int>::iterator i;.
You don't need to put it in an extra line. As with every for loop, you can define the iterator type inside of the parentheses, unless you'll need the value outside of the loops body.
So you can also write
for (... |
73,970,668 | 73,971,983 | FreeConsole() does not detach application from cmd | I launch my application in cmd. I compiled it by Cmake without WIN32_EXECUTABLE, so it hangs in cmd (i.e. is launched as not detached). Now I want to close the console and try to achieve this by calling FreeConsole().
This works in case I double-click the application -- the black console is flashes quickly and gets clo... | Creating a "perfect" application that can be both GUI or console is not possible on Windows.
When a .exe has its subsystem set to console, two things happen:
CreateProcess will attach it to the parents console. If the parent does not have one, a new console is created. This can only be suppressed by passing flags to C... |
73,970,778 | 73,971,415 | Giving integer values to QPushButton(s) to apply C++ logic on them in Qt | I have a switch case with condition values from 0-8. Upon each value, I give it an x and y coordinate of a 3x3 array. Then the code operates logic on the 3x3 array to get the results.
I also have 9 buttons in my Qt Designer ui (arranged in a 3x3 matrix). I want each click of the nine buttons to get a corresponding inte... | You can try this approach and use dynamic property:
static constexpr auto IndexPropertyName = "index";
void MainWidnow::SetupPB(QPushButton* b, QPoint index)
{
connect(b, &QPushButton::clicked, this, &MainWidnow::onSomeButtoPressed);
p->setProperty(IndexPropertyName, index);
}
void MainWidnow::onSomeButtoPresse... |
73,971,095 | 73,971,357 | I can't figure out how to edit the data in my array and the one time that I did it "forgot" the data after I increased the size. (C++) | I'm somewhat new to C++ I decided to work on a small project and I'm currently trying to set up something to make an array, put 5 objects into it and then increase its size and put more objects into it; however, I've run into an issue where I cannot figure out how to put data into the array
This is what I've got so far... | First of all I think you use C-style. Use STL containers (std::vector for example) instead of c arrays.
I don't know what is Token class, but in my opinion you don't need to use new in this part:
ts[0] = new Token(TT_PLUS, "+"); //add the item
|
73,971,250 | 73,971,279 | Why does an overriden template class method still get compiled? | When I create a templated class with a virtual function, and override the function in a derived class, the base function still tries to get compiled.
Here is the minimal reproducible example:
#include <iostream>
template<typename T>
class Base
{
public:
virtual void Method()
{
static_assert(false);
... | First, it needs to be compiled as user can instantiate Base<T> and directly call Method() on it. If you wanted to make it non-callable, use virtual void Method() = 0; for abstract functions.
Second, not only compiled, it's actually accessible from Derived: you can call it e.g. from Derived::Method(), as Base<int>::Meth... |
73,971,774 | 73,971,869 | Vector Pointer in C++ | I have a vector storing struct, and I pass it by address to a function. I wonder why I can only access to the elements by writing
(*v)[0].value
instead of
v[0].value
When I use struct array, and pass it to a function by address, I can simply write
v[0].value to get the value of an element. Any explanation is welc... | You're comparing a pointer to the first element of an array to a pointer to the whole vector.
Let's try to make a pointer to the whole array instead of its first element:
int a[3] = {1,2,3};
int (*ap)[3] = &a;
// int v1 = ap[0]; // error
int v2 = (*ap)[0]; // ok
Which is exactly like how a pointer to a vector behaves:... |
73,971,862 | 73,972,282 | how to take formatted input in c++? | Well i know how to do this in c, for example:
#include <stdio.h>
int main()
{
int a,b,c;
scanf("%d:%d,%d",&a,&b,&c);
printf("%d %d %d",a,b,c);
return 0;
}
But for to do this in c++? Can cin be use like scanf?
| Since input format is "%H:%M,%s" I suspect that a time is an input.
In such case there is better simpler way to do it:
std::tm t{};
while(std::cin >> std::get_time(&t, "%H:%M,%S")) {
std::cout << std::put_time(&t, "%H %M %S") << '\n';
}
https://godbolt.org/z/Y5o9cYc4G
|
73,972,679 | 73,972,811 | CMake use variables from file | I'd like to share some variables between my scripts and CMake. It would be nice to re-use bash syntax:
var1=value1
var2=value2
...
I was trying to use the solution from here as the problem is pretty much the same: https://stackoverflow.com/a/17167673/15035275 But the solution didn't work for me.
I created a file confi... | The answer you linked is not applicable to your problem - I've left a comment on that answer as well.
I don't know of a generic way apart from the regex-based solutions offered by other people in the question you linked.
I can only give you a somewhat more verbose alternative, based on this answer:
execute_process(COMM... |
73,972,993 | 73,974,718 | How i colud use template function in arguments of template function? | I'm trying to realize some abstraction with functions in c++.
I want to do template function which takes two functions as arguments:
template <class inpOutp, class decis>
bool is_part_of_triangle(inpOutp ft_take_data,
decis ft_result){
return (ft_take_data(ft_result));
... | The take_data is a template not an real function of which the address/ function pointer can be passed.
In order to get a concrete function, the template must be instantiated.
That means you need to pass something like:
take_data<TYPE OF NON-TEMPLATE FUNCTION>
Or simply
take_data<decltype(FUNCTION)>
That means you can... |
73,973,055 | 73,975,137 | Template class static string member not initialized correctly | I am trying to create a simple wrapper around glib2.0's GVariant.
I imagined to have a templated class that would be used to derive a format string of GVariant's type:
template <typename T>
struct Object
{
static const std::string format_string;
};
For now I have hard-coded basic integral types and string and dete... | With C++17, you might simply do:
template <typename... Ts>
const std::string Object<std::tuple<Ts...>>::format_string{
"(" + (Object<Ts>::format_string + ... + "") + ")"};
which solves the issue with gcc
Demo
But problems still exists for clang (even for std::vector<int>).
I suspect Static Initialization Order Fiasc... |
73,974,753 | 73,975,123 | undefined reference to 'std::filesystem' using Bazel build | trying to pull and build Visqol following the instructions provided for Linux. I downloaded Bazel, everything seems fine. But when I try to execute with bazel build :visqol -c opt i get the following errors
bazel-out/k8-opt/bin/_objs/visqol/main.o:main.cc:function main: error: undefined reference to 'std::filesystem::_... | In accordance with how to use std::filesystem on gcc 8?, change the line build --linkopt=-ldl in .bazelrc into:
build --linkopt=-lstdc++fs -ldl
You could also open a ticket in the Visgol repo and tell them about this problem and get a proper solution in the future releases of Visgol.
|
73,975,225 | 73,975,815 | Is the initializer for a const static data member considered a default member initializer? | Is the initializer for a const static data member considered a default member initializer?
The relevant wording is [class.mem.general]/10:
A brace-or-equal-initializer shall appear only in the declaration of a
data member. (For static data members, see [class.static.data]; for
non-static data members, see [class.base.... | No.
Static data members aren't initialised in constructors. f() is just the initialiser for A::I.
A default member initialiser is used to initialise a non-static data member in each constructor where the mem-initializer-list doesn't otherwise initialise that member. That is, it's a default for the initialisers of that ... |
73,975,409 | 73,981,827 | A simple threaded program: questions and doubts about detach() | Here is my threaded program, which is very simple:
#include <iostream>
#include <thread>
using namespace std;
void myprint(int a)
{
cout << a << endl;
}
int main()
{
thread obj(myprint, 3);
obj.detach();
cout << "end!!!" << endl;
}
What I can't understand is that the program occasionally has sub-thr... | Aha,this morning I had a stroke of genius and solve the problem successfully. You just need to test the cpu time that join() and detach() executed, you will get the answers.
I think @Someprogrammerdude is right, it's just that the join takes longer to execute, so the problem of duplicate output only occurs in detach()
|
73,975,615 | 73,975,665 | Difference in queue sizes giving arbitrarily large value C++ | #include <iostream>
#include <queue>
using namespace std;
int main()
{
// cout<<"Hello World";
priority_queue<int> spq; // max heap
priority_queue <int, vector<int>, greater<int>> lpq; // min heap
spq.push(1);
lpq.push(2);
lpq.push(3);
cout << spq.size() - lpq.si... | You have unsigned integer wrap-around.
spq.size() is 1, lpq.size() is 2.
So when you do 1 - 2, since you're using unsigned numbers, you don't end up in the negatives, you instead wrap around to the largest unsigned number you have, 18446744073709551615.
|
73,975,788 | 73,976,575 | C++/rapidjson - unable to iterate over array of objects | I have the following json:
{
"data": {
"10": {
"id": 11,
"accountId": 11,
"productId": 2,
"variantId": 0,
"paymentMethod": "PayPal",
"amount": "9.99",
"status": "confirmed",
"created_at": "2019-12-02T21:55:30.000... | iterator->name refers to the bit before the : in the json, to get at the other side you need iterator->value.
for ( auto & data : parsed_response[ "data" ].GetObject() )
{
std::cout << data.name.GetString()
<< data.value["accountId"].GetString()
<< data.value["productId"].GetString()
... |
73,976,001 | 73,977,954 | g++ undefined reference to while linking with a custom shared library | I am trying to link my C++ program with a custom shared library. The shared library is written in C, however, I don't think that it should matter. My library is called libfoo.so. Its full path is /home/xyz/customlib/libfoo.so. I've also added /home/xyz/customlib to my LD_LIBRARY_PATH so ld should be able to find it. Wh... | As indicated by the comments in the post, it turns out that I was missing the extern "C" in the header file. So in my code, I wrapped my include statement in an extern "C" which solved the issue.
TLDR: The header include in the code should look like:
extern "C" // Import C style functions
{
#include <foo.... |
73,976,245 | 73,976,378 | What are the use-cases of "complete-class context"? What's the benefit that a "complete-class context" provides? | In current working draft, the definition of complete-class context is: (§ 11.4.1 [class.mem.general]/7):
A complete-class context of a class (template) is a
(7.1) function body ([dcl.fct.def.general]),
(7.2) default argument ([dcl.fct.default]),
(7.3) default template argument ([temp.param]),
(7.4) noexcept-specifier... | If we did not have a complete-class context then we could not write a class like
struct foo
{
void bar() { std::cout << kitty; }
std::string kitty = "meow";
};
because kitty isn't known about until after bar is defined. You would have to write the class like
struct foo
{
void bar();
std::string kitty ... |
73,976,312 | 73,988,791 | open62541 client fails when calling method with custom datatype input argument | I'm using open62541 to connect to an OPC/UA server and I'm trying to call methods that a certain object on that server provides. Those methods have custom types as input arguments; for example, the following method takes a structure of three booleans:
<opc:Method SymbolicName="SetStatusMethodType" ModellingRule="Ma... | The problem is the typeId of the encoded object. For the server in order to understand the received data, it needs to know the NodeId of the encoding, not the actual NodeId of the type itself. That encoding can be found by following the HasEncoding reference (named "Default Binary") of the type:
auto pRequest =... |
73,976,552 | 73,977,235 | Sort a c++ list and remove all duplicate strings | #include <cstdlib>
#include <fstream>
#include <iostream>
#include <iterator>
#include <list>
#include <string>
using namespace std;
istream& GetLines(istream& is, list<string>& list) {
string str;
if (list.size() > 0) {
list.clear();
}
while (getline(is, str, is.widen('\n'))) {
list.p... | The proper way to solve this is as suggested to read the documentation about the container you are using and in std::list Operations, you'll find this list:
Public member function
Description
merge
merges two sorted lists
splice
moves elements from another list
removeremove_if
removes elements satisfying sp... |
73,976,779 | 73,977,676 | Trying to use copy and swap idiom on operator= | While trying to implement MyVector I end up with:
#include <iostream>
#include <string>
using namespace std;
template <typename T>
class MyVector
{
int m_size = 0;
int m_capacity = 0;
T* m_data = nullptr;
public:
MyVector()
{
cout << "defautl ctor" << endl;
realloc(2);
}
... | As stated in comments, you did not implement a swap() function for MyVector, so the statement swap(*this, copy); is calling std::swap() (one of the many pitfalls of using using namespace std;), which will invoke your operator= again, hence the recursive behavior you are seeing.
Also, your copy constructor is not implem... |
73,976,814 | 73,988,934 | converting (roughly) the current time into a 32 bit integer | I just need a way to roughly convert current time into a 32 bit integer. It doesn't need to be very accurate.. even accuracy of only a couple minutes would be ok.
The main idea is the next time I need to check it, it should be higher than or at least not lower than the previous time I retrieved this value. (I don't che... |
I use C++ 20 (the MSVC version of it, whatever comes with VS 2022)
Excellent. This means that you have very good tools to work with in the chrono department.
Because of your requirements, there are only a few solutions I would consider acceptable.
You should not deal in local time as it jumps around too much due to... |
73,977,225 | 74,234,480 | vs code c++: unable to establish a connection to GDB | I'm trying to set up a OpenGL environment in vs code, I'm using MinGW64 with msys for compilation and package management, I wrote a tasks and launch json files for generating builds, but when I run the build that was generated I get an error stating "unable to establish connection to GDB" and my app aborts.
this is my ... | No clue what the problem was, but I ended up reinstalling everything (msys, mingw, g++, gdb etc....) and the issue was fixed
|
73,977,688 | 73,980,929 | Unreal Engine 5.0.3 ERROR: Could not find NetFxSDK install dir | I was trying to create a new C++ Unreal Engine project, but every time I do it (Only with C++), I get a popping window that says:
Running C:/Program Files/Epic Games/UE_5.0/Engine/Binaries/DotNET/UnrealBuildTool/UnrealBuildTool.exe -projectfiles -project="C:/Users/user/Documents/Unreal Projects/MyProject/MyProject.upr... | I had this same problem earlier today.
From Visual Studio Installer you can install .NET Framework SDK 4.6.0
Main GUI for Visual Studio Install
From here click on the modify button to add features and functionally.
Modifying VS Installer Screen
Then you just need to check the box for the .NET Framework and follow the i... |
73,977,781 | 73,978,670 | Finding nearest "ancestor" in tree of types | I am forming a "tree" of types in the following way:
template <typename T, typename PARENT, typename ... CHILDREN>
class Node {};
class X;
class A;
class AA;
class AB;
class B;
class BA;
class BB;
class X : public Node<X, void, A, B> {};
class A : public Node<A, X, AA, AB> {};
class AA : public Node<AA, A> {};
class... | I think I figured it out.
Assuming the Node base class has the following:
template <typename T, typename PARENT, typename ... CHILDREN>
class Node {
using parent_type = PARENT;
};
Then nearest_ancestor can be defined as:
template <typename T, typename U, typename ENABLE = void>
struct nearest_ancestor {
using ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.