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 |
|---|---|---|---|---|
66,522,661 | 66,529,717 | Forwarding Q_PROPERTY from one class to another | I have a GUI component written using QtWidgets and I have created a QtQuick wrapper for the component by inheriting QQuickItem. The original component expose a number of properties that can be exposed directly, while some properties require introducing new classes derived from QQuickItem. Is there a more elegant way to... | The problem here is that we cannot inherit from both QtWidget AND QtQuickItem because both are subclass of QObject and Qt MOC simply does not support this. It also does not support templates of QObject-based classes.
So unfortunately we have to write additional code to pass properties through one way or another.
With i... |
66,522,936 | 66,523,043 | Why are some ARRAYS written like this in C++? | I just wanted to know why are some arrays written like this?
int arr[] = {3, 4, 6, 9, 11};
Why can't it just be written like this instead?
int arr[5] = {3, 4, 6, 9, 11}
What's the benefit?
|
Why can't it just be written like this instead?
The premise is wrong. It can be written both ways.
What's the benefit?
The size is redundant information. We've already implicitly given the size 5 by providing 5 initialisers. Providing redundant information is a potential source of bugs during development when that ... |
66,522,951 | 66,523,357 | Sort a 3D std::vector based on values in a 1D std::vector | I have a 3D vector :
vector<vector<vector<char>>> children;
this vector contains multiple 2D vectors and I would like to sort them based on a 1D vector:
vector<int> score;
each 2D vector in children is associated with a value in score. I have tried multiple similar questions but with no luck, so I was wondering how d... | If your goal is to sort the scores and maintain the sorted scores with their relative position in the 3D vector, as the comment suggested and based on this answer, you can sort an array of indices that are based on the score criteria.
After sorting the indices, you use the indices to "point to" each sorted item in the ... |
66,523,086 | 66,523,109 | Type Confusion in C++ | I am referring to this link.
#include <iostream>
using namespace std;
class Base {}; // Parent Class
class Execute: public Base { // Child of Base Class
public:
virtual void exec(const char *program)
{
system(program);
}
};
class Greeter: public Base { // Child of Base Class
public:
vir... | The name is mapped to an index in the vtable at compile time, so at run time the function call is just an array lookup.
The code in question results in Undefined Behavior, because a b2 is not a Greeter*. (A dynamic_cast would return nullptr.) One possible outcome is that the vtable entry for sayHi will have the same in... |
66,523,170 | 66,524,043 | How to close particular aplication after opening it in c++? | So in my code I'm opening for example notepad using ShellExecute and I want to close it after but I cannot find any working way, so my question is, what is the easiest way to close particular aplication using c++ code?
#include <iostream>
#include <Windows.h>
int main()
{
ShellExecute(NULL, "open", "notepad", NUL... | You can use ShellExecuteEx with SEE_MASK_NOCLOSEPROCESS, then you can pass it as a parameter it to the TerminateProcess function.
Here is a sample:
#include <windows.h>
int main()
{
SHELLEXECUTEINFO lpExecInfo{};
lpExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
lpExecInfo.lpFile = L"notepad.exe";
lpExecIn... |
66,523,211 | 66,525,926 | Is there a limit of object in openGL? | I want to draw 2000 spheres using OpenGL in Visual C++.
The following code draw 1000 spheres and the result looks fine.
But when I increase the number of spheres of 2000 (see the partial below code and highlighted by ** ), it failed.
The following error message appears.
"freeglut : fgInitGL2 : fghGenBuffers is NULL"
Co... |
Is there a limit of object in openGL?
OpenGL doesn't define limits like a "maximum number of objects".
Application is able to draw as many objects as possible as they fit into CPU memory, but usually drawing becomes unreliably slow before application hits memory limits. Even when all texture and vertex data do not fi... |
66,523,478 | 66,524,581 | Template method overload not called | I have this class (.h file):
class Entity {
public:
template<typename T, typename... Args>
T& addComponent(Args &&... args) {
// add component and return
}
};
When I get an specific type, i want a different behavior, so I'm triying to overload the "addComponent" method like this (.cpp file):
tem... | The trouble with the original code is that when code wants to use a specialization of that template function, it must know that the explicit specialization exists. If the explicit specialization is only found in one translation unit (generally meaning a single *.cpp file plus included headers), then it's invalid for a ... |
66,523,483 | 66,523,751 | Is there any way to check if a template class has a nested class definition (or a typedef) in C++14? | I have the following structures defined:
struct NoRelationship {};
struct OneToMany {};
struct Interdependent {};
template <typename RelationType>
struct SignatureGenerator
{
using type = std::function<void()>;
};
template <>
struct SignatureGenerator<Interdependent>
{
using type = std::function<void()>;... | For your yes overload, you are using:
template<typename C> static yes test(decltype(&C::extra_type)); // incorrect for types
However, the decltype and & is only needed because the example that you were looking at was checking for the existence of a member function. But extra_type is a type, and so you can't take its a... |
66,523,693 | 66,523,871 | C++20 concepts require operator overloading combine with user-define template operator overloading function | case 1
Consider the following concept which requires the value_type of a range R is printable:
#include <iostream>
#include <iterator>
template <class R, typename T = std::ranges::range_value_t<R>>
concept printable_range = requires(std::ostream& os, const T& x) { os << x; };
It works fine with std::vector<int> on di... |
Which compiler should I trust? It seems like a Clang bug.
This is a GCC/MSVC bug. Name lookup for os << x will perform argument-dependent lookup to find any other associated operator<<s, but the associated namespaces here are just std. Your operator<< is not in namespace std, so lookup should not find it, so there sh... |
66,524,404 | 66,524,522 | Is there a way I can fix this issue with length counter function? | I have to find the length of an array of characters using a function that uses the pointer notation and, for some reason, I get 23 but the result should be 5.
Here is the code I built:
#include <iostream>
using namespace std;
int length(char *N)
{
int length = 0;
char* S = N;
for (; *S != '\0'; S++);
f... | You don't need two loops.
And note that you have to leave a space in the array (the last element) to fill it by '\0'.
Hence by the two notes and if you want to use five characters excluding the '\0', your code will be as follows
#include <iostream>
size_t length(char *N){
size_t length = 0;
for (; *N != '\0'; N... |
66,524,450 | 66,524,628 | variable in constructor not declared in this scope c++ | Forgive me for I'm still a beginner in c++
The following code gives an error that the variable is not in scope,
error: 'vec' was not declared in this scope
vec[key] = value;
without changing how object is declared in the main function, how can I resolve this issue?
// Program to illustrate the working of
/... | /** Initialize your data structure here. */
std::vector<int> vec;
MyHashMap():vec(1000000, -1)
{}
|
66,524,772 | 66,524,810 | Does returning to another void function from a void function is legal in C++? | The C standard prohibit this. But I'm not sure what C++ standard says about this.
#include <iostream>
void bar() {
std::cout << "From Bar" << "\n";
}
void foo() {
std::cout << "From Foo" << "\n";
return bar();
}
int main()
{
foo();
return 0;
}
The program compiles and works just fine. ... | Yes, this is allowed in C++. The standard says (quote from latest draft):
[stmt.return]
... A return statement with an operand of type void shall be used only in a function whose return type is cv void. ...
|
66,524,793 | 66,524,849 | How to use the enum of one .proto file in another file? | For CPP programming, I have defined a enum in a .proto file and I have to use the same enum in another .proto file.
//first.proto
package A;
enum foo
{
COUNTRY_UNKNOWN = 0;
COUNTRY_INDIA = 1;
}
I want to use the foo data structure in another .proto file like this:
//second.proto
package B;
message bar
{
fo... | update like this:
import 'first.proto';
package B;
message
{
A.foo currentCountry = 1;
}
|
66,525,352 | 66,527,132 | How can I get the integral type of a template argument regardless of whether it's an enum or not | I'm getting the error:
Error C2154 '_Ty': only enumeration type is allowed as an argument to compiler intrinsic type trait '__underlying_type'
I thought it shouldn't be resolving underlying_type to underlying_type, because I first check whether T is an enum. Here is the code:
template <typename T>
struct Foo
{
... | Unfortunately, std::integral_underlying_type is not SFINAE friendly until C++20.
You can then delay instantiation of std::underlying_type<T>::type:
template <typename T>
struct Foo
{
using integral_underlying_type =
typename std::conditional_t<std::is_enum_v<T>,
std::unde... |
66,525,575 | 66,525,712 | What does (*p_z[id])(p_z[id]->size() - 1) do? | I've never used c++ and I'm converting a C++ code to Python. This line was hard to Google and I could not figure out whether my interpretation is correct.
We have p_z, which is declared as a vector<shared_ptr<ArrayXd>>. ArrayXd appears to be something from the Eigen library and represents a 1d dynamic array. Then:
(... | If you don't understand complex code, you can simplify it, even without understanding. In this case, p_z[id] appears twice, so you can introduce a temporary variable for it:
vector< shared_ptr <ArrayXd> > p_z;
shared_ptr <ArrayXd> temp = p_z[id];
(*temp)(temp->size() - 1)
Now, you can see that temp gets dereferenced t... |
66,525,703 | 66,525,915 | Polymorphism cast doesn't work for my classes | Sorry for asking I believe a repeated question, but I can't figure out the problem here, maybe my understanding of this is not correct.
Setup
class Job {
public:
virtual bool createJob() {
return false;
}
};
class Limit {
public:
virtual bool updateLimit() {
... | As dxiv has already stated in his comment, static/dynamic_cast will only work, if the object in question actually IS that class.
They are hints to the compiler that a pointer/reference to a variable is of a certain class, but they do not convert the base class to the subclass.
So this would work:
Base *basePtr = new De... |
66,525,740 | 66,527,585 | How to use a virtual environment to call Python from C++ in Clion? | I would like to use a virtual environment to call Python from C++ in Clion.
I can use Py_Initialize(); on C++ when I run it on terminal, but I cannot use it when I run it on Clion.
The following is the error message when running in Clion.
Could not find platform independent libraries <prefix>
Could not find platform d... | I have reworked your CMakeLists.txt to use the standard way of finding the Python interpreter and Python libraries. Can you give it go? If you have CMake 3.14 or higher then the ability to find NumPy is already built in.
cmake_minimum_required( VERSION 3.14 )
# Create Project
project( Python2CPP )
# Require C++14 (or ... |
66,525,751 | 66,525,782 | How to make code faster to fit it in time limit? | I'm trying to submit this code on spoj https://www.spoj.com/problems/PALIN which is asking to find next smallest palindrome of a given number n, but as this code works, it is slow therefor it exceeds the time limit (2-9 seconds). is there another way to solve this exercise in a faster way?
The first line contains integ... | The most obvious thing to do is to stop copying and reversing the string. Instead, compare the first character to the last character, then the second to the second-to-last, and so on.
Also, why are you using strings at all? Strings are complex and expensive. The operations you are performing can be done entirely on num... |
66,525,779 | 66,550,709 | C++ Get the substring between custom delimiters without the use of regex | I've a simple string of format:
"lorem ipsum <span id='1'>extract_me-1</span> dolor
sit amet <span id='2'>extract_me-2</span> adispicing consequit lorem ipsum
sit amet <span id='3'>extract_me-3</span> adispicing dolor lorem"
And now i need to extract the strings between a custom delimiters specified
for example,
Subst... | I was able to solve this using .find and .substr. It turned out to be easier than I thought
#include <string>
#include <iostream>
using namespace std;
int t1,t2;
string str="lorem ipsum <span id='1'>extract_me-1</span> dolor sit amet <span id='2'>extract_me-2</span> adispicing consequit lorem ipsum sit amet <span id=... |
66,525,858 | 66,526,383 | Error in Linked List Insertion at last position | I coded a Linked List Insertion program in C++. When I added a function to insert a node at the last position of the linked list, I am getting a weird output. It seems like the address is being outputted. This is my code.
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node... | I do not see any problem with logic, and i think your code should be fixed by removing the public "Node *ptr;" variable definition. In other words, you may only need to add this variable locally in all of your fuctions.
Also it would be a better practice if you initialized the node->next =null inside Node constructor.
... |
66,525,874 | 66,525,991 | The behavior of the for loop split between switch cases | While playing with the code I've noticed a strange behavior that I do not know to explain the logic behind
void foo(int n)
{
int m = n;
while (--n > 0)
{
switch (n)
{
case -1:
case 0:
for (int j = 0; j < m; ++j)
default:
... | default is just a label (address to where the code jumps if n is not -1 or 0).
Thus when n is not -1 or 0, the flow enters the body of the for loop skipping the initialisation of j. You can write the same code also as this, so it would be clearer what is happening here:
int m = n;
while (--n > 0)
{
switch (n)
{... |
66,526,033 | 66,526,034 | How can I have code called (e.g., a function) when the player changes text cursor position in a multiline text box? | I'd like to use something like a multiline editable box widget for my UMG ui, and have something happen when the text cursor moves, in any of the various ways that can occur. How can I get my code called at these times, and also how do I get information about where the cursor currently is in the text?
I see in the SMul... | Make a child class of UMultiLineEditableTextBox, which has a function with the same signature as OnCursorMoved. This class will also need to override TSharedRef<SWidget> RebuildWidget():
#include "CoreMinimal.h"
#include "Components/MultiLineEditableTextBox.h"
#include "MyEditable.generated.h"
/**
*
*/
UCLASS()
cla... |
66,526,664 | 66,527,104 | How can I print a list of structs that contain two members? | I created a struct and put two member variables in it. Then initialized a list with the mentioned struct type.
struct job {
string name;
int time;
};
list<job> jobList;
string line;
ifstream file("input.txt"); // the direction of my input file.
if (file.is_open()) {
while (getline(file, line)) {
... | The problem with:
for (auto v : jobList)
std::cout << v << "\n";
}
is that v is a job structure, and you have no stream output operator overloaded for job.
There are two possible solutions:
Output the members one by one:
for (auto const& v : jobList) {
std::cout << v.name << " - " << v.time << '\n';
}
Creat... |
66,526,702 | 66,526,729 | C++ lambda capture by value semantic? | class TestGetStr {
public:
string a;
string getString() {
return a;
}
};
void acceptConstString(const string & a) {
std::cout << a << std::endl;
}
int main(int argc, const char * argv[]) {
auto testGetStr = TestGetStr();
acceptConstString(testGetStr.getString()); //compile ok
... | You can add mutable qualifier.
auto testaaa = [testGetStr]() mutable {
// ^^^^^^^
acceptConstString(testGetStr.getString());
};
Otherwise the operator() of the lambda is const-qualified, and then can't call non-const member functions on the captured object.
mutable: allows body to modi... |
66,526,875 | 66,551,430 | MinGW C++ compiler cant find OpenCV in the system path | So I'm getting an error stating "fatal error: opencv2\core\mat.hpp: No such file or directory" when trying to compile a small c++ file from .cpp with MinGW. It happens in one form or another in Sublime Text 3, Atom, and on the command line with "gcc myfile.cpp". I should note that I'm on Windows 10. Here's the code:
#i... | Add -I option with path to opencv includes and -L with path to opencv libraries, like this:
gcc -IC:\OpenCV\opencv\build\include -LC:\OpenCV\opencv\build\x64\vc15\lib test_opencv.cpp
|
66,527,033 | 66,527,170 | Why does min still complain inside constexpr? | I have the following code snippet:
#include <iostream>
#include <type_traits>
#include <algorithm>
#include <cstdint>
using T = double;
int main()
{
f();
}
void f() {
T x = 2;
if constexpr(std::is_integral_v<T>)
{
std::cout << std::min(static_cast<int64_t>(2), x);
} else {
std::cout << ... | You need to make f() template, and T template parameter.
template <typename T>
void f() {
T x = 2;
if constexpr(std::is_integral_v<T>)
{
std::cout << std::min(static_cast<int64_t>(2), x);
} else {
std::cout << std::min(1.0, x);
}
}
then
int main()
{
f<double>();
}
For constexpr if:... |
66,527,567 | 66,528,593 | Get sub-map from std::map by number of elements instead of key using iterator | I have a std::map<std::string, std::vector<std::string>> and I need to perform a threaded task on this map by dividing the map into sub-maps and passing each sub-map to a thread.
With a std::vector<T> I would be able to get a sub-vector pretty easy, by doing this:
#include <vector>
#include <string>
int main(void)
{
... | A slightly different approach would be to use one of the execution policies added in C++17, like std::execution::parallel_policy. In the example below, the instance std::execution::par is used:
#include <execution>
// ...
std::for_each(std::execution::par, full.begin(), full.end(), [](auto& p) {
// He... |
66,527,835 | 66,528,965 | Do I have to call py::initialize_interpreter() and py::finalize_interpreter() within the same scope? | I am trying to embed Python script in my C++ application.
I am wondering if I have to call py::initialize_interpreter() and py::finalize_interpreter() within the same scope, like below.
if(condition){
py::initialize_interpreter();
{
other pybind processes
}
py::finalize_interpreter();
}
Or can I do ... | No you don't need to call it in same scope, however you need to be aware that you can not call the py::initialize_interpreter(); again once it was initialized. To call it again you first need to call py::finalize_interpreter();.
|
66,527,957 | 66,528,069 | C++ Return the reference of an array | The original question is exercise 6.36 in C++ Primer 5th.
It wants a declaration which returns the reference of an array including 10 strings.
I found the answer here.
But when I test it, gdb tells me it returns a int * variable.
Here is how my test goes:
#include <iostream>
#include <string>
using namespace std;
in... |
Is this answer correct?
It is a declaration of a function that returns reference to an array of 10 int.
gdb tells me it returns a int * variable.
No it doesn't. It tells you that the variable t that you created is an int * variable.
|
66,528,455 | 66,528,576 | What is a type field? | I am learning c++ .
Under the topic Type Fields My book states the following:
To use the derived classes as more than a convenient shorthand in the declarations, we must solve the following problem:
Given a pointer of type Base*, to which derived type does the object pointed really belongs? There are four fundamental ... | It seems the book is suggesting something like this:
struct FruitBase
{
protected:
enum class EFruit
{
Apple,
Plum,
};
FruitBase(EFruit type): type{type} {}
public:
EFruit type;
void prepare()
{
if(type == EFruit::Plum)
extractSeed();
else if... |
66,528,579 | 66,528,696 | What happened in the function convert(&m)? | Here is the code:
int convert(int* a) {
return (*a)++;
}
int main(){
int m = 56;
int n = convert(&m);
cout << m << endl;
m = convert(&m);
cout << m << endl;
return 0;
}
Why is the answer m=57 instead of m=58 after m=convert(&m)?
| The second call increments m to 58, but it returns the original value (57) due to the use of the post-increment ++ operator. That original value is then assigned back to m, overwriting the incremented value. The net effect is that m is unchanged.
You can verify this by adding some printouts to see the exact values in p... |
66,528,686 | 66,528,796 | Basic ODR violation: member functions in .h files | Disclaimer: This is probably a basic question, but I'm a theoretical physicist by training trying to learn to code properly, so please bear with me.
Let's say that I want to model a fairly involved physical system. In my understanding, one way of modelling this system is to introduce it as a class. However, since the s... | Normally, a class definition goes in an ".h" file and its member functions' definitions go in a ".cpp" file.
If you want to define member functions in the header, you need to either declare them inline, or write them inside the class definition (which makes them implicitly inline).
|
66,529,030 | 66,529,444 | How really distinguish compile time and run time information? | This question might seem broad, but it really isn't.
More specifically, if we are using templates, how do we distinguish what is compile time information and run time information?
I was watching CppCon video on the optimization and HFT systems and came across this example. If you are not familiar with high frequency t... | You're right on the general principle: at compile time, you won't know whether to sell or buy. That's going to take an if-statement.
However, the technique used there is still useful when the single if-statement to control buy/sell controls two large blocks of similar code. You can now write out those blocks explicitly... |
66,529,637 | 66,529,737 | How to prevent memory gaps in C++ new/delete? | This question is based on https://arduino.stackexchange.com/questions/81857/what-would-be-the-best-way-of-dynamically-change-instances-regarding-dynamic-m
I have a base class, and (possibly) many derived classes from it. I want to have 4 instances to those derived classes, but those instances change. E.g. assume derive... | You have to make sure that
You have enough memory to hold 4 instances of any derived types.
The memory alignment is suitable for all derived types.
Then you can allocate memory enough to hold 4 instances and use new(buffer) Type to construct the instances. Once you're done and want to switch the types, you call the d... |
66,530,237 | 66,530,484 | How to call constructor from templated baseclass | I have a library with classes I'm using. In my project, I have created a template, so that I can derive from a specialized class, but with my own methods included. Now I have the problem, that I can not call the constructor, which is different for each class I want to use.
I have created a sample project, which demonst... | You have to initialize the direct base class, you can't bypass Document and directly initialize TextCtrl.
The problem is, Document<T> has a no-arg constructor, but inherits from T which have no such constructor. Hence Document<T> can never be instantiated.
You can introduce inherited constructors into scope, then initi... |
66,530,525 | 66,530,782 | ifstreaming a file not working properly. Here is the code | In my program i am storing data given by the user in a .txt file with the help of ofstream.
I am using setw() to ensure proper gaping between the entered data and i am storing the data of a user in a single row. Here is the code for that:
string n,mn,fn;
int a;
cout<<"Enter your full name: ";
getline(cin, n);
cin.ignor... | If you read a file you don't have to specify that there is a gap in between values. Fstream does it for you. Any where there is spaces it won't read as one, for example the father's name Jack worn. It will only read Jack. Fstream reading has built in space delimited reading. So you will have to read the father's name a... |
66,530,624 | 66,530,665 | User input as argument in stack | What I'm trying to do is push user input onto stack using functions, since I have a switch-case menu and each case has it's own function(print stack, add onto stack..) Printing the stack works, user input works as well, but it seems that nothing is being added to the stack.
I'll show you the things I've tried so far:
v... | In such prototypes:
void addStack(stack<int> myStack)
The changes are made locally, and as soon as the function reaches the end, everything is discarded. For this reason, you may want to use a reference-to operator – so that you can change the actual value (which is passed as the parameter).
You can do that like this:... |
66,530,866 | 66,530,912 | Why isn't my class using the values I've given it? | In the process of trying to understand and use classes and methods, I have been trying to create a class with private values that uses a method to alter those values. I create a program that requests input from a user (a length and width) and creates a "rectangle" from those values (it just stores the values they input... | Rectangle(l, w); doesn't do what you think it does. It creates a temporary rectangle, which is then destroyed immedately.
Rectangle(l); also doesn't do what you expect. It's equivalent to Rectangle l;, which creates a rectangle named l using the 0-argument constructor.
You want *this = Rectangle(l, w);, or just assign ... |
66,530,908 | 66,530,946 | Should I use exceptions for checking valid input? | I am using gcc10.2, c++20.
I am studying c++ after 2 years of python.
In python we always did run-time check for input validity
def createRectangle(x, y, width, height): # just for example
for v in [x, y, width, height]:
if v < 0:
raise ValueError("Cant be negative")
# blahblahblah
How woul... | for (int v : {x, y, width, height})
if (v < 0)
throw std::runtime_error("Can't be negative");
Note that such loop copies each variable twice. If your variables are heavy to copy (e.g. containers), use pointers instead:
for (const int *v : {&x, &y, &width, &height})
if (*v < 0)
...
Comments al... |
66,530,923 | 66,531,841 | SWIG Python wrapper for std::optional<> | I am writing a C++ 17 library, and a python 3 wrapper with SWIG (4.0.2). Some of the functions in the library return an std::optional<> type. I've looking for a wrapper for C++17's std::optional<T> for python through SWIG, but I can't find any online that can help me with my T, an actual type (this T is not the same T ... | A first approach is the following. Assume you have a function called call_to_function with parameters ARGS (this could be int, int, or std::string) within a namespace library.
First, define and implement a template wrapper for std::optional<T>:
%{
template<class T>
struct LB__optional {
std::optional<T> m_opt;
... |
66,530,989 | 66,531,183 | Why this destructor affect my code and class objects but without it all work fine? | So i created a class along with 2 constructor, a function for print and a destructor.
I tryed to create 2 objects with different values and i encountered some issues with destructor.
I wrote 2 constructors so i can create objects in 2 different ways :
like this
myclass o1;
o1=myclass(..parameters..)
or like this
mycla... | The main issue you have is with:
myclass o1;
o1=myclass(vect,n);
Since your class doesn't respect the rule of three (or rule of five), when a temporary is created, it shares int *b;. Then, when the temporary is deleted, your b member is deleted.
From here, you an hack it away with:
myclass o1(vect,n); // no temporarie... |
66,531,225 | 66,531,890 | CMake add fmt library | I have a CMake project, with following structure:
cmake_minimum_required(VERSION 3.11)
project(ReadGraph)
# Download and unpack googletest at configure time
configure_file(CMakeLists.txt.in googletest-download/CMakeLists.txt)
execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" .
RESULT_VARIABLE result
... | CMake 3.11 introduced the FetchContent module for exactly this purpose: To download 3rdparty dependencies at configuration time and to build them as part of the project itself. So in order to use both GTest and FMT you can use
# While FetchContent only requires CMake 3.11, selecting C++20 through
# CMAKE_CXX_STANDARD r... |
66,531,482 | 66,532,115 | Application crashes when using address sanitizer with MSVC | I am trying to use address sanitizer with MSVC.
Visual Studio Installer says I have "Visual Studio Community 2019" version 16.9.0.
I have the most basic C++ program:
int main() {
return 0;
}
The CMakeLists.txt is also very basic:
cmake_minimum_required(VERSION 3.14)
project(untitled VERSION 1.0.0)
add_executable($... | ASAN is still an experimental feature in MSVC. For this reason the clang_rt.asan_*.dll DLLs are not installed in System32 as part of the VC++ redistributable package.
As explained here, when using ASAN in shared CRT mode (/MDd), you need to ensure clang_rt.asan_dbg_dynamic-x86_64.dll and clang_rt.asan_dynamic-x86_64.dl... |
66,531,536 | 66,531,610 | How to create a shared pointer with make_shared using the Object pointer passed into Function? | I create an instance of object and get a pointer to that then pass into a function. The function responsible for capturing that pointer and storing it inside an unordered_map.
I made several attempts to make it compile but none of them works.
#include <iostream>
#include <memory>
#include <unordered_map>
struct Foo {
... | Bar should take std::shared_ptr:
void bar(std::shared_ptr<Foo> foo) {
zoo.emplace("zilla", std::move(foo));
}
int main()
{
// Normal
auto foo = std::make_shared<Foo>();
foo->name = "Stackoverflow";
bar(foo);
}
|
66,531,987 | 66,607,656 | Copy vector (returned from a function) into a specific point of another vector directly at function call without needing extra temp variables [c++] | I have a function that returns a vector and I want all of that vector inserted into another vector at a specific point directly when calling that function.
What I would like to do is something like this:
#include <vector>
#include <iostream>
using namespace std;
typedef vector<double> Double1D;
Double1D myFunction(Do... | G'day, Alex from the past. This is you from the future. Here is how you solved it.
The function you want to use is a vector function called: insert() or a more efficient way that works for you is using copy() with back_inserter().
copy with back_inserter can only insert the vector to the back, whereas insert allows to... |
66,532,001 | 66,532,102 | Creating a 2-dimensional array with different sizes within a loop | The problem
I have an array of int's which vary in value called sizes. I want to create a 2d array (called arr) where the first dimension size is the length of the sizes array, and the second dimension's size is the value of the integer at that index. I hope the following code makes it easier to understand my question.... | C++ doesn't support jagged 2d arrays. A 2d array needs to have a size of N x M where N and M are both greater than zero.
Instead of using a 2d array, you can use a 2d vector to get this behavior like
std::vector<std::vector<int>> table;
for (auto size : sizes)
table.push_back(std::vector<int>(size));
|
66,532,135 | 66,862,531 | rotation and translation of object opencv | So i m working with opencv to find an object inside an image i have scene image and the object image i could detect the object with template matching but i need to give a rotation tolerance which is not avaible with template matching i m going to use feature 2D to detect features with findhomography and decomposehomogr... | I found the solution so I will post it
first of all the use of feature desciption algorithm is needed i choosed to work with SURF algorithm
after finding the object and the scene keypoints you need to find the homography matrix with findhomography after that you can calculate the angle using this code
float a = hom... |
66,532,537 | 66,544,804 | perf- how to get the current runtime clock of the program | I'm using perf tools to measure performance
with the commands:
perf record -F 99 -T -d -p $(pid_of_my_program)
perf sched script -v
and the result I got:
TimerTask 23652 544157.760762: 1 cycles: c0044606 finish_task_switch ([kernel.kallsyms])
TimerTask 23652 544157.760788: 1 cycles: ... | This answer assumes that you want to get the current timestamp at which the perf samples were recorded, and thus the times when the process tracked by perf was running.
The perf module uses sched_clock function to compute timestamps for an event. The timestamp that you see in the perf sched script command is actually r... |
66,532,576 | 66,533,011 | C++ std::vectors with predefined sizes | While taking a look at a solution for a problem, I came across this implementation of a vector.
const int MX = 100000;
std::vector <int> adj[MX];
The push_back() function doesn't work with this implementation of the vector class, and to add an element, the following code was used:
std::ifstream fin ("file.in");
int N ... | What you have is C style array of vectors, off the bat you could replace that with std::array:
std::array<std::vector<int>, MX> adj;
To loop through these you would have to use a nested one, the outer loop to go through the array, and the inner one to go through each vector, something like this:
const int MX = 3;
//a... |
66,532,769 | 66,533,090 | wrong output on printing subsets of array | I am trying to print all the subsets of an array. But not getting the correct output.
#include<iostream>
using namespace std;
int arr[]={1,2,3,4,5};
int n=5;
void print(int a[],int cnt, int idx)
{
if(idx==n)
{
for(int i=0;i<cnt;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
... | Replace the array with a vector. As the array in C++ is passed by reference, the print function is accessing the same array, which causes the problem.
#include <iostream>
#include<vector>
using namespace std;
int arr[]={1,2,3,4,5};
int n=5;
void print(vector<int>a,int cnt, int idx)
{
if(idx==n)
{
for(i... |
66,533,066 | 66,533,950 | Unable to populate ComboBox model with QVariantList | From QML:
AudioInfoCpp is the C++ class's object. Aim to to get data from C++ and fill it in the model of the combobox.
property ListModel comboModel: cbItems
AudioInfoCpp
{
id: audioInfoCpp
Component.onCompleted:
{
fetchInputDevices()
comboModel.append(inputDevices1)
console.log(in... | The problem comes from this line:
textRole: "langDescription"
That means it will look through each element in your model for the langDescription field. But you are populating your QVariantList with QStrings:
QVariantList tt;
for (const QAudioDeviceInfo& device : devices1)
{
tt.append(device.device... |
66,533,141 | 66,533,532 | Memory alignment of Armadillo vectors vec/fvec | I want to load __m256 directly from Armadillo vector data with .memptr().
Does Armadillo ensure the data memory is 256-bits aligned? If it is then I would just convert the float/double pointer returned by .memptr() to __m256 pointer and skip the _mm256_load_ps(), if it makes sense in terms of performance.
| The Armadillo do not seems to talk about this point in the documentation so it is left unspecified. Thus, vector data are likely not ensured to be 32-bytes aligned.
However, you do not need vector data to be aligned to load them in AVX registers: you can use the unaligned load intrinsic _mm256_loadu_ps. AFAIK, the perf... |
66,533,229 | 66,533,414 | How do I filter or output within an array if the number I searched for was not found? | I cannot output correctly when the number is not found in the array. I've tried multiple conditionals so it would only trigger when it is true. But nothing worked.
int main()
{
int abfrage;
cout << "Type a number between 0 and 1000 to find it's position in the array " << endl;
cin >> abfrage;
const int... | It looks like you have incorrectly combined two for loops. Currently, you set zahlenfeld[i] to a random number immediately before comparing it with abfrage.
You probably also want to allow the user to continue guessing until they choose a number that is in the array. So you can use a while loop to accept input multiple... |
66,533,314 | 66,534,939 | How to decrement a float variable until it's exactly zero | I am making keyboard controls for a camera, and I am experiencing issues regarding the innacuracy of floats. I have the variables "float Xvelocity" and "float Zvelocity", I increment these velocities by adding or subtracting the acceleration speed every time the respective direction keys are being held (A, D, W or S).
... | This is not a floating-point accuracy issue unless your acceleration, deltaTime, and velocity are calibrated so that, mathematically, velocity reaches zero exactly after an integer number of steps. More likely, the problem is simply that your velocity is not an exact multiple of acceleration/deltaTime, even allowing fo... |
66,533,665 | 66,533,718 | differences between capture by reference and by copy in lambda expressions | I am using Microsoft Visual Studio trying to run the following code:
#include <iostream>
#include <functional>
using depFunction = std::function<void()>;
class Man
{
public:
class BankAccount {
public:
BankAccount(double b, double d) : balance(b), dept(d) {};
protected:
double balance;
... | age and agePointer are local variables in the function deposit. When the lambda theFunc captures them by reference, those references are only valid while theFunc is used in the same scope as the function deposit.
When you return theFunc from deposit, those references to the local variables are dangling, and so you invo... |
66,533,818 | 66,536,167 | ASCII character 27 (left arrow) disappears when using the system() function in C++ | While writing a program I encountered a bug. When I don't use the system() function in my code, e.g. system("CLS"); character 27 (that is the left arrow in the ASCII code) is displayed correctly, but after using this function this character turns into an empty space. I should add that this does not happen with any othe... | The ← character in Unicode is codepoint U+2190 LEFTWARDS ARROW.
In codepage 437 (aka the DOS OEM codepage), for instance, byte 0x1B (dec 27) is used to display Unicode codepoint U+2190. See Console Code Pages for more details.
So, it is possible that maybe calling system("CLS") is resetting the current codepage of the... |
66,533,829 | 66,727,660 | Regex character class subtraction in C++ | I'm writing a C++ program that will need to take regular expressions that are defined in a XML Schema file and use them to validate XML data. The problem is, the flavor of regular expressions used by XML Schemas does not seem to be directly supported in C++.
For example, there are a couple special character classes \i ... | Okay after going through the other answers I tried out a few different things and ended up using the xmlRegexp functionality from libxml2.
The xmlRegexp related functions are very poorly documented so I figured I would post an example here because others may find it useful:
#include <iostream>
#include <libxml/xmlregex... |
66,533,885 | 66,555,210 | Replacement for pj_get_def? | I have an application that parses the output of pj_get_def that turns EPSG identifiers into some useful key/value pairs.
According to the migration guide, the replacement is proj_pj_info. However, the PJ_PROJ_INFO I get back has an empty definition and the description is an ambiguous (if human readable) string.
Here's ... | Well, the documentation is just wrong. The correct replacement isn't proj_pj_info, it's proj_as_proj_string.
There's a small caveat, however: in PROJ 4, this included the ellipsoid. In PROJ 6, it does not. If the ellipsoid is needed, an additional call to proj_get_ellipsoid (followed by another proj_as_proj_string) is ... |
66,533,962 | 66,534,061 | Why multiple function call not working in Opengl? | I'm try to use different function to make various object and call by one function like display() in my Opengl project. But It's not working, when I called two function then show me a function another one is not showing, I don't know why,
I have tried this way:
#include <windows.h> // for MS Windows
#include <GL/glut.h... | You are clearing the buffer before rendering each of the shapes, thus erasing the previous shape you just drew. Instead you should clear it only once per display. Same goes with glFlush:
void box() {
// Draw a Red 1x1 Square centered at origin
glBegin(GL_POLYGON);
glColor3f(1.0f, 0.0f, 0.0f); // Red
glV... |
66,534,093 | 66,534,256 | Set giving extra element | I'm doing some rather simple code with set
#include <iostream>
#include <map>
#include <string>
#include <set>
using namespace std;
void printSol(map<string, string> parelles, const set<string>& sols) {
cout << "COUPLES:" << endl;
for (auto& x : parelles) {
cout << x.first << " " << x.second << endl;
... | The map::operator[] strikes again. This operator inserts a value-initialized element if the key doesn't exist in the map. For string, this means it will insert an empty string. Here's a fix:
// sols.insert(parelles[nom1]);
// sols.insert(parelles[nom2]);
auto it = parelles.find(nom1);
if (it != parelles.end()) sols.i... |
66,534,397 | 66,534,971 | When using either default capture mode, is this captured by copy or (*this) captured by reference? Is it the same thing? | I was a bit puzzled when I saw the following working
struct A {
void g(){}
void f(){
[&](){ g(); }();
}
};
but then I found this answer which explains in quite deep detail how that works.
In essence, it boils down to this is captured by value whether you use [=] or [&].
However, on cppreference I r... | The first interpretation was the intent prior to C++17 (when that answer was written), but the second is the intent since (as reflected by the ever-current cppreference). Originally it was considered that this (the pointer) was the subject of the capture, and it is of course impossible to do so by reference (as pointe... |
66,534,637 | 66,534,991 | Efficiently calculate mean in a large C++ array | I have a data set of 65K samples in 7 blocks: float arr[7][65536] I need to calculate the mean for each corresponding 7 numbers so the result will be an array of size 65536:
float result[0] = arr[0][0] + arr[1][0] + arr[2][0] + ... / 7
float result[1] = arr[0][1] + arr[1][1] + arr[2][1] + ... / 7
The problem is that a... | One simple solution is to walk through the contiguous dimension. However, if sizeof(arr[0][0]) is quite big, this may not be optimal as result will not fit in the L1 cache. The optimal solution is probably to use blocking to solve this issue.
Here is a C++ example code to do that:
// Blocked reduction using blocks of s... |
66,534,771 | 66,535,361 | Convert Linux Debian gcc command to CMakeLists.txt | I hope the question is not too trivial, but I am trying to convert a gcc command into a CMakeLists.txt. Unfortunately I am failing at understanding the basics and I hope you can help me.
My main reason for wanting to do this is that I'm building the whole thing on a Raspberry and it has quite a few performance problems... | You can use SET() to set the compiler flags. Check the CMake documentation
You can set the CMAKE_CXX_FLAGS to the flags you want to pass to the compiler
|
66,534,983 | 66,535,059 | Alias for a specific symbol within a namespace? | I would like to use specific symbols from a namespace with short syntax, but without resorting to using namespace <xyz>; as that brings in all symbols to the current scope. For example, the idea (that doesn't compile) would be something like:
#include <iostream>
using cout = std::cout;
using endl = std::endl;
cout << "... | Yes there is a possibility, you can simply write:
using std::endl;
using std::cout;
|
66,535,707 | 66,591,790 | QTableWidget: Prioritize horizontal space for a specific column | I have a QTableWidget that has a column (#3) that needs more space than others. I want to resize all columns to their contents, and give priority to column #3. If column #3 pushes the table's width past what's available, I want column #3 to be truncated with '...' without a horizontal scrollBar.
The screenshot below ... | This should work, try it out
#include <QApplication>
#include <QTableWidget>
#include <QStringList>
#include <QRect>
#include <QLayout>
#include <QDialog>
#include <QHeaderView>
#include <QScrollBar>
#include <iostream>
int main( int argc, char* argv[] )
{
QApplication a(argc, argv);
QDialog* d = new QDialog();
d->s... |
66,535,719 | 66,588,185 | Boost.Test linker error by use with precompiled headers (PCH) | I have a linker error when using Boost.Test with precompiled header (PCH) that does not occur without PCH. I use the dynamically linked library as described in Usage variants.
How can I fix the error to use Boost.Test also with PCH?
The problem occurs at least with Fedora and boost 1.73 (has only dynamic libraries) and... | Alan Birtles got the hint into the right direction. I was not aware of the influence of the compiler switch BOOST_TEST_DYN_LINK for the single file in the context of PCH here. A definition for all files of the project in the style of:
target_compile_definitions(${PROJECT_NAME} PRIVATE
"BOOST_TEST_DYN_LINK")... |
66,535,803 | 67,794,341 | Find the name of the Imported DLLs using PE Headers | A Few days back I have started with Windows System Programming using c++. Hence, thought of building a utility to grab the PE Headers of an exe file.
And now I am stuck with the Image_Import_descriptor structure.
What I want is to get the names of the DLL files(modules) imported by the exe. And below is the code I am u... | Got the technique from 'ired' security blogs. Below is the working code.
HANDLE h_File = CreateFile(L"testing.exe", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (!h_File) {
printf("\nERROR : Could not open the file specified\n");
}
//Mapping Given EXE file to Memory
HANDLE ... |
66,536,039 | 66,536,655 | Please confirm the best way to Restore the DC when a custom Pen and a custom Brush are selected | Can someone confirm if this sample code from Microsoft fails to restore the custom brush set with SetDCBrushColor?
case WM_PAINT:
{
hdc = BeginPaint(hWnd, &ps);
// Initializing original object
HGDIOBJ original = NULL;
// Saving the original object
... |
Did Microsoft forget to use SelectObject with a previously saved
version of the original brush?
I would say: Yes, they did!
In the case of the SetDCPenColor call, there isn't a problem, as restoring the original (saved) pen will revert the changes made. It seems that the example forgets to save (and subsequently rest... |
66,536,668 | 66,536,713 | C++ vector push_back() function only changing last value | I am new with C++, so sorry if the question is too simple. I am trying to append a double value to a double vector in iteration (fired by a timer). The function that is called in iteration is the following:
void cMain::update_vector(vector<double> vtr, double value) {
vtr.push_back(value);
}
The callback of the ti... | void cMain::update_vector(vector<double> vtr, double value) {
vtr.push_back(value);
}
This passes vtr by value (i.e. a copy is made passing it to the function), then you push a value onto this copy, and finally it goes out of scope which deletes the copy.
It looks like what you are trying to do is add a value to a... |
66,536,755 | 66,543,929 | VS 2019 C++ compiler cant compile some strings | I have some strange and stupid situation. I have this part of code:
FString x = TEXT("ааааааа");//Russian language (line 54)
Caesar* ciph = new Caesar;// (line 55)
When I try to compile my project, I have such errors:
../Widget_Manager.cpp(54): error C2001: newline in constant
../Widget_Manager.cpp(55): error C2146... | To solve compilation problem, I
File -> Save as -> near save button arrow -> Save with encodig -> Choose UTF-8
|
66,537,510 | 66,537,675 | Can an std::vector<float> resize itself to a smaller size? | SharedConsumableRotatingBuffer(std::optional<size_t> maxBufferSize_) {
if (maxBufferSize_.has_value()) {
ALOGV(TAG, "SharedConsumableRotatingBuffer resizing buffer to %zu", maxBufferSize_.value());
buffer.resize(maxBufferSize_.value());
ALOGV(TAG, "SharedConsumableRotatingBuffer buffer size:... |
Can an std::vector<float> resize itself to a smaller size?
Yes. If you provide a smaller argument than the current size of the vector to resize, then the size of the vector will be set to that smaller value i.e. elements will be removed.
Sidenote: that the capacity will remain unaffected by resize unless the size gro... |
66,537,761 | 66,538,131 | How to access different arrays of different types with a unique scoped enum? | I have 2 structs (ScreenN and ScreenR) inheriting from a base struct (Screen). They just have POD data with no members.
struct Screen {
int base {10};
};
struct ScreenN : public Screen {
int spe_n {20};
};
struct ScreenR : public Screen {
int spe_r {30};
};
A Test class containing 2 arrays of structs :
class Test... | So what you want is to have getScreen return a different type based on a runtime parameter (the enum)? Is that correct?
That's not how C++ works; it's a statically typed language. Each function has a single return type; and that type is determined at compile time.
Now, as to what you've tried:
Templates - these stamp ... |
66,538,117 | 66,538,417 | Can you have a vector of templated objects with different template types? | I am wondering if there is a way to have a vector of templated objects with different template types
example
template<class T>
class object
{
public:
void function()
{
}
};
int main()
{
std::vector<object> v;
v.push_back(object<int>());
v.pus... | Others can correct me if I am wrong but I think you have 3 options.
Use a Variant. You don't provide a lot of details but if you cannot live with a defined set of possible values this may be too limiting.
Use inheritance/polymorphism. You could declare some virtual class and have all your stored object implement that... |
66,538,400 | 66,539,204 | How to get at a C++ Container<T>'s T if no Container::value_type is provided? | It's rather common that container templates contain a value_type typedef. This makes it easy to create other templated code, most recently concepts, which are able to extract the T if only having been given Container and not Container<T>.
However, not all containers (or other templated classes) define such a value_type... | Here's a solution that's similar to Quimby's solution but using partial template specialization instead:
template<typename...>
struct inner_type_impl;
template<template<typename...> typename C, typename T, typename...Args>
struct inner_type_impl<C<T,Args...>>
{
using type = T;
};
template<typename T>
using inner_... |
66,538,452 | 66,538,587 | the call to "conclusionaryOutput(number1, number2, isASquare1, isASquare2)" is throwing an error and I'm not sure why | The purpose of this program is to accept two numbers from the user, and figure out the two inputted numbers' factors and if they have any factors that are squares.
When I try to run it, it throws an error on the function call of conclusionaryOutput():
[cquery] address of function 'listSquares' will always evaluate to
... | When you call your conclusionaryOutput function (at the end of squareInquiry) you must give it the names of actual variables in the calling module rather than use the names of the parameters given in the function's definition. (This may be a basic misunderstanding of function calling in C++ because, everywhere else in ... |
66,538,493 | 66,538,652 | Pointer to member type incompatible with object when calling member function pointer | Problem
I have an array of member function pointers that I assign at run-time. I am getting a compile-time error when attempting to call them:
pointer to member type 'void (YCPU::)(uint16_t)' {aka 'void (YCPU::)(short unsigned int)'} incompatible with object type 'YCPUInstruction'`
I'm having trouble understanding th... | The left operand of .* must refer to / the left operand of ->* must point at an object of the member function's containing class. The right operand can be any expression which gives the pointer-to-member value.
The containing class of the member functions you're using is YCPU, so it's not correct to have the YCPUInstru... |
66,538,658 | 66,608,800 | Lexicographic Rank of a Set Partitioned Into Groups | Given a set of 8 sequential numbers {0..7} partitioned into 4 groups of size 2, with the numbers in each group in ascending order, how can a rank be generated for the set? The rank should be in lexicographic order, and preferably the algorithm should be linear in complexity.
Examples of the partitioning:
{{0 1} {2 3} ... | Here's what I came up with. It's quadratic in complexity, which is not the greatest, but it does the trick. The basic algorithm is as follows.
Given a set of sequential numbers from [0..7] partitioned into unordered pairs, loop over each pair and find its rank among pairs that
exclude numbers preceding it. Then mult... |
66,538,989 | 66,539,130 | Defining an enum in C++ class definition: ‘MyEnum’ has not been declared | I'm attempting to both define and use an enum in a C++ class definition, but I get the following error:
error: ‘myEnum’ has not been declared
MyClass.h
#ifndef MyClass_H
#define MyClass_H
class MyClass
{
public:
MyClass();
~MyClass();
enum myEnum
{
A = 0,
B = 1,
C = 2
};
int ... | If you are using a C++98 compiler, you cannot use the enum::x syntax. The :: scope resolution operator is only defined for namespaces and classes in C++98. Enumerations were added in C++11. See here
A qualified id-expression is an unqualified id-expression prepended by a scope resolution operator ::, and optionally, a... |
66,539,099 | 66,539,157 | How to get the "raw" ptr of a lambda *capture* function | I want to make a C++ assembly hooking using lambda captures but for this i need to get the pointer of a lambda capture function.
something like this:
int val0 = 42;
auto lambdaCap = new auto([&]() -> int { return val0++; });
uint64_t pLambdaFn = static_cast<uint64_t>(&decltype(*lambdaCap)::operator()); // need this
I ... | &decltype(*lambdaCap)::operator()) is not valid because decltype(*lambdaCap) is actually an lvalue reference to the closure type.
Instead, std::remove_pointer_t<decltype(lambdaCap)> would give you the closure type itself. So you can write &std::remove_pointer_t<decltype(lambdaCap)>::operator() to get the pointer-to-mem... |
66,540,314 | 66,547,640 | My attempt at netcat in C++ won't get me replies from the server | I've made my attempt at netcat in a C++ program that uses sockets. It seems to be able to generate the socket, connect, and maybe send data fine but there seems to be an error I can't find. It doesn't properly return replies from the server. I'm able to connect to my HTTP server and scanme.nmap.org fine, but whenever I... | The real netcat can read from socket and from stdin in parallel. Your program can read either from stdin or from the socket and both of these calls getline() and recv() are waiting of there are no data.
So your program probably:
getline() reads a line from stdin. The line contains something like "GET ... \n"
send the ... |
66,540,931 | 66,541,020 | Can anyone explain this Image Resolution Setup code? Exactly what is going on here | I'm trying to understand someone else's code for raw image management.
Here's what I'm looking at:
// Resolution has to be a power of 2.
// This code finds the lowest RxR resolution which has equal or more pixel than requested
uint32_t higher = std::max(resolutionX, resolutionY);
higher--;
higher |= higher >> 1;
highe... | A number which is one less than a power of two is all 0 bits on the left and all 1 bits on the right (e.g. 1112 = 7, 111111112 = 255).
The sequence of |= operators will make sure that for any set bit in the input, all of the bits to its right will also be set — first, copy each bit right by 1, then copy each pair of bi... |
66,540,937 | 66,541,170 | How to compress/decompress buffer using Fast-LZMA2 | I want to compress/decompress a unsigned char buffer using fast-LZMA2 by 7Zip : https://github.com/conor42/fast-lzma2
In the sample there's two function :
static int compress_file(FL2_CStream *fcs)
{
unsigned char in_buffer[8 * 1024];
unsigned char out_buffer[4 * 1024];
FL2_inBuffer in_buf = { in_buffer, s... | Check the header file for all of the functions available. This one looks like the one you need. You will need to cast your buffers as (void *).
High level functions
fast-lzma2.h
...
/*! FL2_compress() :
* Compresses `src` content as a single LZMA2 compressed stream into already allocated `dst`.
* Call FL2_compressM... |
66,541,147 | 66,541,193 | Trying to create a function that passes a 2d array outputs array in a table format (similar to tabulate from python3) | So I'm trying to create a function that takes a 2d array as input along with Rows and Cols variables and output the contents of the array in a table format. This is what I have so far
#include <iostream>
using namespace std;
void Tabulate(int *x[][], int xRows, int xCols) {
for (int i = 0; i < xRows; i++) {
for ... | You are trying to pass a 2D array to a function. In that case either your array should be dynamic or one dimension constant.
Use this:
void Tabulate(int **x, int xRows, int xCols) //dynamic array
See more details/method here(there are some really great answers here): Passing a 2D array to a C++ function
|
66,541,211 | 66,541,461 | What does the : Operator mean in C++ inheritance? | I have been reading up on inheritance in C++ and noticed that
class Car: public Vehicle {
public:
string model = "Mustang";
};
You used a ":" operator before the defining the child class, however I couldn't find what this means.
Is it just something we should know to use but not how it works or what it does?
| The single colon could also signify class inheritance, if the class declaration is followed by : and a class name, it means the class derives from the class behind the single colon.
class InheritedClass : public BaseClass.
|
66,541,263 | 66,541,498 | std::vector that can be consumed fast | I'd like to be able to consume parts of a buffer until it's empty. I designed my own below, but I'd like to know if there is such thing in the std library already, so I remove the possibilities of implementing my own wrong.
Note that I use std::vector<T> only for automatic storage. I don't do push_back to insert and po... | I think you can take advantage of using dequeue from STL.
It implements a doubly linkedlist in which you can read from one side and write from the other side of it. Check this link for more detail explanations.
Also the other best implementation for a buffer is a circular buffer implementation.
I leave a C++ implementa... |
66,541,465 | 66,541,494 | Can references be reassigned? | My understanding was that references, once assigned, could not be reassigned after. However, in A Tour of C++, Stroustrup has this bit of code:
int x = 2;
int y = 3;
int& r = x;
int& r2 = y;
r = r2;
This seems to imply that the reference r can be reassigned after its initial assignment. Is the rule just that reference... | No there is no reassignment for the references here. Just the value of y which is referenced by r2 is assigned to x which is referenced by r.
To handle this situation, think of the reference as an alias of the variable it references. when you put the reference anywhere you are putting the variable itself.
You can make ... |
66,541,480 | 66,543,874 | How to get OpenMP to work with #pragma omp task? | I'm using OpenMP with Linux terminal. I compile my program with the flag -fopenmp. The environment I'm using does support multithreading.
#pragma omp parallel num_threads(3)
{
#pragma omp task
R11Inverted = compute_inverse(r11, half);
#pragma omp task
printf("5 I am threa... | You are missing the {} around the block of code and also the single clause.
Try the following:
#pragma omp parallel num_threads(3)
{
#pragma omp single
{
#pragma omp task
R11Inverted = compute_inverse(r11, half);
#pragma omp task
{
printf(... |
66,541,940 | 66,546,379 | Dockerfile: Does it matter how I clean my build? | Is there a difference (when it comes to image size) between
RUN make && make clean
and
RUN make
RUN make clean
Not sure how Docker works, but will the latter create an unnecessary layer?
| RUN make clean as a separate step will never make your image smaller than skipping it entirely. If you're going to run it, run it in the same RUN command as the build.
More generally, each RUN command creates a new Docker image layer. Creating the layer in itself isn't expensive, but the resulting image is all of the... |
66,542,258 | 66,542,381 | Preprocessor variable for armhf c++ |
Such a question: how can I determine that the code is running on a computer that has an armhf processor?
I know that for ARM64 there is a preprocessor variable __aarch64__ and I can do something like this:
#if defined(__aarch64___)
...
#endif
Is there the same variable for armhf?
| A command similar to this one lists all the predefined macros of your compiler (of course, you have to replace g++ by your actual compiler for the specific target, and add the specific options for this target).
echo | g++ -dM -E - | sort
You will certainly detect some explicit enough names you can test with #if define... |
66,542,474 | 66,542,629 | Using a callback to consume data from std::vector<uint8_t> | Based on the previous answers, I wrote a better buffer that can be consumed fast:
#include <iostream>
#include <vector>
#include <functional>
#include <stdio.h>
#include <string.h>
using namespace std;
template <class T>
class Buffer
{
public:
Buffer(size_t reserve) {
_buffer.reserve(reserve);
}
... | You are capturing your array by value.
Capturing by reference will give you the expected result.
size_t consumedBytes2 = b.consume(3, [&r](const uint8_t* begin, const uint8_t* end){
std::cout << "begin: " << begin << ", end: " << end << std::endl;
std::copy(begin, end, (uint8_t*)r);
});
Capturing a pointer by ... |
66,542,558 | 66,542,578 | C++ vector as class member vs in function | When I am using vector as following in a function, I get a variable D and it works.
vector<int> D(100);
However, when I decide to use this as a class member, I get the following weird error :
error: expected identifier before numeric constant
99 | vector<int> D(100);
| ^~~
Could someon... | Default member initializer (since C++11) for member variable only supports equal-sign initializer (and braced-initializer, which doesn't match this use-case).
Through a default member initializer, which is a brace or equals initializer included in the member declaration and is used if the member is omitted from the me... |
66,542,582 | 66,543,197 | C++ program doesn't output when I run on cmd or VScode (but on repl.it it does) | I have this C++ program I wrote that sums vectors:
#include <cmath>
#include <iostream>
using namespace std;
const float half_Pi = acos(0.0);
double *vectorSum(double *lengths, double *angels, int size, bool cartazian) {
double Cx, Cy, *res;
for (int i = 0; i < size; i++) {
Cx += cos(angels[i] / 90 * half_Pi... | The function vectorSum has undefined behavior due to the uninitialized pointer res which you are assigning data to as if it points to valid memory.
Note that you also have undefined behavior because you don't initialize the values Cx and Cy, but then start adding to them.
A naive fix for the first issue would be to all... |
66,542,797 | 69,604,600 | Is there a way to query direct module dependencies with gcc? | Given a module
// a-m.cc
export module A;
import B;
import C;
import "D.h";
...
Is there a way of invoking gcc (similar to what -M does for headers) that will list the direct dependencies on other modules and imported headers (i.e. B, C, and "D.h")?
| [Edit]
It seems we can invoke gcc with the flag -MMD, which also tracks module dependencies. Given an example project I have, I generated it like this:
// partition.cpp
export module partition;
import :partition1;
export import :partition2;
export import :partition3;
export void Hello1() { _Hello1(); }
For some reas... |
66,542,895 | 66,543,387 | Is it safe to pass a shared pointer using std::ref? | I need to pass the shared pointer containing context object to callback function without moving ownership as all context objects are stored inside unordered_map.
I use std::ref to pass the shared pointer into call back function from parent function.
main -> get shared pointer from map -> parent function (accept shared ... | No, in your implementation it is not safe. In this code:
void HTTPTransport::handle(const evpp::TCPConnPtr &socket, std::shared_ptr<Connection> context) {
ws->onMessage(std::bind(&HTTPTransport::handleMessage, this, std::ref(socket), std::ref(context), _1));
}
context is a local variable so storing a reference to ... |
66,543,163 | 66,543,289 | Can't I use operator ""sv for the parameter of fstream()? | #include<iostream>
#include<fstream>
using namespace std::literals;
int main()
{
auto a = "st"sv;
std::ifstream in("test.txt"sv, std::ios::in); //error C2664
std::ifstream in("test.txt"s, std::ios::in);
}
I'm using visual studio. Can't I using the string-view literal ""sv on fstream? or Am I have to se... | No. You can't.
You can't use it because there is no ctor for std::ifstream that accepts an std::string_view ref
and there is no implicit conversion between std::string_views and the types if_stream accepts, hence you have to make a conversion using staic_cast or the constructor of std::string
If you have an std::strin... |
66,543,301 | 66,544,471 | Does CMake take more memory than normal setup? | I am just curious that: Does CMake take more memory than VS Code run & debug setup? and normal sln projects?
I recently checked that the size of the file is 4.18 MB, but the disk usage is 188 MB.
why?
| CMake is tool build, testing and packaging automation tool. It is not a compiler!
The final executable size or performance does depend on the compiler, so it is independent of CMake (however not independent of what you setup in your CMakeLists.txt).
Why is your executable bigger while using CMake than Microsoft Visual ... |
66,543,312 | 66,543,490 | C++ valarray vs array size allocation | I am allocating a multidimensional valarray of size 2000x2000 and it is working smoothly.
valarray<valarray<int>> D(valarray<int>(-2,2000), 2000);
D[1999][1999] = 2000;
However, if I try to allocate a normal array and access an element, I get segmentation fault.
int A[2000][2000];
A[1999][1999] = 2000;
Both are on th... | Like std::vector, the underlying storage of std::valarray is dynamic, and the size of the object that manages this storage does not depend on the number of elements.
This program:
#include <iostream>
#include<valarray>
int main() {
std::cout << "sizeof(std::valarray<std::valarray<int>>): "
<< sizeof... |
66,543,568 | 66,548,947 | How to implement Palette type for different platforms in QML | So at the moment I have 3 Qml types:
ThemeToUse.qml
QtObject {
property Palette palette: Palette {}
Component.onCompleted: {
if (themeContext) {
palette = themeContext.palette
}
}
}
Palette.qml
QtObject {
property color WindowsColor: "red"
}
BaseTheme.qml
QtObject {
pro... | I recommend using a QQmlFileSelector. It will allow you to add different versions of any qml file, based on platform or any other selector string that you choose.
Let's say I have a file called MyTheme.qml. And let's say, I want that file to look different if I run on Windows vs Android. My directory structure would lo... |
66,543,846 | 66,545,637 | Strange behaviour when I am trying to implement my linked list in c++ | I'm trying to implement my singly linked list , and I have this problem:
When I'm trying to pushBack some elements in my linked list , it will print only the first one which I added.For example , if I try to pushBack 2,3,4 - it will print only 2.
In case if I want to pushUp some elements in my linked list , it will pri... | You are missing edge cases. When you add the first node you are pointing it via head and tail ok but then you should check if there is only one node by comparing the address. And you should consider it for both function because if there is only one node head tail will change or head will be overwritten in your code.
... |
66,544,408 | 66,545,039 | How to call an overloaded operator from a nested class inside parent in a header file? | I have an enum class E nested in class C. I want to use it as bit flags, so I overloaded its operators.
My class C contains function test() which makes use of overloaded operators. Because it is only two lines long, it is located in the header file to be inlined. However, this function does not call the overloaded oper... | class C {
public:
enum class E {
e2 = 2,
e4 = 4
};
const E e;
C(E e) : e(e) {}
inline void test(E e); // function must be inline
};
// Flag active
inline bool operator==(C::E lhs, C::E rhs) ...
// implement later
inline void C::test(C::E e) {
// do stuff
}
I can't think of ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.