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 |
|---|---|---|---|---|
64,642,769 | 64,643,040 | nonzero Reduced cost: Is lower or upper bound active? | Reduced cost give the dual variable corresponding to a box constraint of a variable as was pointed out in the related answer to this question: LP: postive reduced costs corresponding to positive variables?
How do I know whether the lower or upper bound is the active constraint? Of course, I could check whether the diff... | To a large extent you can look at the sign. The rule for reduced costs is:
Basic Non-basic-at-LB Non-basic-at-UB
minimization 0 >= 0 <= 0
maximization 0 <= 0 >= 0
Some problems with this:
Not all solvers may follow this (especially whe... |
64,642,996 | 64,643,239 | How to get a byte array in c/c++ from a function with unknown return type? | For example, I know the address of the function (lets say its 0x0183ad0), and I would like to get an object from that function which returns an unknown type:
unknownType(*fname)() = (unknownType(*)())0x0183ad0
Is there any global type I can replace unknownType with or any method to get that object as a byte array (I k... | "byte array" would be uint8_t* or unsigned char*.
If you know the size of unknownType I would create a
struct unknownType {
uint8_t stuff[123];
};
so you can adapt the struct definition as you gain better understanding of its fields.
|
64,643,002 | 70,710,726 | Primality test. Is this program performing faster than all others? | bool is_prime(BigInt num)
{
if(num == 0 || num == 1 || (num != 2 && num % 2 == 0))
return false;
BigInt sq = sqrt(num);
for(BigInt i = 3; i <= sq; i += 2)
if(num % i == 0)
return false;
return true;
}
We only need to check upto square root.
Proof -> ht... | Your code is doing so called Trial Division primality test, which is slow for big numbers. It has time complexity O(Sqrt(N)) of primitive operations.
If you have really big numbers, 1024 bits or bigger then Trial Division will be a way too slow.
There are two kinds of Primality Tests - deterministic and probabilistic. ... |
64,643,082 | 64,643,770 | is there a better implementation to deal switches? | I had a class type named reply, its form like this:
class reply {
public:
enum class type {
error = 0,
bulk_string = 1,
simple_string = 2,
null = 3,
integer = 4,
array = 5
};
public:
type get_type(void) const {
return type_;
}
private:
type typ... | Design at least "central points" as possible. Concentrate on making it easy to add new reply types, the design will flow from that assumption. Create separated parts associated with each reply with a single one central point that choose the handler. The central point is called a factory and small parts implement the sa... |
64,643,201 | 64,643,565 | Fastest algorithm for finding two array elements that sum to x | Announcement of the exercise: https://cses.fi/problemset/task/1640/
I would like to understand why one algorithm is much faster than another (about 25 times) when I think they have the same complexity O(n log n) but the fastest one should in principle loop 1 more time on my list so I would have really thought it slower... | Note that big-O complexity purposefully ignores constant factors as well as architecture-specific details like branch prediction and caching. The work for the first is N + N * (log_2(N) + log_2(N)) (constructing the vector + two map accesses per element), while the second is N + N * (log_2(N) + 1) (constructing the vec... |
64,643,245 | 64,643,428 | Open a new terminal screen in C ++ | First of all, I have to say that I do not know English exactly. I am improving my English but I am not at a sufficient level yet. Please excuse me for my misspelling and write your answers in the simplest way.
My problem is that I want to run another program made in C ++ when the "1" key is pressed. The files are in th... | If you want to make cross-platform for your application, use system with predefined operating system macros.
For example:
#ifdef __FreeBSD__
system("Terminal application object is here");
#endif
#ifdef _WIN64
system("Terminal application object is here");
#endif
|
64,643,650 | 64,803,593 | MinGW cc1plus.exe and collect2.exe "can't start the application correctly (0xc0210000). click OK to close the application" | I recently installed MinGW64 through MSYS2 and I added it to path to test it in cmd, I created a simple .cpp script and tried to compile it with the g++ 1.cpp -o 1.exe command, but I get 2 error windows:
I tried using other commands too, like c++ instead of g++, but I get the same result, this is the code I'm trying ... | I found a solution, the reason why I was getting those errors was that I was using bitlocker on one of my drives, it didn't even contain files that were being used by the compiler (the program and mingw where all in a different drive) but removing bitlocker on my drive solved the problem
|
64,643,701 | 64,643,987 | How to run without vectors with c++ | Is there a way to execute this code without using vectors?
Can this program be run without vectors in the polygon class?
If possible, how should I modify the code?
And is it right to write the copy constructor and the move constructor as it is now?
It's so hard to do C++ while playing Python. Help me.
Thank you.
Polygo... | Your code is using vector exactly like a C style array, so you can replace it with such an array with minimum changes.
In fact, it will make your code simpler to read, since you will not be misusing a C++ object like a C variable.
class Polygon {
int point;
C2D *arr;
public:
Polygon(int point_, C2D arr_[])... |
64,644,006 | 64,713,064 | How to pass an IUIAutomationElement between threads | I am writing a Node.js native Addon in C++ (using node-addon-api) to interact with Microsofts UIAutomation API. I am trying to listen to Focus Events, wrap the IUIAutomationElement which caused the event and pass the wrapped element to javascript.
I can attach an Event Listener (following this example for Handling Focu... | In order for instances from the IUIAutomation API to be passed across threads you need to keep a strong reference. IUIAutomationElement is based off IUnknown so this can be done using IUnknown::AddRef (https://learn.microsoft.com/en-us/windows/win32/api/unknwn/nf-unknwn-iunknown-addref).
This adds a reference to the re... |
64,644,209 | 64,645,303 | VC++ 2015 error: "an expression involving objects with internal linkage cannot be used as a non-type argument" | The following sample code does compiles in VC++ 2019, clang++ and g++ but not VC++ 2015.
namespace ns
{
template<const char* str>
struct Foo
{
};
static const char name[] = "Test";
Foo<name> foo;
}
int main()
{
}
Are there any workarounds for VC++ 2015? I'm assuming the code is conforming... | MSVC 2015 doesn't fully support C++11, and non-type template arguments with internal linkage is an example of a C++11 feature which VC++ didn't support until version 14.14 (VS 2017 15.8).
I can think of 3 solutions:
Don't use template arguments with internal linkage by removing static const specifiers from char name[]... |
64,644,776 | 64,648,093 | How to use struct vector as an input parameter in Rcpp | I need to supply a vector of structs to an Rcpp function. The cpp file is as below
#include <Rcpp.h>
using namespace Rcpp;
struct teststc{
int y;
};
// [[Rcpp::export]]
void teststruct(std::vector<teststc> ys){
Rcpp::Rcout <<"test"<<std::endl;
}
When I compile this cpp file, it returns this error
error: no m... | The problem is that you are trying to export a function to R that takes as an argument an object of type std::vector<teststc>. Such an object does not exist in R, so it cannot pass it to the C++ code.
If you want to be able to pass an object to C++ from R and convert it into your own struct, then you must write the C++... |
64,645,090 | 64,667,609 | c++ file handling, reading within a file | Good day, I am struggling to read a file from a .txt document, any help would be appreciated.
The code is almost done, it runs without errors, but it wont read the file where the data is stored.
the data is stored under the document: idnumbers.txt
the code:
using namespace std;
int year;
int read(char*);
void display(c... | Since you want a c++, I give the following typical c++ code for your reference.
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string str;
int year;
char schar str2[3]={}, month[3]={}, day[3]={};
std::ifstream file("idnumbers.txt");
while ( std::getline(file, str) )
... |
64,645,340 | 64,645,576 | Shared memory safty, could you read and write at the same time and what would happen? | I am using the sys/shm library to share memory between two applications.
It works well and as I want it to, however I am unsure of the library is entirely safe in the way I currently have it implemented.
What would happen if a value is changed at the same time the other application tries to read it. Could this even hap... | It is not safe.
I mean if you put your write code in a loop and the run the send code,the read code may be executed after the first write and before the last write.
It according the thread scheduler.
But your data in share memory are integer values. It can be write and read in one instruction,so the value your read fro... |
64,646,194 | 64,646,308 | Cannot find lpublic library | Trying to compile my project on Centos 8.2 using cmake 3.12, im facing with the following error:
cannot find -lpublic
here is full log:
[ 20%] Building CXX object CMakeFiles/ .cpp.o
[ 40%] Building CXX object CMakeFiles/ .cpp.o
[ 60%] Linking CXX shared library .so
[ 60%] Built target myproj
Scanning dependencies of... | That seems like you try to link against the target "public", which is a suspicious target name. It might be target_link_libraries command with lowercase public instead of uppercase one, like target_link_libraryies(nist01 public something) instead of target_link_libraries(nist01 PUBLIC something).
|
64,646,227 | 64,646,379 | Too few arguments to function 'int fclose(FILE*)' | Hello I am a beginner of C language for microprocessors. I want to read a ''.bmp'' file in order to apply line detection on it. I have declared a function to read the image. This error occurs when compile button is pushed:
#include "esp_camera.h"
#include "Arduino.h"
#include "FS.h" // SD Card ESP32
#inc... | The fclose() function needs to know which file to close. You need to tell it that by supplying "file" as an argument. You want to use fclose(file).
|
64,646,372 | 64,646,484 | C++ Map send pointer element as parameter | I need to print the array from nodes in a list that I made for a heuristic search algorithm.
For the list, I have a C++ map std::map<int, Node>List
WHERE Node is a structure that looks like:
struct Node{
Node *pParent;
int array[3][3]; };
I can successfully insert the Node "n" to the list like this:
List.inse... | std::map<int, Node> p = List.begin(); doesn't work because begin() returns an iterator but you've declared p to have type std::map.
You want:
std::map<int, Node>::iterator p = List.begin();
Or simply use auto to not have to care about the type:
auto p = List.begin();
|
64,646,443 | 64,646,544 | How to get all mousemove events while main thread is busy Windows MFC C++ | I have a long CPU operation on a mousemove event. It seems like no new mousemove events are sent to my application during that time, making for big jumps in mouse position.
I thought mouseevents would build up in a queue and then all get sent to my app, but this does not seem to be the case.
I would like as high resolu... | You have a few options:
As you mentioned, put your processing in a worker thread and let Windows messages pump in your main thread. This is probably the most conventional method, the most logical design.
Use GetCursorPos and GetAsyncKeyState to get mouse state whenever you want it, without depending on the Windows mes... |
64,646,672 | 64,646,763 | Do pointer arithmetic expressions count as instructions? | I have written a program that flips the elements of an array that are next to each other. for example
1, 2, 1, 2 becomes 2, 1, 2, 1
The code I wrote is:
#include <iostream>
template <class T>
void swap(T& a, T& b){
T temp = a;
a = b;
b = temp;
}
template <class T>
void oReverse(T* p, int size){
for(T*... | Firstly, *p++ increments p after the value is fetched. So instead of
swap(*p, *p++);
you would like to do this:
swap(*p, *++p);
But this will not work either. The standard does not define in which order the arguments to a function should be evaluated. So instead of
swap(*p, *++p);
write
swap(*p, *(p+1));
p++;
and y... |
64,646,938 | 64,647,492 | How to obtain the libasan.so path with Cmake? | I have a shared library in which the tests for a project are located. This is using Cgreen as a test framework. This allows one to run all the tests using the cgreen runner as this:
cgreen-runner my-tests.so
I can do this from CMake pretty easy:
add_test(NAME mytest COMMAND ${CGREEN_EXECUTABLE} ${CMAKE_LIBRARY_OUTPUT_... | You can simply call the command from CMake:
execute_process(COMMAND gcc -print-file-name=libasan.so
OUTPUT_VARIABLE LIBASAN_PATH
OUTPUT_STRIP_TRAILING_WHITESPACE)
To catch failures you can pass a RESULT_VARIABLE and check if its value is equal to 0.
|
64,647,286 | 64,647,784 | Is there a clever way of avoiding extra padding with nested classes in C++? | These structs, align1 and align2, contain the same data, but align1 has more padding due to the nested layout.
How can I get the memory saving alignment of align2 while also using a nested struct like in align1?
int main() {
struct align1 {
struct {
double d; // 8 bytes
bool b1; ... | I explicitly rely on the permission to propose code which is "dirty or bad looking as" ... anything. To be even more clear, I only provide an idea. You need to test yourself and take responsibility yourself. I consider this question to explicitly allow untested code.
With this code:
typedef union
{
struct
{
... |
64,647,304 | 64,649,098 | C++ Array to a number | I have no idea how to write a code which would take numbers from the array and equal them to an integer number without 0.
For example, I have an array A[size]= {12,68,45,20,10} and I need to get the answer as n= 12684521. Any ideas or hints how to make it?
| It is possible to do it without using strings or stringstreams. Here's the code:
int integer(int* arr, size_t length)
{
int result = 0;
for (size_t i = 0; i < length; i++)
{
int t1 = arr[i], t2 = 0;
while (t1 != 0)
{
if(t1 % 10 != 0)
{
t2 *= 10... |
64,647,328 | 64,648,127 | Deleting a specific key from a file using file I/O in C++ | string _delete_an_apiKey(int n)
{
string a;
string del;
int cnt = 0;
ofstream f1("tempAPIKeys.dat",ios::app); // Temporary file for executing deletion
ifstream f2(file,ios::in); // Main file containing all the keys
while(!f2.eof())
{
if(cnt != n)
{
... | The reason you see last key twice is because the iostream::eof is raised after reading the end of the stream, it does not mean that the next read will be end of file.
Use inputStream >> data in the while loop, which guarantee entering the loop if the read was successful, like:
while(f2 >> a)
{
if(cnt != n)
{
... |
64,647,661 | 64,648,148 | GCC 10.2 not accepting an lambda empty lambda as a constexpr std::function<void()> | I was playing around with constexpr when I found that GCC rejected this seemingly valid code:
#include <functional>
constexpr void test(const std::function<void()>& a) {
a();
}
int main() {
test([](){});
}
I went to godbolt, and clang happens to compile this code fine. Is this a bug in GCC? Here is the g... | As already mentioned in the comments, std::function itself can not be used in constexpr environemt, because the operator()() and also the constructor of std::function is not constexpr.
As this you can use directly a pointer to function, if you have capture less lambdas or you can templatize you function like this in C+... |
64,647,734 | 64,649,979 | Error setting up unordered_map with non copying-able type with gcc 8.4 | See here: https://godbolt.org/z/MW3jW6
Using gcc 8.4 (8.3 in godbolt) my code is failing to compile. With gcc 10.x it seems to compile ok. But I can't figure out what the error is telling me exactly...
Here is the code for reference:
#include <mutex>
#include <condition_variable>
#include <iostream>
#include <unordered... | Your copy constructor (with const), even if legal is unusual, and appears to be problematic.
Use regular one:
non_copy(const non_copy&) = delete;
|
64,648,038 | 64,667,279 | QML TableView Model Silently Failing? | edit: added some clarification
Using QML 5.14
It seems the model attribute of TableView does not want to display a QList<int>, or any variation of int, be it qint8, qint32, etc. I can make it work with unsigned QList<uint>, however I need to keep the negative range of values in my application.
I've found that the infor... | QList<int> is not one of the official supported C++ types used for models (see the list here). A bug report exists to clarify the documentation on that point. A QVariantList is a good alternative to use.
|
64,648,111 | 64,648,793 | how can I pass a parameter to the system function with quotes? | I'm trying to reduce columns of top funcion and save it into a file but I don't know how do it using system() function with quotes. I'm doing it like this:
system("top -b n1 | grep \"^ \" | awk '{ printf(\"%s %s %s %s %s %s %s\n\", $1, $2, $8, $3, $9, $10, $12); }' >> file
I'm pretty sure the problem is with the ... | The problem is not with your quotes. First, you are missing a closing "), and I'm not sure how you are trying to use the variable file but it looks like you are mixing up strings with variables. Make sure that the variable file is indeed used as a variable when you add it to your command string. Lastly, you are escapi... |
64,648,186 | 64,769,390 | Using a Data Converter to Display 3D Volume as Images | I would like to write a data converter tool. I need analyze the bitstream in a file to display the 2D cross-sections of a 3D volume.
The dataset I am trying to view can be found here: https://figshare.com/articles/SSOCT_test_dataset_for_OCTproZ/12356705.
It's the file titled: burned_wood_with_tape_1664x512x256_12bit.ra... | Down below I implemented next visualization.
Example RAW file burned_wood_with_tape_1664x512x256_12bit.raw consists of 1664 samples per A-scan, 512 A-scans per B-scan, 16 B-scans per buffer, 16 buffers per volume, and 2 volumes in this file, each sample is encoded as 2-bytes unsigned integer in little endian order, onl... |
64,648,426 | 64,648,989 | What would be an example where std::bit_cast produces a value representation of multiple values? | The following is a quote from the standard (draft n4861) under [bit.cast] (emphasizes are mine)
Returns: An object of type To. Implicitly creates objects nested within the result (6.7.2). Each bit of the value representation of the result is equal to the corresponding bit in the object representation of from. Padding ... | Sum types come to mind. A union can have members of the same type:
union u {
int a;
int b;
};
Now, if we bit-cast something into a u, what sort of u do we get? Is it one where a is active or b? Those are formally different values of a u, but they would seem to have the same value representation.
|
64,649,801 | 64,650,025 | c++ vector<Book*> title being a string | I'm doing an university project on a library.
The class Book is used on data so I thought of creating a vector with pointers to the objects Book's. The problem is, I need to read an input file with the data and then create a Book to add to the vector<Book*> catalog.
Whenever I do so, the getline() with integers works f... | while(!books_file.eof()) {
Book book; <--------- stack allocated variable
std::getline(books_file, input);
if(books_file.eof()) break;
book.setTitle(input);
std::getline(books_file, input);
book.setBookId(std::stoi(input));
std::getline(books_file, input);
book.setOwner(std::stoi(input))... |
64,649,981 | 64,650,253 | How to sort and print numbers on separate lines with 3 decimal precision? | The program asks user to enter numbers and stores the numbers in the vector. The program stops asking numbers when user enter a negative number. The negative number is not stored the vector.
When program has finished asking numbers it sorts the numbers. After sorting the
program prints the numbers on separate lines wit... | The negative number is not being stored in the vector. It is explicitly being printed out by
cout << fixed << setprecision(3) << values << " " << endl;
because if a negative number, rather than in input error, exited while (cin >> values), values will be that negative number.
Instead use
#include <iostream>
#include <... |
64,650,328 | 64,651,522 | C equivalent of C++ enum data for binary reading and manipulating | trying to convert some C++ code into C, I'm working with binary data and need to use a C equivalent of this:
enum GssipFlags : uint16_t
{
SPARE0 = 1,
SPARE1 = 2 * SPARE0,
SPARE2 = 2 * SPARE1,
SPARE3 = 2 * SPARE2,
REQ_MSG = 2 * SPARE3,
DISCONNECT = 2... | You have one standard option and two potential options depending on your compiler and what "I'm working with binary data and need to use a C" means (memory usage?, speed?, etc):
This has been already commented, the use of structs with the type you are looking for:
typedef struct {
uint16_t SPARE0;
...
} Gssip... |
64,650,841 | 64,650,900 | How to return a lambda function containing a function capture? (C++) | I am new to this Lambda function in C++. I wanted to return a lambda function containing a function capture like this:
#include<bits/stdc++.h>
//typedef void(*func1)();
auto func(void(*func2)())
{
return [&func2](){cout<<"hello world 1"<<endl;func2();};
}
void func2()
{
cout<<"hello world 2"<<endl;
}
int m... | The lambda that you return from func:
return [&func2]() {
// ...
};
is capturing func2 by reference. Since func2 is local to func, this reference is dangling when you return from func. So in main, you get undefined behavior when func2 is called in the body of the lambda.
You can fix this by making the lambda capture... |
64,650,981 | 64,651,285 | Call to implicitly deleted copy constructor of class error | I have a class that has a member of type std::thread, however, when I want to use this class as a member of another class I always get the error that the constructor of the other class was implicitly deleted because std::thread constructor is deleted.
My class with the std::thread member looks as follows:
class VideoS... | The syntax
RemoteCom com = RemoteCom();
requires a copy constructor to exist and to be accessible. This is true even if optimization would eliminate the call to the copy constructor.
Replace with
RemoteCom com;
which uses the default constructor directly.
|
64,651,782 | 64,667,246 | How to draw on QGraphicScene in real time? | i'm having trouble with making app like Windows Paint. I wanted to draw on my window while holding mouse button. I know there's MouseMoveEvent but it has really poor refresh rate for me. Because of that i wanted to create my own event. I tried some options and as for now i have something like that:
DrawArea::DrawArea(Q... | If anyone will have trouble with something similar, here's my implementation:
DrawArea::DrawArea(QObject *parent) : QGraphicsScene(parent), mRadius(2), mDrawPath{}
{
drawing = false; // drawing is boolean type attribute
}
void DrawArea::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if(event->button() & Qt... |
64,652,024 | 64,669,056 | C++ SFINAE constructor accepting derived class too | Primer: C++ base class constructor taking derived class as argument (?)
I have a Vector and a Vector2D class. The former should contain a constructor that allows element-wise type casting. It should be allowed for the derived class too. For some cases, it already works, (see examples below) but i think some SFINAE magi... | @Jarod42 pointed me in the right direction
What i need is && instead of || for the two arguments. However, std::is_base_of is not really enforcing what i want. I replaced it with std::is_same to check if all the arguments supplied by ...TArgs are actually of the same type as the one that the Vector already holds, T.
No... |
64,652,113 | 64,652,387 | C++ replace function | I am trying to use the replace function to replace uppercase letters with lowercase ones. The way I was trying to do it was that when the letter being checked is between ASCII values 65-90, it would be replaced with the character that is 32 ASCII values higher, for example, 65 would be turned to 97 (A to a).
char holde... | I think you are looking for
jumbledPhrase.replace(count, 1, 1, holder);
which is replace 1 (the first 1) character at position count in string jumbledPhrase with 1 copy (the second 1) of the character holder.
Reference here, if actually you were looking for something else
|
64,652,555 | 64,652,776 | how to iterate one time over a loop each time call a function? | I have loop and want to iterate one time each time I call the function.
This is my code:
#include <iostream>
void iter(int max_i, int max_j){
static int i = 0;
static int j = 0;
for (; i< max_i; i++ ){
for(; i<max_j; j++){
std::cout << i << " " << j << s... | From your code, it should be
void iter(int max_i, int max_j){
static int i = 0;
static int j = 0;
if (i < max_i)
{
std::cout << i << " " << j << std::endl;
if (++j >= max_j) {
++i;
j = 0;
}
}
}
Demo
Better to have all those variables in class to avoi... |
64,652,565 | 64,652,790 | Issue with converting a filesystem path to a const BYTE* | What I'm trying to achieve is getting my program executed on Windows startup using the Registry. When I try to put the file location, the compiler complains it cannot convert from filesystem::path to const BYTE*. I have no idea how to fix this, since I'm a beginner when it comes to C++. I have provided the code below:
... | Per the RegSetValueExA() documentation, the function does not accept a std::filesystem::path object. That is what the error message is complaining about.
LSTATUS RegSetValueExA(
HKEY hKey,
LPCSTR lpValueName,
DWORD Reserved,
DWORD dwType,
const BYTE *lpData, // <-- here
DWORD cbDa... |
64,653,248 | 64,653,352 | Strange behaviour of linked list with struct | Basically I created a linked list with struct and a function to add new node to the beginning.
I added 4 nodes to the linked list and read it with a for loop. But the out put is strange
#include <iostream>
using namespace std;
struct Lin{
int val;
Lin* nex;
};
Lin ext (Lin orig, int nod) {
Lin fresh = {no... |
x is stored on the stack, and is not initialized, so x.nex is garbage (and not even NULL).
fresh is stored on the stack, too. It is initialized but unfortunately, orig is stored on the stack as well, and both live only during the call. ext returns a copy of `fresh.
The code looks like you’re more familiar with langua... |
64,653,322 | 64,653,446 | Attempting to access data in second portion of a map of maps C++ | I am sorry if this has been asked before (It seems as though every question has been asked before but with the plethora of questions asked on stack overflow it is sometimes hard to find). I have created a map of maps and am attempting to access the data in the second map. However, this is giving me issues in that I a... | I'm a bit confused why you commented out the second loop. I mean it's wrong but surely you realise that you can't iterate through a map of maps with only one loop?
Here's the code corrected
for (std::map<std::string, std::map<int, int>>::iterator iter = wordMap.begin();
iter != wordMap.end();
iter++)
{
... |
64,653,337 | 64,671,555 | my first conan package not getting found by CMAKE? | I have seemingly successfully built my first local conan package and uploaded it to my local artifactory.. I can also add it by full name in the dependencies of other projects like so..
[requires]
thrift/0.13.0
mypkg/0.0.1@user/channel
[generators]
cmake
I can link it without error likeso in my OtherProject CMakeList... | The right process to debug this kind of problems is the following:
Check the generated conanbuildinfo.cmake file, it will contain variables like CONAN_INCLUDE_DIRS pointing to folders in the Conan cache, that should contain the expected headers.
If you cannot identify the variables in the conanbuildinfo.cmake that bel... |
64,653,457 | 64,653,903 | gmock: How do I pass a pointer of a mock class into another class? | I have to test the following classes with gmock and since I'm pretty new to Gmock Testing in general, I have no idea, where I'm getting these errors from. So I have my Model class in the Model.hpp, which looks like this:
class Model {
public:
Model(double delta_t) : Delta_t(delta_t){};
void add_submodel(std::uniq... | The add_submodel function takes its std::unique_ptr<Submodel> parameter by value. When you call model.add_subproblem(mock1_ptr);, this would result in mock1_ptr being copied. However, unique_ptr is not copyable.
To fix this, you can remove the variable and directly pass the temporary, as in model.add_subproblem(std::ma... |
64,653,998 | 64,654,109 | Reaching nullptr crashes program - Binary Search Tree | I wonder if there is any way (I think there is) to avoid program crash when while loop is reaching nullptr? I did method that passes to string values from Binary Search Tree, but the problem occures when there is no right or left child of parent. My method:
string to_string()
{
stringstream ss;
Node<T>* tmp = r... | When your ss << ... statement reaches a leaf Node* whose left_child and/or right_child are null, it tries to access data that is invalid. You are not handling that condition, hence the crash, and why removing the data access makes the code work.
Try this instead:
ss << "Data: " << tmp->data;
if (tmp->left_child != NULL... |
64,654,756 | 64,655,269 | Difference between Qt::QueuedConnection and Qt::DirectConnection when connecting a signal to a lambda | Let's consider a scenario of two QObjects, senderObject of type SenderObject and receiverObject of type ReceiverObject. senderObject has been created on a worker thread while receiverObject has been created on the main thread. Now let's asssume SenderObject has a signal somethingsChanged and let's consider the followin... | Here's our class SenderObject:
class Sender : public QObject {
Q_OBJECT
public:
explicit Sender() : QObject() {
_timer.setInterval(1000);
connect(&_timer, &QTimer::timeout, this,
[this] { emit somethingsChanged(); });
_timer.start();
}
signals:
void somethingsChanged();
private:
Q... |
64,654,827 | 64,655,032 | C++20 non-type template parameter which is template in the prior type parameters: is not a valid template arg, because is not a variable | I've been stumped on this for a while, and distilled a simple example of my error message. Is there some way to make this work? Am I just missing a "template" or "typename" somewhere?
#include <cstdint>
template<typename T, typename J>
struct silly
{
const void (*f)(T,J);
};
template<typename T, typename J, silly... | Edit:
The third template parameter of sillier is a non-type template argument, which can only be bound to a variable, but dumb_func is not a variable.
This explanation doesn't make sense, and in fact the code is probably fine, and the error might just be a bug as discovered and reported in this answer. The fix given be... |
64,655,205 | 64,659,674 | Using boost::filesystem, how can I prevent overwriting of previous password files? | Alright, I'm fairly new to C++ and coding in general. I'm working on a password generator, that randomly generates a number between 33 and 126, then uses the corresponding ASCII code and creates a password of user-specified length. And then I want to use boost::filesystem to create a passwords folder, and in that folde... | Boost.Filesystem offers an operation called exists, along with other operations for querying status of a file. You could generate the file name using a loop like below:
fs::path generate_filename(fs::path const& dir)
{
fs::path path = dir / "password.txt";
unsigned int counter = 1u;
while (true)
{
... |
64,655,385 | 64,655,406 | Can I avoid explicitly writing out my class-template parameter-type during template instantiation? | I wrote a little templated RAII-class called SaveGuard whose constructor makes a copy of the current state of a specified object, and then later on the destructor restores the object from that saved state. That way I can make temporary changes to an object and I am guaranteed that they will be auto-reverted at the end... | In C++17, you can use class template argument deduction. This requires you to completely omit the template argument list:
SaveGuard guard(myStr); // OK - deduces T as std::string
Before C++17, class template arguments cannot be deduced, so a helper function had to be used instead (std::make_pair is an example of this... |
64,655,447 | 64,655,596 | How to sort char array alphabetically without "sort" function? | I am trying to create a program that passes a predefined char array to a function that sorts the array alphabetically. I just don't know where to start, I need a function that sorts an array with the c++ sort function.
| If you are trying to do it without std::sort, then there are a few different sorting algorithms that you could implement. Here is an example with bubble sort:
#include <iostream>
void sort(char* arr, int sz)
{
for (int i = 1; i < sz; i++)
{
for (int j = 0; j < sz-i; j++)
{
if (arr[j] > arr[j+1])
... |
64,655,591 | 64,655,630 | In C++ .is triangle area showing zero??? why? | The area of triangle is showing zero in the output, why is that??
What have i done wrong??
#include <iostream>
using namespace std;
int main() {
int Base, Height, Area;
// >>> Is anything wrong with the formula??
Area = (0.5) * Height * Base;
cout << "To find the Area of Triangle" << endl << endl;
// Base... | When you have a computed value you must compute it with any changes made to the values involved. Unlike algebra where x = y * 2 means "x is by definition y times two", in C++ it means "assign to x the value of y times 2 as it is right now" and has no bearing on the future.
For something calculated you use a function:
i... |
64,655,841 | 64,655,897 | Why do the constructor of the derived classes want to initialize the virtual base class in C++? | My understanding, for instance reading this, is that the constructor of a derived class does not call its virtual base class' constructor.
Here is a simple example I made:
class A {
protected:
A(int foo) {}
};
class B: public virtual A {
protected:
B() {}
};
class C: public virtual A {
pro... | The constructor of virtual base is constructed. It is constructed conditionally. That is, the constructor of the most derived class calls the constructor of the virtual base. If - this is the condition - the derived class with virtual base is not the concrete class of the constructed object, then it will not construct ... |
64,655,958 | 64,664,165 | Can a class containing a function pointer be used as a non-type template parameter? | Consider the following class S containing a function pointer, and a constexpr object s of that class initialized with a lambda:
struct S
{
void (*f) ();
};
constexpr S s { []{} };
Now if I write a template X with a non-type template parameter of type S, and instantiate it over s like this:
template<S> struct X... | The code is valid.
[temp.arg.nontype]/2:
A template-argument for a non-type template-parameter shall be a converted constant expression ([expr.const]) of the type of the template-parameter.
[expr.const]/10:
A converted constant expression of type T is an expression, implicitly converted to type T, where the converte... |
64,656,045 | 64,661,255 | How to count all non-zero pixels within each polygon area efficiently? | I want to calculate numbers of all white pixels within every polygon area efficiently.
Given some processes:
// some codes for reading gray image
// cv::Mat gray = cv::imread("gray.jpg");
// given polygons
// vector< vector<cv::Point> > polygons;
cv::Mat cropped;
cv::Mat mask = cv::Mat::zeros(gray.size(), CV_8UC1);
c... | There are some minor improvements that can be done, but all of them combined should provide a decent speedup.
Compute the threshold only once
Make most operations on smaller images, using the bounding box of your polygon to get the region of interest
Avoid unneeded copies in the for loop, use const auto&
Example code... |
64,656,428 | 64,656,475 | Error: No Matching Constructor when trying to construct a templated object from a vector value | I have the following templated classes MyObject and SmallObject. Below, I have a constructor for a MyObject that takes a vector as input and converts each item in the vector into a SmallObject. However, when it runs in tests, it returns an error for no matching constructor.
I can't tell what is wrong, my guess was that... | The parameter values is passed as reference to const, then values[i] returns const T&. While the constructor of SmallObj takes reference to non-const which can't bind to constant. If it's not supposed to modify the argument you can change the constructor to take reference to const.
template<typename T>
SmallObj<T>::Sma... |
64,656,916 | 64,664,189 | CMake. Public static library not linking, undefined reference | I am trying to setup a modern cmake project so it can be easily maintainable for my team. But when I compile I get a linker error in the main that my library functions are undefined.
I have a project with the following layout.
CMakeLists.txt
src/
├─ CMakeLists.txt
├─ main.cpp
├─ lib/
│ ├─ include/
│ │ ├─ lib.h
│ ├─... | I was calling a C function from C++ code. I simply needed to add this to my header files:
#ifdef __cplusplus
extern "C" {
#endif
...
#ifdef __cplusplus
}
#endif
|
64,657,155 | 64,674,571 | Including files with ifdef resulting in multiple definitions | I'm trying to understand ifdef directive + including files and while it appeared to make sense in my head, it seems to be not as straight forward as I had thought: I'm getting a "multiple definitions" error.
What I'm trying to do is get the compiler to include certain file depending on if something is defined.
I have ... | After some digging, it seems that there's just something I'm not understanding in the whole process. In any case, it also seems the consensus (from responses here and what I can read elsewhere) is that using the pre-processor isn't really the proper way to do what I want and a build system should be used.
Admittedly, i... |
64,657,316 | 64,657,392 | warning: object backing the pointer will be destroyed at the end of the full-expression for std::pair | Following code gives the dangling pointer error.
std::vector<std::pair<std::string, int>> c;
for (auto& b : c) {
const auto& [s, i] = b;
std::string_view v = s.substr(i);
std::cout << v;
}
I think that b holds the reference to the std::pair<std::string, int>, so s should be the refe... | In std::string_view v = s.substr(i);, std::string::substr returns std::string by value, i.e. it returns a temporary std::string. std::string could be converted to std::string_view implicitly, which is constructed from std::string::data(), i.e. the pointer to the underlying array of the temporary std::string. After the ... |
64,657,337 | 64,657,480 | c++ get number of bytes of the function arguments | How do I get the size in bytes of function parameters?
Example:
void DummyFun(int64_t a, int32_t b, char c);
The size in bytes is going to be 13.
I'm trying to solve this by using templates, but I'm not very good at it.
This is the contextualized code and what I tried so far:
template<typename T>
constexpr size_t getSi... | In C++17 you can use a fold expression:
template<typename... Others>
constexpr size_t getSize() {
return (sizeof(Others) + ...);
}
Demo
|
64,657,529 | 64,657,933 | What is no matching function for call to 'isPalindrome'? | top 35/3_palindrome.cpp:18:8: error: no matching function for call to 'isPalindrome'
if(isPalindrome(s)){
^~~~~~~~~~~~
top 35/3_palindrome.cpp:4:5: note: candidate function not viable: no known conversion from 'std::__1::string' (aka 'basic_string<char,
char_traits<char>, allocator<char> >') to 'char *... | The Problem
Your isPalindrome function expects char * for its argument. There is no suitable implicit conversion (operator or otherwise) from what you're giving it, a std::string, to that char *. The compiler is dutifully pressing on and attempting to find an alternative overload of isPalindrome that matches what you'r... |
64,657,898 | 64,664,312 | Why does C++ allow functions that don't actually return a value? | In C++, a function with a non-void return type without a return statement is allowed. So, the following code will compile:
std::string give_me_a_string()
{
}
In C#, however, such a method is not allowed. So, the following code will not compile:
public string GiveMeAString()
{
}
Why is this the case? What was the desi... | C++ requires code to be "well-behaved" in order to be executed in a defined manner, but the language doesn't try to be smarter than the programmer – when a situation arises that could lead to undefined behaviour, the compiler is free to assume that such a situation can actually never happen at runtime, even though it c... |
64,657,941 | 64,660,236 | How to count number of running process with given name? | How I could check how many instances of an executable is running also checking if each exe has a different PID?
--Edit--
What I already got:
The code display the PID correctly but szProcessName always return:
void DisplayProcessNameAndID(DWORD processID)
{
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
//... | As mentioned in the comment, OpenProcess failed and the GetModuleBaseName function was skipped. The processes you opened are protected process. Even if you have the SeDebugPrivilege privilege, it can only allow PROCESS_QUERY_LIMITED_INFORMATION|SYNCHRONIZE access.
The following sample to list process with name works fo... |
64,658,295 | 64,658,473 | c++ getline() doesn't seem to operate correctly, Doesn't read the line till the end | I have tried using cin.ignore(); instead of the dummy variable, didn't help. content of the file looks like this:
D Name Surname
A Name2 Surname2
...
amount of the students is unknown.
...
output should look like this:
Name Surname class: D
Name2 Surname2 class: A
but mine output loos like this:
Name Class A
urname Cla... | It looks like you've tried all kinds of things to make this work, including reading from cin in the middle of your loop that reads from file.. Very strange. I suggest you throw out the entire loop and try something simple as follows:
You just read one line at a time. For each line you read, you put that into a strin... |
64,658,307 | 64,658,701 | Where is the parameter -Isrc defined in CodeBlocks? | I've got an existing project written in C++ from my predecessor. He used CodeBlocks as an IDE.
I never used this IDE and hardly programmed any C++. He used the tinyxml library, so I added it to the project.
When I try to build it, the build log says something like this:
g++.exe -Wall -fexceptions -DBOOST_THREAD_USE_LIB... | Look for the include search directory configuration in
menue "Project"
entry "Build options ..."
tab "Search directories"
subtab "Compiler"
Linker search path nearby in subtab "Linker".
Config of libs to link in tab (not subtab) "Linker settings".
My CodeBlocks is 16.01, but that should not be too different whatever ... |
64,658,426 | 64,658,811 | Can Class Function get called by Threads and get access to class data? | For a project that I have to make for school, I have been asked to make a program using threads. The library I am using is <pthread.h>. To understand how threads work I tried by writing some code in a blank file to see how they would behave. I actually discovered thank to another stackoverflow question how to pass to p... | The main problem here is that you're trying to cast a single pointer arg to two pointers to different unrelated things and then dereference the result. You can't do it without having an undefined behaviour. You can only pass one pointer to pthread_create(), and if you need to pass more than that (e.g., pointer + index... |
64,658,925 | 64,659,146 | C++ Semantics of calling reset on a unique pointer in a destructor | Say we have a simple struct with a unique pointer in a hpp file:
struct SomeType
{
SomeType() = default;
~SomeType();
std::unique_ptr<int> ptr;
};
In the cpp we then have:
SomeType::~SomeType()
{
ptr.reset();
}
Is this destructor somehow useful or just superfluous?
Is there any chance of a double... | If that's the only line of code in the destructor it is unnecessary, it will happen either way. All members destructors are called after the parent destructor automatically.
It may be useful if you have some other stuff to do in the destructor and/or the exact order of actions is important.
Double deletion will not hap... |
64,659,232 | 64,661,475 | Fast 16-bit grayscale image writing (30fps) | I have a 16 bit grayscale camera stream with 30fps (1024x768px) and want to write each image as fast as possible to hard disk. The images sould not be compressed with lossy methods, I need every bit for further processing.
I tried it with but unfortunately PNG and TIFF are to slow and BMP does not support 16 bit in ope... | I found an answer, which was not documented.
The PGM Format support 16-bit grayscale with fast writing.
cv::imwrite("test.pgm", imOut);
I opened an issue to update OpenCV documentation. OpenCV 4.5.0 imwrite Documentation OpenCV Issue
Thank you.
|
64,659,464 | 64,659,795 | Why does a constructor when explicitly called return a temporary object, when it has no return type? | I am learning OOP in C++ and got to know that we can explicitly call the constructor as shown below:
var obj = var(); // Assume var is a class and obj is an instance of an object of the class var.
From what I have understood till now, var() constructor instantiates a temporary object, initializes it and then it is sen... | That syntax for creating an object looks like the syntax calling a function, but they are different. You can't call a constructor.
In C++17 there isn't even two objects. The temporary value var() is materialised as obj.
|
64,659,781 | 64,659,903 | Why incomplete type (forward declared) size calculation cannot be postponed when using type as a field? | In the following code:
class B;
struct A
{
B* b; // <- why MUST be a pointer? Why size cannot be calculated later...?
}
struct B
{
...
}
As far as I understand, struct A must define b as B*, as the compiler cannot tell the size of B when calculating size of A.
What I do not understand, is why the compiler cann... | Imagine that you could actually define A as:
class B;
struct A {
B b; // not a pointer
}
That is, b is a data member of incomplete type – the compiler doesn't know the size of B at this point.
Then, if B were defined as:
struct B {
A a;
}
This would require infinite memory.
|
64,660,000 | 64,660,094 | Copy a file from one directory to another in C++ | I am writing a C++ program to copy one file from one directory to another. I don't want to use C++ 17 features. I have already implemented this in the following code.
#include <iostream>
#include <exception>
#include <filesystem>
using std:: cout;
using std:: cin;
using std:: endl;
int main(int argc, char* argv[])
{
... | Change this:
system("cp source destination");
To this:
std::string cmd = std::string("cp '") + source + "' '" + destination + "'";
system(cmd.c_str());
And BTW, you should either return from inside the if(argc != 3) statement, or do the rest of the code inside an else statement.
Lastly, function int main(int argc, ch... |
64,660,122 | 64,660,940 | How to achieve shortsell condition in this stock profit maximisation code? | This is the code I have written to buy the stock when the price is lowest and sell when it is max. I want to implement shortsell condition here like I want to sell even before buying.
Consider this array of stock prices for a week.
3 10 4 1 9 3 2
Now I want to sell when the price is 10 and buy when the price is 1... | If you allow shortselling, your profit is always = max(array) - min(array) without exceptions.
|
64,660,762 | 64,661,302 | How can I interleave a section of two binary numbers? | I am trying to "merge" two binary integers into one but I can't seem to get it right.
The operation I am trying to do is:
Number of bits to merge = 3 (precomputed parameter)
Int 1 : 10010
Int 2 : 11011
Given these two numbers, append 3 bit of each to the result (left to right):
Result : 11 01 00.
Meaning the first ... | You can set each bit in a loop:
std::uint32_t merge(std::size_t start, std::size_t numberOfBits, int i1, int i2) {
if (start == 0 || start > sizeof(int) * 8) return 0;
if (numberOfBits == 0 || numberOfBits > 16) return 0;
if (start < numberOfBits) return 0;
int result = 0;
for (std::size_t i = ... |
64,661,121 | 64,668,173 | Selection exclusion in nested QGraphicsScenes | I have a QGraphicsScene (let's call it mother scene) that includes items, and some of them include a QGraphicsScene as well (let's call them daughter scenes).
Observation : The selection in the daughter scene and in the mother scene don't bother each other. It means that, if I select an item in the mother scene, I can ... | Disclamer
I personally do not recommend embedding widgets in a QGraphicsScene:
The key to the high performance of Graphics View is reducing how much is painted each frame. QGraphicsWidget and QGraphicsProxyWidget together are huge performance killers because they can not be rendered in a efficient way.
The source of ... |
64,661,430 | 64,661,484 | Using the newline character to break a loop in c++ | I'm looking for a way to break a for loop using enter in the visual studio console.
do {
std::cin >> userInput;
if (userInput == '\n')
break;
lineStorage[lineLength] = userInput;
lineLength++;
} while(true);
This is what I have so far, but the newline character won't work for what I need it to.... | Reading with >> by default skips whitespace, and a newline is whitespace. I suggest using getline() instead:
for(int i = 0; i < 80; i++) {
if (!getline(std::cin, userInput) || userInput.empty())
break;
lineStorage[lineLength] = userInput;
lineLength++;
}
If your lineStorage is really supposed to s... |
64,661,493 | 64,682,365 | What is the difference between a Viewport and a View? | Why would you need a viewport? Isn't a View engough? What is the difference?
I have one viewport in my program created so long ago that I forgot it was even there... And now that I want multi-staged rendering and I wonder if I need another one. And the Viewport mdocs page doesn't get into how and why (or maybe I'm blin... | A viewport is how much of the window a view takes up.
A view is what should be visible in that viewport.
A good scenario of having many viewports would be in a splitscreen game.
In a splitscreen game, each player has their own section of the screen. The game can not render one players view inside another players viewpo... |
64,662,045 | 64,699,787 | Intercept TAB Key in WebView2 | I want to intercept the Tab key inside Webview2.
It is possible to intercept a lot of function keys via ICoreWebView2AcceleratorKeyPressedEventHandler that I register with add_AcceleratorKeyPressed
But some keys like the cursor keys and the TAB key doesn't call this event handler. Same for the F5 key, it seams that som... | As mentioned in the discussion I solved the problem.
First I injected a Java script into the browser
m_spWebView->AddScriptToExecuteOnDocumentCreated(
L"window.document.addEventListener('keydown', function(e) {\n"
L" if (e.keyCode===9 || e.keyCode===13) {\n"
L" window.chrome.webview.postMessage('" CHAR_TOK... |
64,662,134 | 64,662,214 | Return reference from operator[] using a bitset adapter | I am using std::bitset with enum class to have more convenient tool. But I am facing a compilation error when returning value from operator[]:
error: non-const lvalue reference to type 'bool' cannot bind to a temporary of type 'std::__1::bitset<2>::reference' (aka '__bit_reference<std::__1::__bitset<1, 2> >')
I have t... | std::bitset (like std::vector<bool>) does not return a bool & from the non-const-version of operator[]. The reasons for this are technical and come from the fact that a bool variable is one byte big while a element of std::bitset is only one bit big. Further bool as type has an alignment requirement of 1 byte, but the ... |
64,662,594 | 64,663,044 | writing to file not displaying everything c++ | not sure where im going wrong
I am trying to write to a file in c++.
this is the code:
struct Student {
int id;
std::string name;
double mark;
double priority;
bool operator < (const Student & s) const {
return (priority < s.priority);
}
void print() const {
std::ofstream myfile;
myf... | The issue in yor current code is that the print() function is overwriting the output file each time it is called.
One possible solution that doesn't require you to use ios::app is to change the signature of the function as follows:
void print(std::ofstream& myfile ) const {
myfile << "id: (";
myfile<< id;
m... |
64,663,165 | 64,663,334 | How to inherit a class constructor that gets a class object c++ | Hello i don't know how to create constructor for rectangle class that inherits from point class. I would like to make that constructor of rectangle take object of class point (it's in the /**/ comment)
class point
{
double x_, y_, z_;
public:
point(const double& a1 = 0, const double& a2 = 0, const double& ... | You can get away with
rectangle(point p1, const double& a1, const double& a2) : point(p1), a_(a1), b_(a2) {}
if you don't have other constructors in point else you will need to add
point(const point& other) = default; // copy construcor
at which point you will also need to look at the rule of three or five
|
64,663,355 | 64,663,614 | Why does the address of a "size_type" variable is used as an argument of "stoi()" in C++? | The address of a size_type variable is used as an argument of stoi(). Reference link is given below:
stoi()
I can also do the same operation without using size_type. I have read the documentation I have given, but I didn't get when should I use it.
Then, what is the contribution of using the address of a size_type vari... | First, it is not mandatory, it can be NULL.
The contribution is for case when your string contains several values. This allows to parse them one by one. After a call to stoi, *idx will contain the start index of the next integer.
For example:
int main() {
std::string str = "23 45 56 5656";
std::string::size_typ... |
64,663,770 | 64,664,268 | Processing two-dimensional dynamically allocated arrays | I need to find the maximum element from the elements below the side diagonal.
But my program searches for the maximum element in the entire array except for the side diagonal. How can I fix this?
#include <iostream>
#include <iomanip>
#include <math.h>
#include <conio.h>
using namespace std;
int main()
{
int **a, t... | The problem is that you initiate max with value a[0][0] which is above side diagonal, so there is a probability it is greater than the value you need. You can correct this by initiating it was the first value below the side diagonal like this.
int max = a[1][n - 1];
You can also make the program run faster by changin... |
64,663,899 | 64,663,961 | Why don't I get destructors called when using unique_ptr? | Here I am creating dynamically allocated array of S objects and I expect them to be destroyed by unique_ptr, which doesn't happen and I get this error
Command terminated by signal 11
and that means the program accessed memory which it shouldn't have accessed as far as I am concerned.
#include <iostream>
#include <memor... |
new s[4]
If you use new[] allocation you have to destroy it using delete[], not delete.
auto ptr = unique_ptr<S[]>(arr);
|
64,665,212 | 64,665,300 | Pass a function pointer as an argument between classes | How can we pass a function pointer as an argument? For example, the function pointer myFunPtr is an argument when calling class A and I need this pointer to point to function funcB in class B
#include <iostream>
typedef void(*myFunPtr)(void);
class A {
public:
A(myFunPtr ptr);
virtual ~A();
myFunPtr fu... | This is a function pointer type to a free function (not a class member function):
typedef void(*myFunPtr)(void);
This is a B member function pointer type:
typedef void(B::*myFunPtr)(void);
Demo
Here's another Demo that will call a member function in a B. To do that, a pointer to a B and a pointer to a B member functi... |
64,665,320 | 66,771,040 | Are ros2 messages self describing? | In c++ and ros2, is it possible to subscribe to a topic without knowing its type? If so, and a message is received, is it possible to introspect the message at all, again without knowing its type? Meaning, are ros2 messages self-describing (such as FlexBuffer messages)?
| No, ros2 messages are not self-describing, since they are binarized in order to improve throughput. Hence, you need not only the .msg/.idl description file, but also need to compile that into a message description, before the messages can be interpreted.
The concept of ros2 interfaces is described here: https://docs.ro... |
64,665,329 | 64,665,396 | Making structured (even) spaces in C++ for displaying data | I've created a program that displays multiplication table:
for (int a=1; a<=10; a++)
{
cout << endl;
for (int b=1; b<=10; b++)
{
cout << " [" << a*b <<"] ";
}
}
The problem is it displays it like this:
I've tried to use setw() but it doesn't work since it sets it to all the numbers so it jus... | If you look at the documentation for setw you will note that you need to stream it to your stream like so:
cout << " [" << setw(3) << a*b <<"] ";
Here is a live example.
If you need to calculate the size that you need for the stream width, you can look up a question like this:
Efficient way to determine number of d... |
64,665,552 | 64,665,619 | What happens when you pass a memory address to a function with a pass by pointer arguement? | I was studying C++ and got confused in this part the following question below:
What is the output of the following program?
#include <iostream>
using namespace std;
void displayArray(const int A[], const int no){
for (int i = 0; i < no; i++)
cout << A[i] << "\t";
cout << endl;
}
void modifyArray(in... | Indexing an array is essentially adding then dereferencing. So, arr[i] == *(arr + i). Thus, &b[3] == &(*(b + 3)) which is just b + 3. Since arrays are contiguous chunks of memory, this is just an array that starts 3 elements over, or {4, 5, 6, 7, 8}. So, index 4 of that array, which is index 7 of the original array, is... |
64,665,582 | 64,666,626 | How to merge two QJsonObjects in Qt? | I have:
QJsonObject obj1({"bla" : "lab"})
QJsonObject obj2({"bla2" : "lab2"})
and I need:
QJsonObject obj3({"bla" : "lab", "bla2" : "lab2"})
Or in JSON:
{
"bla" : "lab"
}
{
"bla2" : "lab2"
}
And I need:
{
"bla" : "lab",
"bla2" : "lab2"
}
How to achieve that?
| Solution
I prefer to avoid explicit loops, so my solution would be to use a convertion to and from QVariantMap, aka QMap<QString, QVariant>:
Use QJsonObject::toVariantMap to convert all JSON objects to QVariantMap
Use QMap::insert to insert all maps into one
Use QJsonObject::fromVariantMap to convert the resulting m... |
64,665,782 | 64,665,873 | How to access nested template parameters that are enums? | Say I have a class template taking an enum parameter, A below. And I have another class template, B. And I instantiate an object of B specialized on A as in the code shown here:
enum class Colours { red, green, blue };
template <Colours C>
class A {};
template <typename T>
class B {};
B<A<Colours::red>> myObj;
How ... |
Adding a using E = E; line to A doesn't compile.
Indeed it does not. But you can do something like this:
template <auto E_>
class A {
public: static constexpr auto E = E_;
};
which compiles and works as expected. This assumes C++17.
|
64,665,966 | 64,666,557 | Operator with different types | I am quite new to C++ and I am implementing a, quite simple, (linear algebra) vector class as a template.
Now, I am trying to implement the addition and subtraction operators but with the ability to perform the operations not only between vectors, but also with scalars (short, long, float, double, etc.) (this will be a... | First, the free function template doesn't need to be a friend since it's not directly accessing the private members in Vector<T>. It also doesn't need to be forward declared. This can also be greatly simplified by using a std::vector<T> to keep the data to not have to implement the rule of 5 manually.
Example:
#include... |
64,666,139 | 64,675,592 | Display row numbers in ListView UWP | I'm looking for a solution to display row numbers for every element in ListView. What's more, the row numbers need to be updated after some element is deleted from the list or when the elements are moved to another positions. I'm using UWP (C++).
| If you want to display row numbers in a ListView, we suggest you to use data binding. You could refer to the document: XAML controls; bind to a C++/WinRT property and XAML items controls; bind to a C++/WinRT collection for detailed code about data binding.
Take the project Bookstore implemented in the above documents a... |
64,666,769 | 64,667,289 | "Identifier is undefined" error after I explicitly defined the method | I wrote the following code, composing of two classes, Item and Integer. Integer is derived from Item and has a value "data". I wrote a printAll method which is meant to print one by one the elements of an array containing pointers but when I try to implement the printAll method in the main function I am getting an erro... | The mistake is that you put printAll in the Integer class. Change your code like this
class Integer : public Item {
...
};
void printAll(Item** items, int n) {
for (int i = 0; i < n; i++) {
items[i]->print();
}
}
If a method is in a class, then you must (explicitly or implicitly) provide an object... |
64,667,081 | 64,667,144 | (Congruence) Why does the std:: before the first thread make it print second? | #include <iostream>
#include <thread>
void foo(){
std::cout << "Thread 1 \n";
}
void bar(){
std::cout<< "Thread 2 \n";
}
using namespace std;
int main()
{
std::thread t1(foo);
thread t2(bar);
t1.join();
t2.join();
return 0;
}
The above code gives me an output of Thread 1 \n Thread 2... | Using std:: has absolutely no impact here. You simply do not have any control over in which order the threads will be run so you can get any order.
|
64,667,503 | 64,667,614 | How to save the build time of a C++ DLL | My project is a C++ DLL (cmake project), that expose methods from a c interface to another C# project,
I want to add a methode getBuildTime() in the c interface that return the buildtime (the exact date and time) so from the C# project we can know when the DLL was built.
Is there a way to do this stuff ?
I don't know i... | Build time in C/C++ code can be obtained by built-in macros __DATE__ and __TIME__, e.g. do something like string build_time = __DATE__ " " __TIME__;.
Also file which contains these macros usage needs to be touched before each build to change file's modify time. touch is a unix command, which can be avaialble in Windows... |
64,668,027 | 64,668,550 | Access member elements of derived class from overriden | How do I access the derived class after overriding the copy operator overload function?
I'm new to OOP C++ so I'm not sure if defining operator overloads as pure virtual works; otherwise, how would I enforce them to be defined in derived classes?
The example here I used is of a Matrix interface and a row-major specific... | As mentioned in the comments, you can use a dynamic_cast on the passed reference to test if it refers to an actual RMMatrix object. Something like this:
RMMatrix& operator=(const IMatrix& other) override {
const RMMatrix& test = dynamic_cast<const RMMatrix&>(other);
data = test.data;
return ... |
64,668,478 | 64,672,450 | Print a sequence of strings with one missplaced string | I'm doing an exercise for fun (not homework), where given a sequence of strings sorted, with one word that appears too soon, we have to print the sequence sorted.
The point is that we have to do it with O(1) auxiliary space, so no vector nor list
I tried the following:
#include <iostream>
#include <string>
using namesp... | You can simplify the code to:
std::string word1;
std::string word2;
std::cin >> word1 >> word2;
while (word2 != "END") {
std::cout << std::min(word1, word2) << std::endl;
word1 = std::max(word1, word2);
std::cin >> word2;
}
std::cout << word1 << std::endl;
Demo
|
64,668,526 | 64,669,398 | why do I have to use cin.ignore when I not using getline()? | I wrote the following code
#include <iostream>
#include <string>
using namespace std;
int main()
{
int i;
while(true)
{
cout << "\nEnter an integer: ";
cin >> i;
if( cin.good() )
{
break;
}
cin.clear();
cout << "Incorrect input";
}
cout << "inte... | Basically the ignore() reads the rest of the line and drops it. You want to do this because otherwise you would simply try to re-read the same value again and again and always fail.
Example:
Enter an integer:
Fify Six <-- If I typed that.
Then the line:
cin >> i; // This will fail (... |
64,668,535 | 64,668,790 | Trouble setting console window title in C++ | I've been trying to learn how to make C++ apps with the Windows API. I tried using a simple function, SetConsoleTitle(), to set the title of the console window. This is my program:
#include <iostream>
#include <tchar.h>
#include <windows.h>
int main(){
TCHAR abc[5];
abc[0] = 'H';
abc[1] = 'E';
abc[2] =... | As @AlanBirtles says, you need to null terminate your string. That's the only way C++ knows how long the string is. There are three ways to do that:
TCHAR abc[6]; // <-- increase this size
...
abc[5] = '\0'; // <-- add this
TCHAR abc[] = "HELLO"; // the terminator will be added automatically
TCHAR abc[6] = {0}; /... |
64,668,597 | 64,668,976 | glCopyPixels() is not returning the selected buffer pixels | I'm trying to copy the front buffer to the back buffer and also I need to copy the back buffer to the aux0 or aux1 buffer, but I can't get it to work. All I get is a blank copy, not the pixels. I do this right after I swap buffers with: SwapBuffers(glDeviceContext);
This is the code to get the pixels into another buff... | Instead of using glCopyPixels I recommend using framebuffer objects and use glBlitFrameBuffer or drawing a textured quad to the back buffer, instead of copying the front buffer to the back buffer. In general you should treat both the front and the back buffer as unreliable where the contents might become corrupted at a... |
64,668,791 | 64,668,907 | C++ Constructor calling | Lets assume I have a program:
class A {
public:
A() { cout << '1'; }
A(int i) { cout << '2'; }
};
int main() {
A a;
a = 0;
return 0;
}
Result of this program will be 12.
So my question is - why am I able to call the second constructor through a = 0, when I already created the object and called th... |
Isn't a constructor supposed to be called only once (during object creation)?
Yes, and that's what happens.
When you do a = 0;, the copy assignment operator A &operator=(const A &) gets called. Since the second operand is an int rather than an A, a new temporary instance of A is constructed, passed to the assignment ... |
64,668,870 | 64,669,011 | Adding const char* to string_view | I have a string_view:
std::string_view view;
How can I append something like a const char* to it? For example:
std::string_view view = "hello";
view += " world"; // Doesn't work
Also, how can I create a string_view with a specified size?
Like for example:
std::string_view view(100); // Creates a string_view with an i... | std::string_view is a read-only view into an existing char[] buffer stored elsewhere in memory, or to chars that are accessible by a range of iterators. You can't add new data to a std::string_view.
For what you are attempting, you need to use std::string instead, eg:
std::string s = "hello";
s += " world";
std::stri... |
64,668,965 | 64,669,037 | Partial template instanciation | If I have this two template classes:
template<int a, typename V>
class A {
};
template<template<int, typename> typename V>
class B {
};
I can write something like B<A> a;.
How can I achieve a similar thing for this two classes:
template<int a, typename V>
class A {
};
template<template<typename> typename V>
class ... | You can't do this directly, but you can create a helper template using and pass it to B.
template <int N>
struct foo
{
template <typename T>
using type = A<N, T>;
};
B<foo<42>::type> x;
|
64,669,335 | 64,669,854 | Is it reasonable approach when C++ function does not 'move from' rvalue reference argument? | Suppose the class Object satisfies the requirements of MoveConstructible and MoveAssignable, but not the requirements of either CopyConstructible or CopyAssignable (i.e. PIMPL with unique_ptr within). Then I have two consumers:
bool consumer1(Object && arg) {
if(arg ...) { // arg satisfies some condition
... | This question is rather subjective, but I'll try to answer in the definitive.
While there isn't anything technically incorrect about the code you have authored, since the code will compile and run correctly, from a higher-level this is a design-smell.
Visibly duplicate calls to std::move on objects limits a developer's... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.