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 |
|---|---|---|---|---|
69,516,690 | 69,516,912 | Matlab and Eigen eigenvectors differ only by the sign | I am working with a project which consists in translating Matlab code to C/C++.
At one point I have to calculate the eigenvectors of a matrix, in Matlab this is done using the eig function while in C++ I use EigenSolver from the Eigen library.
The problem is that some eigenvectors (apparently random) have the opposite ... | According to the documentation of eig, the sign of the eigenvectors is not guaranteed to be consistent between MATLAB releases and/or machines used:
Different machines and releases of MATLAB® can produce different eigenvectors that are still numerically accurate:
For real eigenvectors, the sign of the eigenvectors ca... |
69,517,158 | 69,517,205 | Trouble with GLSL dot product | So I was trying to implement basic diffuse lighting using OpenGL. I wrote a simple shader that would take a normal vector and a light vector and calculate the brightness of a pixel using the dot product of said vectors. Here are my outputs:
Light coming from the left ([1, 0, 0] as light vector)
Light coming down ([0,... | The diffuse light is calculated using the formula max(dot(-lightDir, normal), 0.0f);. So if dot (-lightDir, normal) is less than 0, the scene is completely black.
The Dot product of 2 Unit vector is the cosine of the angle between the 2 vectors. Hence, if the angle is > 90° and < 270° the result is less than 0.
This me... |
69,517,191 | 69,533,886 | CMake - Create executable for all *.cpp file in folder | I have this folder tree:
benchmark/
├─ pair/
│ ├─ benchmark_create.cpp
│ ├─ benchmark_insert.cpp
│ ├─ benchmark_remove.cpp
├─ set/
├─ CMakeLists.txt
And this is my current CMakeLists.txt file content:
add_executable(dbg_pair_creation pair/benchmark_creation)
target_link_libraries(pair_creation benchmark::benchmark)... | You could use a foreach loop.
set(benchmarks creation insert remove)
foreach (benchmark IN LISTS benchmarks)
add_executable(dbg_pair_${benchmark} pair/benchmark_${benchmark}.cpp)
target_link_libraries(dbg_pair_${benchmark} PRIVATE benchmark::benchmark)
set_property(
TARGET dbg_pair_${benchmark}
PROPERTY R... |
69,517,456 | 69,517,646 | How can I check(checkV) if a value exists in Binary search tree if does I output "true" else "false" | How can I check(checkV) if a value exists in Binary search tree if does I output "true" else "false"
void search(Node* root, int checkV){
if(checkV > root->data){
search(root->right, checkV);
}
if(checkV < root->data){
search(root->left, checkV);
}
if(checkV == root->data){
... | If you need to use function "search", then first you should check if root points the nullptr, then if you found data and only after that you should search. Something like this:
void search(Node* root, int checkV) {
if (root->data == nullptr) {
cout << "false" << endl;
}
else if (checkV == root->dat... |
69,517,663 | 69,517,832 | Correct parameter char *[] to call function? | I am trying to implement bubble sort the function bubbleSort(names, size) and test it with my driver code. I get error on the driver code when I call the function. I would like to know how to set the first parameter correctly when I call the function.
I get two errors which is related to the first parameter "names".
E... | Your sort function wants an array of C-strings, but you are passing it an array of characters. Hence the error.
To sort an array of characters, try this:
#include <iostream>
using namespace std;
void bubbleSort(char names[], const int size)
{
bool swapped;
char temp;
for (int i = 0; i < size; ++i)
{
... |
69,517,813 | 69,517,948 | Iterate a string until int or char | I want to make to two vectors from a string.
from :
std::string input = "82aw55beA1/de50Ie109+500s";
to :
std::vector<int> numbers = {82,55,1,50,109,500};
std::vector<char> notNumbers = {'a','w','b','e','A','/','d','e','I','e','+','s'};
How do I do this in the most efficient time complexitie?
| You can make one pass over the string. You need to know if you're currently parsing a digit or not, whether you're "in" a number, and the current number you're in.
It's a pretty straightforward process, but if you have questions, please ask.
#include <string>
#include <vector>
#include <iostream>
#include <cctype>
int... |
69,517,845 | 69,517,921 | LEAKER: errors found! memory was not deallocated | I keep getting the same error:
LEAKER: errors found!
Leaks found: 2 allocations (48 bytes).
unknown:unknown():0 memory leak: memory was not deallocated.
unknown:unknown():0 memory leak: memory was not deallocated.
I keep checking my destructor and my Clear() function, but I can't figure out what I am missing. I know I ... | This is a lot to digest, but at least one source of error here is likely that you have
class LinkedList
{
...
private:
Node* head = new Node; // Node pointer for the head
Node* tail = new Node; // Node pointer for the tail
unsigned int count;
}
And then in your constructor
LinkedList<T... |
69,517,879 | 69,522,013 | Install tesseract + openCV Cmake C++ | I've been trying to install Tesseract under OpenCV for a very long time now.
Earlier I built OpenCV using CMake-gui and connected Contrib successfully. Now I can use add. libraries.
I have cloned tesseract and leptonica repasitories.
And I tried to connect it in the same way as Contrib, but nothing came of it .... I al... | Is tesseract build included in opencv, or can you use already installed tesseract ?
I strongly suggest to use the latest tesseract (a.k.a 5.0) (even not released yet) - there is plenty improvement and fixes especially for cmake build. AFAIK API calls are the same as in 4.x, so when you COMPILE opencv against it, it sho... |
69,517,894 | 69,518,411 | Cannot play mp3 with mciSendString in C++ console application | I'm trying to play an mp3 file from a win32 C++ console application. From what I've read online, mciSendString is the API I'm looking for, and I expected the following to work but it doesn't.
#include <cstdio>
#include <array>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <mmsystem.h>
using namespace std;
... | Your program is ending after you invoke the mci command. The music is going to stop playing when the process exits.
Simply add something to the end of the program to keep it from exiting.
Instead of this:
std::printf("%s\n", errorString.data());
}
This:
std::printf("%s\n", errorString.data());
printf... |
69,517,949 | 69,518,007 | I have a problem with array pointers (c++) in therms of functions | I'm new to pointers, and want to learn them.
I created a script that should adopt Python's len() function for arrays to get the size of them for learning reasons. So I wrote the following code:
int len(int *arrPtr){
int arrSize = *(&arrPtr + 1) - arrPtr;
return arrSize;
}
int main(){
int arr[] = {1,2,3,4,5... | This is how you can handle array sizes :
#include <array>
#include <iostream>
//using namespace std; // don't do this.
template<std::size_t N>
void function(const int(&arr)[N])
{
std::cout << "std::array from function, len = " << N << "\n";
std::cout << "arr[2] = " << arr[2] << "\n";
}
void function2(const st... |
69,518,014 | 69,518,050 | Problem with some hidden == operand when erasing shared_ptr from a vector | I wrote this AddressBook program in C++ as an exercise, and everything works fine except the removeContact method.
The compiler (MSVC) reports an issue related, I think, to some sort of incompatible right operand with a == operator.
Here's the compiler output:
error C2679: binary '==': no operator found which takes a r... | std::erase takes a value which is searched in your container and then removed, not an iterator.
Therefore trying to pass an iterator there triggers an error because std::erase is trying to compare your container elements with this iterator, but iterators and elements are normally not comparable.
To erase an element you... |
69,518,490 | 69,518,582 | Generic Linked List error: LinkedList is not a class template | // This is the Node.h file
#ifndef NODE
#define NODE
template <typename T>
class Node
{
private:
T elem;
Node *next;
friend class LinkedList<T>;
};
#endif // NODE
This is the LinkedLilst.h file
#ifndef LINKED_LIST
#define LINKED_... | You need to forward declare the LinkedList class template:
#ifndef NODE
#define NODE
template<class> class LinkedList; // <- forward declaration
template <typename T>
class Node
{
private:
T elem;
Node *next;
friend class Linked... |
69,518,605 | 69,718,949 | VS Code - automatic namespace name generating | When I format my C++ code, it automatically adds comment with name of the namespace at the end of the namespace. How to turn off this automatically generating namespace comment at the end of the namespace in VS Code ?
Example of my code:
namespace test {
int add(int a, int b) {
return a + b;
}
} // namesp... | If you're using the C/C++ extension with a recent version of clang-tidy, then they should be turned off by default. It's controlled by the clang-format setting FixNamespaceComments: false. It's possible you're using using another extension to format your code which doesn't have that default or your other clang-format s... |
69,519,227 | 69,520,140 | How to calculate all generated permutations correctly and recursion included? | I am currently working on a little program that's supposed to find every combination.
Fill the
following place holders with digits in the range from 1 to 9. Each digit only appears once and make the
equation sum up to 100.
_ / _ * _ + _ * _ * _ / _ + _ * _ = 100
#include <bits/stdc++.h>
#include <cmath>
using namespac... | As PiedPiper already mentioned about the integer division issue, you can simply declare the arr[] as double and it solves the issue.
As an extension, you can also calculate the permutations using a recursive way. Please check the function findCombosRecursive() which have similar functionality as findCombos() but making... |
69,519,672 | 69,519,771 | 2 int8_t's to uint16_t and back | I want to support some serial device in my application.
This device is used with another program and I want to interact with both the device and the save files this program creates.
Yet for some yet to be discovered reason, weird integer casting is going on.
The device returns uint8's over a serial USB connection, the ... | Your encode method can just be an assignment. Implicit conversion between unsigned integer types and signed integer types is well defined.
uint8_t val_1 = 255;
int8_t val_2 = val_1;
REQUIRE(-1 == val_2);
As for combine - you'll want to cast your first value to a uint16_t to ensure you have enough bits available, and t... |
69,519,732 | 69,519,843 | Make new instance of the template class of a c++ object | So if I have
template <class T>
class Object {
// stuff
};
and I receive an instance of object in a function I want to call the constructor of class T.
void foo(Object object) {
auto newT = object::T();
}
Is this possible?
| Typically the best solution is to template the inner type:
template <class T>
void foo(Object<T> object) {
T newT;
}
However, sometimes (with more meta-programming) this sort of solution will be more verbose than the alternatives:
Option 1: store the template variable in the Object class:
template <class T>
class... |
69,520,116 | 69,520,143 | Reverse string using pointer arithmetic | I am trying to understand how the below function *reverseString(const char *str) reverses the string with pointer arithmetic. I have been Googling and watched videos which handle similar cases but unfortunately they didn't help me out.
Could you please somebody help me what may be missing for me to understand how this ... | char *result = new char[len + 1];
This line allocates a new string (length of the other string's characters, plus one for the terminating null), and stores it in result. Note that result points to the beginning of the string, and is not modified.
char *res = result + len;
This line is making res point to the... |
69,520,633 | 70,339,311 | "Undefined symbols" of shrink_to_fit() when compiling Cronet on iOS 15 with Xcode 13 | Error message:
Undefined symbols for architecture arm64:
"std::__1::basic_string<unsigned short, base::string16_internals::string16_char_traits, std::__1::allocator<unsigned short> >::shrink_to_fit()", referenced from:
base::UTF8ToUTF16(char const*, unsigned long, std::__1::basic_string<unsigned short, base::st... | This was pretty tricky to track down, but I think I found the issue. First of all, string16.ii can be simplified to:
template <class T>
struct basic_string {
__attribute__((internal_linkage))
void shrink_to_fit();
};
template <class T>
void basic_string<T>::shrink_to_fit() { }
template class basic_string<char... |
69,520,659 | 69,522,147 | C++ Pointers and Memory Allocation | I am taking a C++ class in school and was give a few lines of code with errors and I'm having trouble finding all 4 errors. The code is supposed to print the number "302" I'm not good with pointers.
Here is the code
int main () {
int* ptr;
int* temp;
int x;
ptr = int;
*ptr = 3;
cout << ptr << endl;
x=0;
temp = x;
cout... | Other answers already pointed out the problems, their explanation and a possible solution, except for problem in this:
temp = x needs to be a pointer, *temp = x
No, you are wrong here. Pointer temp is uninitialised and dereferencing an uninitialised pointer (*temp) will lead to Undefined Behaviour. Two ways you can... |
69,520,866 | 69,521,176 | How to construct a std::optional of a struct with std::shared_ptr | I'm trying to create an optional with a class that has a shared_ptr but the implicitly deleted constructor prevents me from using make_optional to create it.
Is the only option to manually write that constructor?
Here is a simple reproduction:
https://onlinegdb.com/DcWzF1NAt
#include <optional>
#include <memory>
class ... | It's not an implicitly deleted constructor causing a problem, it's the implicitly deleted copy assignment operator and has nothing to do with std::shared_ptr, it's because you've declared the B::a member to be const. The solution here is to not mark it as const:
class B
{
public:
B(std::shared_ptr<A>& a):
a{a}
{}
... |
69,520,994 | 69,522,912 | Is there a way to enable UNICODE formatting in Dev C++ | This question has never been asked before.
I am using Dev C++ version 5.11. so, I was surfing across youtube for game libraries, and I came across olcConsoleGameEngine.h. I do not like to use Visual C++ for some particular reasons, and olcConsoleGameEngine.h requires UNICODE support.
This is not supported in Dev C++ by... | The "enable UNICODE" option is just a convenience to make sure #define UNICODE happens before #include windows. There's no magic.
|
69,521,679 | 69,523,288 | Binary Strings are Printed Backwards | I have tried to search for a way to make bit representation of a variable work using macro. The code prints the binary strings backward as I am relatively new to c++ I thought it was the indexing that was the problem as it needs to start high and then count down.
#include <iostream>
#include <memory>
#include <climits>... | As -500 mentioned in the comment you should have the right result if you start with 7 like this
auto bit_index_in_byte{7};
for (int n = s - 1; n >=0; --n)
{
EXTRACTBIT(bit_index_in_byte, &(*byte));
--bit_index_in_byte;
if (-1 == bit_index_in_byte)
{
std::cout << " ";... |
69,521,734 | 69,523,524 | Vector product of multiple vectors using meta function | Given a vector like:
template<int... elements>
struct vec;
How is it possible to create a metafunction which can do multiply element by element all provided vectors. For example
template<typename ...AllVecs>
struct multiVecs
{
using type = ....
}
where type would execute all products element by... | Let's start with the two vector product, and go from there.
template <typename lhs, typename rhs>
struct multiplies;
template <int... lhs, int... rhs>
struct multiplies<vec<lhs...>, vec<rhs...>> {
static_assert(sizeof...(lhs) == sizeof...(rhs), "Vector arity mismatch");
using type = vec<(lhs * rhs)...>
};
tem... |
69,521,906 | 69,522,002 | Random value at time of output |
I have written this recursive function in C++ that prints array elements, but when I run it I get an extra number as output like 634, 389, etc. Can someone please tell me why this is happening and how can I fix this?
| The first call to your function prints out arr[5] to which you didn't assign value so it takes the random value that is in that place in the memory. To fix your issue I would recommend calling function with array size - 1 so in your case
func(arr, 4);
|
69,522,009 | 69,522,079 | How to write functional interface with cmake language? | I found many project with CMake building system will create some_independent_function.CMake.
For example, folly and other Facebook library. They use variable like FOLLY_INCLUDE with CMake recommended naming rules to mark input and output for function to find folly project. Obviously it uses implicit variable as output.... | That is not how the CMake language works. It is not designed to have such returns. Implicit variable names is the way to go.
Feel free to dislike for this design choices, then you are in good company :-)
|
69,522,751 | 69,525,250 | C++ string delimiter exception | I'm working on a piece of code and encountered a small problem here.
In an overall the problem is with a string delimiter and a splitting of a C++ std::string.
The string that I have is:
std::string nStr =
R"(
"0000:ae:05.2:
Address: 0000:ae:05.2
Segment: 0x0000
")";
Normally the above is way larger and has many more... | Okay, from what I can understand from your comments, you want to split the original string into lines, and then split the individual lines by using ":" as a delimiter. With the exception for the first line, which only has one value. Thus the resulting pair for this line should have the value from the line and the strin... |
69,522,878 | 69,617,244 | How to resolve this C6385 code analysis warning: Reading invalid data | I am trying to address a code analysis warning that appears in the following method:
CStringArray* CCreateReportDlg::BuildCustomAssignArray(ROW_DATA_S &rsRowData)
{
INT_PTR iAssign, iNumAssigns, iUsedAssign;
CStringArray *pAryStrCustom = nullptr;
CUSTOM_ASSIGN_S *psAssign = nullptr;
if (rsRo... |
Warning... the readable size is (size_t)*40+8 bytes, but 80 bytes may be read.
The wording for this warning is not accurate, because size_t is not a number, it's a data type. (size_t)*40+8 doesn't make sense. It's probably meant to be:
Warning... the readable size is '40+8 bytes', but '80 bytes' may be read.
This w... |
69,523,092 | 69,523,741 | std::pair gives "no matching function call" error in combination with const std:unique_ptr | I stumbled across a behaviour of std::make_pair that I do not understand. Given the following code
#include <iostream>
using namespace std;
#include <memory>
#include <utility>
class TestClass
{
public:
TestClass(const std::string& str) : str{std::make_unique<const std::string>(str)} {};
~TestCla... | Lets breakdown what your code does:
~TestClass() = default; // (1)
You are explicitly defining the destructor as a defaulted destructor. This counts as a user-declared destructor.
std::unique_ptr<const std::string> str{}; // (2)
Declares a non-const unique_ptr field. This field can be mutated and therefore, moved fr... |
69,523,130 | 69,523,294 | C++ GamerServer Library with Unity Client | I made a simple C++ game server library(network session) and I wanted to use it for Unity client to make a simple MMORPG.
I found that my library needs to be changed to DLL.
So, I made a dll of my C++ game server library and found that my class cannot be used for Unity Client directly.
Is there an easy way to use my c+... | You are trying to create a Unity native plugin. You have to make sure that you export your methods in the proper way and then you can "link" them to a C# method that will have the same signature. Tip: make sure to keep with the native/primitive types. Since it is a long topic to be explained here I am sharing a link th... |
69,523,389 | 69,524,722 | App closes before uploading data to database, Qt | So I have made a basic app that allows users to enter in data and then upon pressing submit the data is submitted to a firebase and the app closes. However for some reason the app is closing without submitting the data to the firebase.
The code for the submit button is as follows:
void checkinapp::on_pushButton_clicked... | If I were you I would do this:
void checkinapp::on_pushButton_clicked()
{
checkinapp::post();
//checkinapp::exit();
}
then in the post method:
void post()
{
m_networkManager = new QNetworkAccessManager ( this );
...
HERE connect the Manager to your custom slot, something like
connect(mm_network... |
69,523,550 | 69,523,637 | Is a map containing addresses of out-of-scope objects undefined behavior? | If I have a map of object addresses to some other type e.g. string:
std::map<unsigned long, std::string> index;
// ^^^ This is a number representing address of an object
// that may go out of scope while the map is still alive.
Is pushing to it objects using addresses to objects that may go out of scope be... | Assuming string is std::string, it is not an address. unsigned long is not an address either.
In case you converted some pointer values to unsigned long and use that unsigned long as key in the map there is not problem with reading those integers. They have no implicit relation to the original pointers.
|
69,523,555 | 69,523,772 | Writing an long integer to an string as char* in Arduino function | i am fighting with this problem for all night long, and nothing working for me...
I have tried with alot of methods founded on the internet, but i'm still locked here.
All I want is to write an number in the middle of an char string to display it on an oled screen using an nodemcu v3 based on ESP8266.
This is what I wa... | sprintf is your friend here, write the number to a buffer first and then print that buffer. However you still need a different way to get to that number, random returns a long value, so to get your desired result you should adjust your parameters first:
randNumber = random(302, 487);
Don't worry about the decimals we'... |
69,523,747 | 69,532,163 | SWIG: Access Array of Structs in Python | Say I have the following static constexpr array of c struct:
#include <cstdint>
namespace ns1::ns2 {
struct Person {
char name[32];
uint8_t age;
};
static constexpr Person PERSONS[] = {
{"Ken", 8},
{"Cat", 27}
};
}
How can I access elements in ns1::ns2::PERSONS in p... |
One way I can think of is to create a accessor like const Person& get(uint32_t index) in the swig interface file.
According to 5.4.5 Arrays in the SWIG documentation, that's the way to do it:
%module test
%include <stdint.i>
%inline %{
#include <cstdint>
namespace ns1::ns2 {
struct Person {
char name[3... |
69,524,622 | 69,524,700 | Why I got garbage value after reclaring variable in a smaller scope | int tar = 0;
{
int tar = tar;
cout<<tar;
}
It prints out 814005873, but what I expected was 0.
| The variable in the outer scope is not relevant. You'd get the same with
{
int tar = tar;
cout<<tar;
}
tar is not initialzed hence using its value to initialize itself is undefined behavior. All major compilers warn about such case of tar being used uninitialized. For example: https://go... |
69,524,675 | 69,525,272 | unique_ptr deleter trick: which compiler is correct? | I was going through this particular SO on how to save memory space for custom deleter pointer. At the bottom of the answer, it provides a custom written version in C++11.
After dozens of minutes trying to understand the code, I discover some compiler inconsistencies among the Big 3, where clang compiles, while the othe... | It appears to be a gcc bug, and a completely different MSVC bug.
gcc cannot do this:
template <typename T, T t> struct foo {};
when instantiated with a function type. T has to be a template parameter for this bug to be triggered; template <void t(void*) noexcept> works.
template <typename T, T* t> struct foo {};
fixe... |
69,525,309 | 69,525,491 | Emscripten: how to disable warning: explicit specialization cannot have a storage class | I am building my program by using the latest Emscripten compiler.
It is based on Clang version 14. Actually it is a small test program which is the following:
#include <iostream>
struct Test {
template<typename T>
static inline void Dump(const T& value) {
std::cout << "[generic] = '" << value << "'\n";... | Explicit specialization of (both static and non-static) function templates cannot be put into class definitions.
Just put it into the enclosing namespace(i.e somewhere after the class):
#include <iostream>
struct Test {
template <typename T>
static inline void Dump(const T& value) {
std::cout << "[gene... |
69,525,592 | 69,571,412 | Undefined Symbol error when linking pybind11 with a dynamic library that calls an external function | I'm trying to link a pybind11 module with a .so dynamic library, and the library calls functions not implemented in the .so file. It works fine in a normal c++ executable file, but raises Undefined Symbol error when imported in python.
Here is a simple demo to reproduce my problem.
The function Student::print() is comp... | I'll be honest: I don't know how pybind11 works internally well enough to tell you why this is happening. However, there is a workaround that makes your code works, which is to compile Student.cpp into a shared library of its own and link it to the pybind11 module. This is how you can modify your CMakeLists.txt to make... |
69,525,866 | 69,525,992 | Undefined symbols for architecture x86_64 with QNetworkReply | I keep getting the following error:
Undefined symbols for architecture x86_64: "checkinapp::myOnFinishedSlot(QNetworkReply*)", referenced from: "checkinapp::qt_static_metacall(QObject*,QMetaObject::Call,int,void**) in moc_checkinapp.o
I have looked through several times and can't figure out where I have gone wrong. (Im... | Your declaration
void myOnFinishSlot(QNetworkReply* x)
Does not match your definition:
void myOnFinishSlot()
You effectively defined two methods with different overloads.
Either merge the definition and declaration:
public slots:
void myOnFinishSlot(QNetworkReply* x) { exit(); }
or move the definition outside of the... |
69,525,870 | 69,526,532 | Vertical Order Traversal using Iterative method | I'm trying to solve the problem of Vertical Order Traversal of Binary Tree using map and queue. I did solve it using a recursive way, but I'm not getting the same answer using the iterative way.
10
/ \
7 4
/ \ / \
3 11 14 6
Approach :
First I declared an integer that stores horizon... | You cannot use a single Hd variable like that. Note how in the first iteration, Hd will go to -1 and back to 0 because the root has both a left and right child. So in the next iteration you start again with 0, yet the node that you pull from the queue has nothing to do with that value of Hd.
Instead, put pairs in the q... |
69,525,922 | 69,528,963 | Googletest: CLANG compiles where GCC fails | Here is a very simple script using gtest (saved in file gt.cpp)
#include<gtest/gtest.h>
double timesTwo(double x){return x*2;}
TEST(testTimesTwo, integerTests){EXPECT_EQ(6, timesTwo(3));}
int main(int argc, char* argv[]){
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
The script compiles fi... | Here is this error message passed through a http://demangler.com/
Undefined symbols for architecture x86_64:
"_testing::internal::EqFailure(char const*, char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::al... |
69,526,375 | 69,530,583 | Best way to store a pointer to base class, but be able to use derived class functions | I have a Cell, which can store objects of CellContent type. CellContent have to be a virtual class. From CellContent I have to derive classes Enemy and Item. So the idea is to store a pointer to a CellContent inside of Cell. The question is: what is the best way to store a pointer to a derived class in this circumstanc... | All functions of the derived-class, which:
Need to be callable,
While variable is of base-class-type,
But without casting from base-class-type to derived-class-type manually,
should be declared virtual in the base-class (and be overridden in derived-class).
|
69,527,038 | 69,527,398 | How can I write variable definition without declaration? | I can write declaration or declaration with definition. Examples:
int x = 1; // declaration and definition
extern int x; // only declaration
bool f(); // only declaration
bool g() {} // declaration and definition
class X; // declaration
class X {}; // declaration and definition
So we can see that this is possible to w... | There is no definition without a declaration, since the meaning of the first term includes the second. Further, I provided some information from the C++ drafts (6.2. Declarations and definitions):
A declaration is said to be a definition of each entity that it
defines.
Link: https://eel.is/c++draft/basic.def
|
69,527,302 | 69,527,911 | How to get a list of objects with common attributes? | Given a class Movie (id, title, ranking, release date, character number, ticket price, comment etc.), enum type: ACTION, COMEDY, DRAMA, FANTASY etc. and a class Cinema (name, location). I need to write a function calculateProfit ( Movie*, day) that would calculate cinema's profit based on some particular day. Also I ne... | Given a std::vector<std::shared_ptr<Movie>>, you can find by title as follows:
using MovieCollection = std::vector<std::shared_ptr<Movie>>;
MovieCollection find_by_title(const MovieCollection& collection, const std::string& fragment) {
MovieCollection ret;
for (auto movie: collection) {
if (movie->title.find(fr... |
69,527,632 | 69,529,010 | Qt GIF creation: Colours swapped when using gif-h library | Apparently, I am trying to use gif-h library for gif creation with qt 4.7 for a C++ project. After embedding the library to the project, I can generate GIF through my qt GUI app, however, the colours on the final/actual GIF are swapped. What I mean is that:
below red frame
becomes below blue frame
and same goes f... | Ok, I have managed to resolve the problem by using QImage::rgbSwapped() function. Thank you to @Pablo Yaggi particularly for the hint.
I will have to remove the code snippet from the question due to security reasons.
|
69,527,715 | 69,648,292 | Check whether OpenSSL supports certain curve via header/define in CMake | I need to check whether OpenSSL supports certain Elliptic Curve(s) via CMake.
While cipher and hash availability may be checked via existence of functions from openssl/evp.h, like check_cxx_symbol_exists("EVP_md4", openssl/evp.h, _openssl_has_md4), I don't see a way to do the same for curves.
Do I miss something, or th... | This code (mostly taken from openssl) lists the available ECs:
#include <stdio.h>
#include <openssl/ec.h>
#include <openssl/objects.h>
int
main ()
{
int ret = 1;
EC_builtin_curve *curves = NULL;
size_t n, crv_len = EC_get_builtin_curves (NULL, 0);
curves = OPENSSL_malloc((int)sizeof(*curves) * crv_len);
if ... |
69,527,976 | 69,528,907 | Too much combination to expand a macro | I want to apply a function to data buffers and their types are known at runtime.
I use for that a templated function template <typename T1, typename T2, typename T3> void myFunction().
myFunction is a member of a class, which also contains the data structures storing the buffers. The buffers are stored in a char* point... | I'm not sure what you were trying to achieve with BOOST_PP_SEQ_FOR_EACH, as BOOST_PP_SEQ_FOR_EACH_PRODUCT already gives you all permutations of the template arguments:
#include <boost/preprocessor.hpp>
// List the possible types
#define STRIP_ALL_TYPES \
(eIBT_Int8)(eIBT_UInt8) \
(eIBT_Int16)(eIBT_... |
69,527,983 | 69,528,092 | accessing operator overload functions using object pointer | I am implementing this class from https://isocpp.org/wiki/faq/operator-overloading
class Matrix {
public:
Matrix(unsigned rows, unsigned cols);
double& operator() (unsigned row, unsigned col); // Subscript operators often come in pairs
double operator() (unsigned row, unsigned col) const; // Subscript op... | (*m)(i,j) should do the trick. But then you might as well implement an equivalent at method so you can write m->at(i,j).
|
69,528,447 | 69,528,595 | Why don't pointers have same address as the variable they are pointing to? | I am a beginner at C++ (and have no knowledge of C , coming form a Java and Python background).
I was learning about pointers and ran the following code I am sharing from my self tutorial file:
#include<iostream>
using namespace std;
int main() {
//What is a pointer:-
// A datatype that holds address o... | A picture is worth a thousand words.
+----------------+
a: | 3 | 94ac7ff7d4
+----------------+
^
|
`-------------.
|
+--------------|-+
b: | 0x94ac7ff7d4 * | 94ac7ff7d8
+----------------+
^
|
`--... |
69,528,726 | 69,529,229 | Why is this unordered_map not finding existing keys? (C++14) | I'm trying to use an unordered_map for a custom type. However, the map is storing duplicate entries, which have the same hash value and should evaluate as equal when using ==.
I've reduced my code to the following proof of concept, where I can see that the hash function runs correctly, but the equals operator is never ... | Pointers are not the objects they point to.
You are using pointers as keys. The objects equal operator will be ignored.
|
69,529,544 | 69,529,941 | Is initializing char array from string literal considered to be a implicit conversion? | Is
char x[10] = "banana";
considered to be a implicit conversion from const char[7] to char[10]?
Since std::is_convertible<const char[7], char[10]>::value evaluates to false the obvious answer would be that it isn't, but I couldn't find a proper definition of implicit conversion anywhere. Reading cppreference I'd say t... | Language-lawyerly speaking, initializing char array from string literal is a implicit conversion.
[conv.general]:
An expression E can be implicitly converted to a type T if and only if the declaration T t=E; is well-formed, for some invented temporary variable t ([dcl.init]).
Note that the core language only defines ... |
69,531,076 | 69,532,358 | C++ Async multi-thread file parsing store results in vector | I'm trying to speed up a file parser by using multi threading. I've created a function that reads and parses a json-file and returns a vector.
Now, to speed things up, i tried to use async, so i created a future vector to store the results. When each thread is finished (ran the parsing function), i would like to append... | You want to store ints in your vector, but have a std::future, that is not going to work. You have to get the vector out of the future and then copy its elements.
But with that approach you would have no async operation, since you always wait for the single operation to finish before you start the next one.
Here is an ... |
69,531,298 | 69,531,874 | GL_LINEAR / GL_NEAREST equivalent in DirectX 11 | I have a scene in which i load the same texture only depending on its resolution i use different filtering modes in OpenGL, these are GL_LINEAR, GL_NEAREST and so on. For example, for a texture with a resolution below 128 pixels, I set GL_TEXTURE_MIN_FILTER to GL_LINEAR, and for GL_TEXTURE_MAG_FILTER I set GL_NEAREST. ... | You can find all of the filtering options here.
Your code if you had written it only for DirectX API would look something like this:
D3D11_SAMPLER_DESC sampler_desc{};
if (width > 128 || height > 128) {
sampler_desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
sampler_desc.MinLOD = 0;
sampler_desc.MaxLOD = D3D... |
69,531,837 | 69,532,079 | How to allocate memory to a 2D array of objects in c++? | Three classes Zoo, ZooObject and Animal are present.Is it valid to declare a 2D array of ZooObjects like mentioned below? If so, how do i initialise it? I am familiar with dynamically allocating a 2D array, but can't figure out this one.
class ZooObject;
class Zoo {
public:
int rows, cols;
ZooObject ***zooArray;
... | As already was mentioned, here is nice post where the general answer to the question was detailing explained.
How do I declare a 2d array in C++ using new?
In your case, if you want to store this as 2D array. You should allocate first all rows, where each row is a ZooObject**, which is ZooObject `s pointers array.
And ... |
69,533,352 | 69,533,419 | Not understanding setprecision function in c++ | I'm learning C++ and am supposed to make a program which takes height in inches, weight in pounds, and age from the user, and gives them the size of their clothing. You get the size of their hat by dividing their weight by their height and multiplying that result with 2.9. I have been testing my code and the output is ... | You're using setprecision correctly, the issue is that you have an additional statement that is generating the 1.
Remove the cout << HatSize; line. HatSize is a function that returns void, so you're sending the actual function itself as input to cout, which is being interpreted as 1.
I would also recommend adding a << ... |
69,533,568 | 69,533,696 | Assigning a std::string's c_str() result to that same std::string guaranteed safe by the standard? | Is the following code guaranteed safe by the standard, with regards to std::string?
#include <string>
#include <cstdio>
int main()
{
std::string strCool = "My cool string!";
const char *pszCool = strCool.c_str();
strCool = pszCool;
printf( "Result: %s", strCool.c_str() );
}
I've seen statements that ... | In C++17, this was specified as:
basic_string& operator=(const charT* s);
Returns: *this = basic_string(s).
Remarks: Uses traits::length().
This sequence of operations guarantees that a copy is made before the original storage is destroyed. While a standard library is not required to implement this call using this exa... |
69,533,671 | 69,534,481 | C++ noise interpolation issue | I am attempting to generate noise similar to perlin or value noise.
I am using stb_image_write library from here to write to image file (i write to disk as hdr and converted to png with GIMP to post on here).
This code requires C++ 20 because I am using std::lerp();
Because I am generating a linear gradient as testing ... | I think you're accessing the imago outside it's boundaries.
X and y can go up to 60 in the loops:
for ( size_t x = 0; x <= size - step; x += step )
And the you are accessing position y+step and x+step, which gives 64.
|
69,534,035 | 69,534,054 | Problem when defining templates with c++ STL containers | I am trying to create a function that works with a template that is supposed to adapt to a container with a vector class by itself as default. T<int> for example. However, when I try to use this function in main I get the error that there is no matching function.
#include<string>
#include<iostream>
#include<fstream>
#i... | Your code is valid, and is compiled by GCC and MSVC. However, a Clang bug means the template type you use needs to match exactly with the template template parameter*. Since std::vector has 2 template parameters, and the template template parameter you've written has only 1, it's not an exact match and it fails, even t... |
69,534,591 | 69,534,668 | Cpp initialize std::map in header | I want to initialize a std::map in my_cpp.h header file:
std::map<std::string, double> my_map;
my_map["name1"] = 0;
my_map["name2"] = 0;
But there was a compile error showed up:
error: ‘my_map’ does not name a type
Can someone explain why this not work for a C++ newbie?
Thanks
| You can't initialize a map in a .h file like that. Those assignment statements need to be inside a function/method instead.
Otherwise, initialize the map directly in its declaration, eg
std::map<std::string, double> my_map = {
{"name1", 0.0},
{"name2", 0.0}
};
|
69,534,781 | 69,534,948 | Size of struct with bit fields in C++ not adding up | Why is the sizeof a struct with bit fields not what I expected.
#include <iostream>
using namespace std;
struct test {
uint8_t x : 4;
uint16_t y : 8;
uint16_t z : 8;
};
struct test2 {
uint8_t x : 4;
uint16_t y : 10;
uint16_t z : 10;
};
int main()
{
cout << sizeof(test) << endl;
cout << si... | No only bitfields, but all the structures are aligned by the compiler to get the maximum efficiency. If you want to force them to the minimum size you need to use the gcc's attribute packed or the equivalent in compiler you are using, like following:
#include <iostream>
using namespace std;
struct test {
uint8_t x... |
69,535,076 | 69,536,088 | Compiler cannot find header file within header file in C++ | I have a header file provided by yaml-cpp library, yaml.h
yaml.h:
#include "yaml-cpp/parser.h"
#include "yaml-cpp/emitter.h"
#include "yaml-cpp/emitterstyle.h"
#include "yaml-cpp/stlemitter.h"
#include "yaml-cpp/exceptions.h"
#include "yaml-cpp/node/node.h"
#include "yaml-cpp/node/impl.h"
#include "yaml-cpp/node/conve... | When you have a file yaml.h that itself includes other files like this:
#include "yaml-cpp/parser.h"
Then the expected directory layout is as follows:
somewhere/
|
+-- yaml.h
|
+-- yaml-cpp/
|
+-- parser.h
You are expected to pass -Isomewhere to your compiler and use the header file yaml.h lik... |
69,536,258 | 69,566,175 | CUDA Zeropadding 3D matrix | I have a integer matrix of size 100x200x800 which is stored on the host in a flat 100*200*800 vector, i.e., I have
int* h_data = (int*)malloc(sizeof(int)*100*200*800);
On the device (GPU), I want to pad each dimension with zeros such that I obtain a matrix of size 128x256x1024, allocated as follows:
int *d_data;
cudaM... | As you hypothesize, you can use cudaMemcpy3D for this operation. Basically:
Allocate your device array as normal
Zero it with cudaMemset
Use cudaMemcpy3D to perform a linear memory copy from host to device for the selected subarray from the host source to the device destination array.
The cudaMemcpy3D API is a bit ba... |
69,536,380 | 69,544,454 | Link 1st-party library with CMake | I want to make a game in C++ and my goal is to isolate the game engine code from the game logic code, so I can potentially reuse some of the logic and have separate git repos:
+-- MyPersonalProjects
| +-- TheEngine (library)
| | +-- src...
| +-- TheGame (depends on TheEngine)
| | +-- src...
| +-- AnotherGame (de... | If you just have an engine and a bunch of games, it's good enough to include the engine as a git submodule to each game and then call add_subdirectory on the engine from inside each. For a sketch:
cmake_minimum_required(VERSION 3.21)
project(Game)
add_subdirectory(Engine)
# ...
target_link_libraries(Game PRIVATE Eng... |
69,536,550 | 69,536,759 | Initialize a matrix with constant string in c++ | I'm trying to initialize this matrix with a constant string (i.e. "@"), in order to fill it later. Hence, the output is not what I'm expecting. Can you please tell me what I'm doing wrong? Can you give me some advice on how to better initialize the matrix with a constant string?
#include <iostream>
#include <string>
us... | There are many isssues. Explanation in comments.
But as one of the a comments above says: get a good C++ book. BTW your code is rather C code than C++ code.
#include <iostream>
#include <string>
using namespace std;
char Board[3][3];
const char PLAYER = 'X'; // you don't need a pointer here, you need a char here
con... |
69,537,024 | 69,541,554 | Is it safe to mix UNICODE and non-UNICODE translation units? | I'm integrating a library which requires _UNICODE and UNICODE to be defined; I can't set these definitions globally on my project for now, so I was wondering if I can safely build only the library code with these definitions.
I'm worried about ODR violations, but as far as I understand these definitions only impact mac... | If there is one inline function with _TEXT()/TCHAR/... in different translation unit, one with preprocessor defined and one not (even if function is not used), then you got ODR-violation.
"is it safe?"
No.
Do you have currently ODR violations?
Not sure, maybe, maybe not.
Currently that tchar.h only #define/typedef ... |
69,537,052 | 74,292,111 | Clang-format array initializer one per line | Clang-format, given an array of structs with initializers, is putting two items per line:
sym keywords[] = {
{0, 0, "C"}, {0, 0, "T"},
{0, 0, "V"}, {0, 0, "ax"},
{0, 0, "bool"}, {0, 0, "break"},
...
{0, 0, "val"}, {0, 0, "vector"},
{0, 0, "version"}, {0, 0,... | I'm not entirely sure, but ArrayInitializerAlignmentStyle set to left might achieve that result. This option was added with clang-format version 13.
At least my current settings turn your code into:
sym keywords[] = {
{0, 0, "C" },
{0, 0, "T" },
{0, 0, "V" },
{0, 0, "ax" },
{0, 0,... |
69,537,561 | 73,571,639 | No result in QTSql query | I've created a function to exeute a query to postgresql database. I call the function with the query string, a boolean in order to tell me if the query is ok or not and an error string. If I try with a correct query (tested in postgresql prompt) I dont enter in xQueryResult.next() loop but xQueryResult is not empty. I... | The code is ok. Bug is in qt version. Updating Qt code works properly.
|
69,538,013 | 69,545,109 | Shared CMake scripts between multiple projects | I'm looking for a way to share CMake scripts between multiple projects.
In a repo called somelib I have a cmake folder, and from the other projects I want to include the scripts in it. In the CMakeLists.txt of somelib I include many files from the cmake folder.
My projects declare "somelib" as an external dependency li... | Don't do include(${somelib_SOURCE_DIR}/CMakeLists.txt) since FetchContent_MakeAvailable(somelib) already calls add_subdirectory on that same file.
If you want access to its scripts, then just run:
list(APPEND CMAKE_MODULE_PATH "${somelib_SOURCE_DIR}/cmake")
include(Cache)
include(Linker)
include(CompilerWarnings)
Bu... |
69,538,035 | 69,538,226 | Implementing the assignment operator in an abstract base class using the curiously recurring template pattern (CRTP) | I am writing an abstract CRTP-based abstract base class for static/dynamic arrays. I intend to put as many methods as possible in the base class so that there is no code duplication in the derived classes. I have got the indexing operator working but I'm struggling with the assignment (=) operator.
/** Array base class... | Since the member variables of your ArrayBase are reference, the implicitly-declared ArrayBase::operator= will be automatically deleted.
The alternative is to remove the member variables and directly use the help function to get the reference of the derived class:
template <class t_derived_class, class data_type>
class ... |
69,538,072 | 69,538,242 | Avoid copy construction by std::transform | I'm calling std::transform with a lambda that takes by reference and gives back a reference to the vector element. However, according to my program output, the copy constructor is called and the objects are NOT the same.
Code:
#include <algorithm>
#include <iostream>
#include <vector>
class Math
{
private:
int val... | The copies have nothing to do with your usage of std::transform. They happen when you construct your v_math std::vector, because you're using a std::initializer_list constructor, which forces copies during construction.
In your std::transform call, operator=(const Math&) is called, change your code to the following to ... |
69,538,474 | 69,538,595 | Need help understanding the sort() c++ function weird behavior | I have a comparator function that compares two strings which represent numbers that have no leading zeros, eg "123" or "5".
bool comp(string s1,string s2){
if(s1.size()!=s2.size())
return s1.size()<s2.size();
int i=0;
while(i<s1.size() && s1[i]==s2[i])
i++;
if(i==s1.size())
re... | Your comparer doesn't respect strict weak ordering,
equality checked by
if (i == s1.size())
return true;
should be
if (i == s1.size())
return false;
Alternatively, using <tuple> facility ensures strict weak ordering:
bool comp(const std::string& s1, const std::string& s2)
{
return std::forward_as_tuple(s1... |
69,539,246 | 69,543,604 | How do i find empty space in array and fill it with part of code / how do i rand 3 randed arrays into one and shuffle it randomly? |
Got a task to do password generator.
Right now i have a problem with the output because if i build the code
here is the outcome.
so my problem is that i need to get something more like this with my own input choice and to mix it into each other so it wouldn't go like the first picture.
i hopefully made myself ... | If I understand you want to combine a random selection of characters from each of the 3 sets in a random order, then a convenient way to ensure you end up with a randomized selection from each set combined in a random order would be to:
shuffle each set initially,
create a string concatenating the needed number of cha... |
69,539,401 | 69,539,667 | Finding factors of number in C++ but I want to print number of factors on first line |
I am able to find the factors but not getting how to print the
count of factors like in Sample output in c++
Question : You are given a number N and find all the distinct factors of N
Input:
First-line will contain the number N.
Output:
In the first line print number of distinct factors of N.
In the second line print... | Store the factors in a vector:
#include <iostream>
#include <vector>
int main() {
int n;
std::cout << "Please enter a number" << std::endl;
std::cin >> n;
std::vector<int> factors;
for(int i = 1; i <= n; ++i) {
if(n%i == 0) {
factors.push_back(i);
}
}
s... |
69,540,071 | 69,541,011 | Coding in Bits. or Structuring a Byte into several different values with respect to corresponding bits. or Bitwise coding or Bit Manipulation | I would like to have single byte with multiple funtions.
I would like to split a Byte into 5 parts; that is first half byte or first four bits, with 0-15 different values.
Then the last half of the byte or last 4 bits must be separated, each bit (that is 5th, 6th, 7th, or 8th_bit) must have value of 0 or 1.
For exampl... | You need to learn a littel bit about boolean algebra. Most important are AND, OR and NOT operations. You can build anything with these 3 operations. There are other Operations which can also be used to come to any desired outcome, like NAND and NOR, and more. But anyway.
C++ has bitwise operators for AND & or OR | or N... |
69,540,504 | 69,543,729 | Segmentation fault when emplacing to map | I have a map like this,
std::unordered_map<size_t, Connection> connections;
and I emplace elements into it like this,
void onConnectionEvent(size_t peer, std::string message, Local::TCP::Connection socket) {
auto [element, inserted] = connections.try_emplace(peer);
auto& connection = element->second;
// D... | You must use a lock that surrounds both manipulation and reading of the container.
STL containers themselves are not thread-safe by default, even though the way this is formulated is, in my opinion, rather confused. Manipulating the content of the same container instance itself - adding, removing or moving elements - i... |
69,540,628 | 69,540,897 | Data members from variadic typename template and overloading | Similar to question Declare member variables from variadic template parameter, but with an additional question:
Let's say I have 2 (or many) structs:
struct A { int a; };
struct B { int b; };
And I want to make a class holding dynamic arrays of each, AND be able to have a call doing specific processing to one of those... | From what I understand, std::tuple does the job too:
template <typename... Ts>
struct Manager
{
std::tuple<std::vector<Ts>...> vectors;
template <typename T, typename F>
void process(F f) {
for (auto& e : std::get<std::vector<T>>(vectors)) {
f(e);
}
}
};
Demo
|
69,540,867 | 69,541,266 | QT: Use stylesheet as external file | I have a project developed in QT 5.9.5, so C++. I have an with a GUI and I want to describe the appereance of the widgets with an external global stylesheet.
I'm working with QTCreator. I added a general file named "stylesheet.qss" and QTCreator put it into "Other files" directory. I have not created resources files. O... |
add your .qss File in Resource(.qrc)
put this code that you want to add your qss in your program in main.cpp :
#include "mainwindow.h"
#include <QApplication>
#include <QFile>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
/**
* Load the application style
*/
QFile styleFi... |
69,541,092 | 69,541,147 | Is there a reason to use std::distance() over iterator::operator-()? | I am unsure why there is both std::distance(iterator const&, iterator const&) and a iterator::operator-(iterator const&) (as well as adaptors operator-(iterator const&, iterator const&)), where iterator is a placeholder for any iterator. Should one be used over the other, and if so, what circumstances?
| operator - is not a member of most iterator types, so it is an error to use it generically unless your algorithm only supports random access.
std::distance on the other hand knows about iterator categories and will use operator - if it is available and if not, it will use N calls to operator -- to do the subtraction.
|
69,541,247 | 69,542,061 | Save a char* parameter intro a string | Please help me with this question.. I'm beginner with gtest.
I have a mocked function
DoSomething(const char* par0, const char* par2)
I want to save its second argument into
std::string `savedPar_`;
EXPECT_CALL(mockd_, DoSomething(_, _,))
.WillOnce(DoAll(SaveArg<1>(savedPar_), (Return(Ok))));
And got thi... | According to the doc
SaveArg<N>(pointer) Save the N-th (0-based) argument to *pointer.
It should be:
std::string savedPar_;
EXPECT_CALL(mockd_, DoSomething(_, _,))
.WillOnce(DoAll(SaveArg<1>(&savedPar_), (Return(Ok))));
// ^
|
69,541,591 | 69,550,275 | Is there a reason why make_reverse_iterator(make_reverse_iterator(it)) results in a different type? | I would think that:
static_assert(is_same_v<
decltype(make_reverse_iterator(make_reverse_iterator(it)))
, decltype(it)>);
would compile, but it doesn't. Is there some reason why this is? I can see this as potentially resulting in larger generated code when writing templates.
This isn't that difficult to implem... | There's a simple question whose answer explains this:
Is the return value of make_reverse_iterator a reverse_iterator?
See, a reverse iterator is not just an iterator that runs backwards. It's a type. Or rather, it's a template which generates a family of types. And that template is expected to provide certain behavior... |
69,541,820 | 69,649,867 | Qt5 Ignoring Native Touch Events | A couple years ago, I had to implement touch features in an application, but my company was still using Scientific Linux 6.4, which did not natively support touch, not to mention multi-touch. Fortunately, I was able to upgrade the kernel to 2.6.32-754, which gave me access to multi-touch events, and while they were not... | The simple answer to this problem seemed to be to use xinput to disable the touchscreen device input, which gave me the behavior I wanted. The reason I don't want to re-write the code handling it is because it would be a lot of effort and time for no difference in behavior or performance. I can't just use the native to... |
69,541,986 | 69,542,891 | Cannot instantiate class inside other class. Member Map::value is not a type name | сlass Chunk
{
private:
size_t value;
public:
Chunk(size_t value)
{
this->value;
}
};
class Snake
{
private:
size_t value;
std::vector<Chunk> snake_body;
public:
Snake(size_t value)
{
Chunk head_chunk(value);
snake_body.push_back(head_chunk);
}
};
class Map
... | Snake snake(value) is not valid syntax for initialization, and Snake snake{ value } is valid syntax(but probably initializes to an unitialized value since value is not initialized). Some more comments in code below :
class Map
{
public:
// this is best if you want the main program to initialize snake with a user pr... |
69,542,293 | 69,542,294 | How to link with ntdll.lib using CMake? | I am using ntdll.lib functions in my code to set the system timer to a higher resolution.
But when I build my project I get this error:
...
.../bin/ld.exe: ... undefined reference to `__imp_NtSetTimerResolution'
collect2.exe: error: ld returned 1 exit status
...
How do I tell the linker to link with ntdll.lib in my CM... | This worked for me:
if (WIN32)
target_link_libraries(executable ntdll)
endif()
|
69,542,355 | 69,542,560 | When is it better to populate an array with fixed index macros vs by incrementing an index? | When would it be better to proceed this way
#define PREFIX_IDX 0
#define SUFFIX_IDX 1
#define ARRAY_DATA_SIZE 2
int data[ARRAY_DATA_SIZE ] = 0;
int main() {
data[PREFIX_IDX] = 6;
data[SUFFIX_IDX] = 19;
return 0;
}
compared with
#define ARRAY_DATA_SIZE 2
int data[ARRAY_DATA_SIZE ] = 0;
int main() {
uint8_t ... | You should avoid macros whenever possible, and it's possible in this case. If you are using at least C++11 (and you should be), you can use constexpr to declare your magic constants at compile time:
static inline constexpr auto PREFIX_IDX = 0u;
static inline constexpr auto SUFFIX_IDX = 1u;
static inline constexpr auto... |
69,542,566 | 69,542,708 | Full pyramid from 5 digit int | i'm having trouble with my C++ homework..
I need an algorithm that can turn an 5 (x4, x3, x2, x1, x0) digit number, into a pyramid like that:
x2
x3x2x1
x4x3x2x1x0
Ex. => 12345
3
234
12345
How can I do that? Do I have to take each number individually and display them in order?
Edit*
I did it, and the code look... | Yes, you’d have to process the digits individually.
Generally I’d expect students to try and tackle it in following ways:
Convert the number to a string, then index individual characters on that string and display them. There are multiple ways of doing the integer-to-string conversion. The simplest may be to use an st... |
69,542,764 | 69,542,910 | Searching a vector for a string, and then find the position of the string in c++ | I am trying to erase a string from a text file. To do this, I want to read the file into a vector, then I want to search for the position of this string, so I can use vector::erase to remove it. After the string has been erased from the vector, I can write the vector into a new file.
So far, I have made all of that, bu... | Below is the working example. There is no need to store the string into a vector or search for the position of the string inside the vector because we can directly check if the read line is equal to the string to be searched for, as shown.
main.cpp
#include <iostream>
#include <fstream>
int main()
{
std::stri... |
69,542,803 | 69,546,285 | getting runtime version information of Qt5 library | Is there inside the Qt5 libraries (for Linux) a C++ function or an API to retrieve at runtime the precise version information of the Qt shared library?
The GNU glibc has gnu_get_libc_version. The libcurl has curl_version.
I want the equivalent for Qt5 (for the RefPerSys project, if that matters). It uses a Qt5 X11 GUI ... | Use qVersion or QT_VERSION (alternative).
To check a specific version: QT_VERSION_CHECK(6, 0, 0).
|
69,542,820 | 69,544,763 | CMake Include paths - library that depend on external library | Take for example this project structure
project
CMakeLists.txt
main.cpp
libA
src.cpp
CMakeLists.txt
libB
foo.h
foo.cpp
CMakeLists.txt
src.cpp and main.cpp:
#include "foo.h"
.
.
.
I need both src.cpp and main.cpp to have libB in their include path, w... | In the top-level:
cmake_minimum_required(VERSION 3.21)
project(project)
option(BUILD_SHARED_LIBS "Build shared libs instead of static" ON)
add_subdirectory(libA)
add_subdirectory(libB)
add_executable(App main.cpp)
target_link_libraries(App PRIVATE libA libB)
In libA:
add_library(libA src.cpp)
# Use PUBLIC below if... |
69,542,893 | 69,543,307 | How to print to file? | I'm need to print some info on a file ".txt".
I wrote on the program the link of the file I want to copy the info. The ".txt" file is empty.
Eclipse tells me that the code is without error. This is the part of code of the print on file:
void stampaVendute(string& vendute,int& n,Opere f[],char p[],int a){
cout<<"\nI... | If if((!stricmp(p,f[i].N_C)) and a<=f[i].anno){ fails the test then nothing is printed to the file. Add a line that unconditionally prints to the file after opening, to see if it works.
Print the file name to the user when the file is opened successfully.
If you are using Windows, you can use process monitor from Sys... |
69,543,157 | 69,543,231 | mulit netsting `mutable` in Google proto | I have proto file, saying that,
message RecommendInfo{
repeated RecommendItem vec_item = 1;
}
message Response{
RecommendInfo recomInfo = 1;
}
I want to produce type Response response.
So I use following code,
Response response;
*(recommendResponse.recominfo().mutable_vec_item()) = {items.begin(), items.end()};
L... | Modifying vecitem modifies the RecommendInfo it belongs to.
So in order to modify the content of vecitem, you have to be operating on a modifiable (aka mutable) RecommendInfo. That's why you have to use mutable_recominfo() instead of recominfo().
|
69,544,262 | 69,544,603 | How to add elements to a vector of pairs every 3rd line? | I'm trying to make a vector of pairs from a text that looks something like that:
line1
line2
line3
And the vector would contain a pair of line1 and line2.
And another vector would contain line1 and line3
Normally I would add lines to a vector like this
vector<string> vector_of_text;
string line_of_text;
... | If I understand the question correctly, you want two vector<pair<string, string>>.
This could be one way:
// an array of two vectors of pairs of strings
std::array<std::vector<std::pair<std::string, std::string>>, 2> tw;
unsigned idx = 0;
std::string one, two, three;
// read three lines
while(std::getline(file, one)... |
69,544,423 | 69,545,387 | Need help creating a program to factorize numbers | The task is to create a program that can do the maximum factorial possible by the machine using "for" cycle.
I understood i have to use bigger data types (the biggest one is "long long", correct me if i'm wrong), and i also understood the concept of the factorial.
Otherwise, i really do not know how to apply what i kno... | Maybe you want to compute the maximum factorial that will fit in an unsigned long long data type.
But let us look at the horrible program. I add comments with the problems.
#include <cstdlib> // Not to be used in C++
#include <iostream>
#include <math.h> // Not needed
include namespace std; // Completely wrong sta... |
69,544,426 | 69,544,528 | C++ reverse a string but printing numbers first | I was given a project in class and almost have it finished, I am required to take a string of numbers and letters and return that string with the numbers printed first followed by the letters in reverse order (ex. abc123 should return 123cba). As of now my code returns a string with the numbers first and the original o... | since you already got the string with letters you can basically reverse it and that's it.
//emplace version:
void reverse_str(std::string& in)
{
std::reverse(in.begin(), in.end());
}
//copy version
std::string reverse_str(std::string in)
{
std::reverse(in.begin(), in.end());
return in;
}
in your case the ... |
69,545,029 | 69,550,001 | C++: How to correct to set up reference of the class function into the non-class reference variable | I have been use the MQTT-library by Goel Gaehwiller(ver. 2.5.0) ad got a little problem with the implementation of the MQTTClient into my own class. The library used a non-class function as a call-back. I tried to use many C++ macroses, but all break the compilation:
void CMQTT::local_mqtt_callback(MQTTClient* client,... | I guess the callback is a std::function type,
You can use the below,
using namespace std::placeholders;
mqtt_client->onMessageAdvanced(std::bind(&CMQTT::local_mqtt_callback,this,_1,_2,_3,_4));
|
69,545,341 | 69,545,469 | getline seems to not be working as I'm expecting (C++) | Beginner programmer here, I'm working on an assignment where we have to create a structure that accepts user input, and I'm running into an issue where the output of the program is skipping a piece of the user input.
Essentially I have a piece of code that says:
MovieData movie1;
MovieData movie2;
//Get tit... | The solution is that, after the transition from formatted to unformatted input, so, something like
first: std::cin >> variable;
and then std::getline(std::cin, variable);
, you need to consume the unread White Space.
And for that you can use std::ws. Please see here
So, after you have used >> add std::ws in your getl... |
69,545,396 | 69,545,566 | Visibility of private field of a template class from a template function | I have a template class
template<class T>
class MyClass
{
public:
MyClass() { privateField = 0; };
T getPrivateField() {
return privateField;
}
private:
T privateField;
};
and a template function which takes an instance of MyClass as a parameter
template<class T>
T foo(MyClass<T> mc) {
retu... | private does not mean that it is completely hidden from the outside, or that nobody outside of the class should be aware that it exists.
Consider this example:
#include <iostream>
struct foo {
int x = 0;
};
struct bar : foo {
private:
int x = 0;
};
int main() {
bar b;
b.x = 0;
}
Now suppose,... |
69,545,451 | 69,546,208 | Can't cross compile C++ files in MinGW properly | I'm trying to compile my C++ app for Windows, using my Linux machine. My issue occurs when I'm executing the compiled exe.
Here's a quick example of my issue.
helloworld.cpp:
#include <iostream>
int main()
{
std::cout << "Hello, World!" << std::endl;
return 0;
}
This code compiles and runs perfectly using g++... | To build a fully static file you should not only use -static-libgcc and/or -static-libstdc++, but also -static to tell the linker to include static versions of any other libraries.
Or you can just build the shared library, but then you will need to distribute any DLL the EXE depends on it with the EXE and put the DLL i... |
69,546,067 | 69,546,193 | Output is nan while it shouldn't be | I need to calculate the following:
S= 1- x^2 / 2! + x^4 / 4! - x^6 / 6! + ... + (-1)^n * x^2n / (2n)!
Where n is between 1 and 100, and x is a double.
I have the following code:
unsigned int factorial (unsigned int n)
{
if (n == 0)
return 1;
return n * factorial(n - 1);
}
double exFive(int n, double ... | Avoid int overflow (undefined behavior (UB)) in factorial(j) Typical 32-bit int can only hold result of factorial(12).
Improve loop computation by calculating the term based on its prior value.
//for (int i = 1; i <= n; ++i) {
// int j = 2 * i;
// s = s + pow(-1, i) * pow(x, 2*i) / factorial(j); //problem is her... |
69,546,421 | 69,634,715 | Undeclared Idenfitier - Templates C++ | The goal of the program is to use templates to create generic lists. My DoublyLinkedList.cpp file takes in a generic type and later stores elements in a linked-list fashion. Anyways, I'm having trouble getting my main function to initialize the list. Some of my code can be found below.
int main(int argv, char* argv[])
... | Since this site is useless and unhelpful I just figured it out myself. The best way I found to accomplish this was to create a function in main.cpp that takes in a template and implements all functions using the object there.
void testList(DoublyLinkedList<T>* list)
{
(*list).print();
}
int main(int argv, char* ar... |
69,546,443 | 69,548,062 | Vscode Run with debugger error "Launch program *file/path* does not exist |
I'm trying to figure out what's wrong with my complier or launch.json file. I get an error whenever i try to run a simple program in vs code. The error says, "Launch program file_path does not exist. I tried downloading different compliers and adding different paths to my system environment variables. I'm losing faith... | I think I know which one is your issue, let me show you a quick example:
I have a folder called Test, having only Test.cpp file:
Then the Test.cpp is only having this simple code:
#include <iostream>
using namespace std;
int main(){
cout<<"Hello World!"<<endl;
return 0;
}
To compile the code and execute it ... |
69,546,491 | 69,546,522 | Converting and printing hex values using sprintf(keeping the leading zeroes) | I have the following C code which takes two long integer values and convert them to two hex strings using the sprintf function:
void reverse_and_encode(FILE *fpt, long *src, long *dst) {
char reversed_src[5], reversed_dst[5];
sprintf(reversed_src, "%x", *dst);
sprintf(reversed_dst, "%x", *src);
printf("... | Use
sprintf(reversed_src, "%04x", ( unsigned int )*dst);
Pay attention to that in general if the the expression 2 * sizeof( long ) (the number of hex digits) can be equal to 8 or 16.for an object of the type long. So you need to declare the arrays like
char reversed_src[2 * sizeof( long ) + 1], reversed_dst[2 * sizeof... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.