question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
71,826,510 | 71,826,651 | Print like a dataframe vector pairs c++ | I have a map:
std::map<string , double> params{{a , 1}, {b, 6 }, {c, 7}{d,8} }
I want to print it like a python dataframe:
a b c d
1 6 7 8
Also, I dont want it to run twice.
void join_parameters(std::pair<string , double> param){
std::map<string , double> params;
params.insert(param);
for(const aut... | Your code only works for a map with 4 elements and it assumes that those elements have keys "a" till "d". If that is the case then I would suggest you to use a different data structure, for example
struct params_t {
double a,b,c,d;
};
If you do need the map then you should not make assumptions about number of elem... |
71,826,513 | 71,826,650 | `std::remove` in template function causing problems with `vector.begin()` being `const` | The error message:
"binary '==': no operator found which takes a left-hand operand of type 'const _Ty' (or there is no acceptable conversion)"
The error seems to be because I'm giving std::remove a const value for the first argument, but I don't see exactly how v.begin() being unmodifiable would cause problems, nor why... |
nor why this error only occurs if the type of the vector is templated, as opposed to a known type vector.
It also occurs if you substitute exampleStruct manually.
std::vector<exampleStruct> eraseElement(std::vector<exampleStruct> v, exampleStruct elem)
{
auto newEnd = std::remove(v.begin(), v.end(), elem);
v.... |
71,826,978 | 71,833,066 | Why can't my programs find resource files when using bazel run //package | I apologise if the title is a bit vague - I didn't know how else to phrase it.
I am quite new to Bazel but one thing that I don't quite understand is why my program fails to find the resource files I specify using the data attribute for the cc_binary rule
For context I am trying to follow Lazy Foo's SDL2 tutorials and ... | Use the C++ runfiles library to find them. Add the dependency in your BUILD file:
cc_binary(
name = "lazy-foo-02",
srcs = [
"main.cpp",
],
data = glob(["media/*"]),
deps = [
"//subprojects:sdl2",
"@bazel_tools//tools/cpp/runfiles",
],
)
and then where your code needs to find the file:
#include ... |
71,827,407 | 71,827,627 | Populating matrix by comparing 2 bits from 2 bitsets? | How to parse/read 2 bits at once from a bitset and process it?
I want to create a matrix that compares if 2 values match and populate the matrix with a 0 or 1.
This is what I did. This is for comparing 1 bit from both bitsets.
void bit2mat(bitset<14> ba, bitset<14> bb)
{
// print the bitsets
cout << "a: " << ba... | Your loops process one element at a time from each bitset. If you want to process two at a time the loop should go in steps of 2:
for (int i = 0; i < ba.size(); i+=2)
Then the two elements to be considered in the iteration are ba[i] and ba[i+1]. Same for the bb loop.
Note that the if and printing in your code can be s... |
71,827,452 | 71,828,188 | Make thread array in C++ | I want to make a program that makes use of all threads.
I get the cores by:
const auto processorCount = std::thread::hardware_concurrency();
Then I tried to do this:
std::thread threads[processorCount];
for (int i = 0; i < processorCount; i++)
{
threads[i] = std::thread(addArray);... | First of all, like in the comments suggested, I would recommend you to use std::vector as well, for example something like, std::vector<std::thread>. Here is a small example of how it could look like:
#include <iostream>
#include <vector>
#include <thread>
using namespace std;
void print(int i)
{
std::cout << i <... |
71,827,551 | 71,827,641 | Inconsistent behaviour c++ classes in classes | Edit based on the comments and the answer:
class Array {
public:
int size;
int *elements;
explicit Array(int maxSize) : size(0), elements(new int[maxSize]) {}
Array(Array &old) : elements(static_cast<int *>(malloc(sizeof(int) * size))), size(old.size) {
memcpy(elements, old.elements, sizeof(i... | Your d object does not hold a valid array of Base objects. You merely allocated memory that may or may not be sufficient. But you never instantiated an object of type Base. So you cannot expect to use it.
If you need an old style array, just create it:
Base d[2] = {/*initialisation*/};
or use new if you need it on the... |
71,828,288 | 71,828,512 | Why is std::aligned_storage to be deprecated in C++23 and what to use instead? | I just saw that C++23 plans to deprecate both std::aligned_storage and std::aligned_storage_t as well as std::aligned_union and std::aligned_union_t.
Placement new'd objects in aligned storage are not particularly constexpr friendly as far as I understand, but that doesn't appear to be a good reason to throw out the ty... | Here are three excerpts from P1413R3:
Background
aligned_* are harmful to codebases and should not be used. At a high level:
Using aligned_* invokes undefined behavior (The types cannot provide storage.)
The guarantees are incorrect (The standard only requires that the type be at least as large as requested but does ... |
71,828,383 | 71,828,936 | C++ If statement before case in switch | I am tasked to rewrite some old software for my company and found an interesting construct inside the sources.
switch(X){
if(Y==Z){
case A: ... break;
case B: ... break;
}
case C: ... break;
default: ...;
}
The compiler warns me, that the code inside the if statment will not be executed b... |
Is there any reason ... why you would write a construct like that?
Only the author knows for sure (even they might not know). If there is source versioning metadata available, then associated commit message might be useful. Without more information, we can only guess what they were thinking. Some potential answers:
... |
71,828,716 | 71,829,912 | msys2 g++ - Entry Point Not Found | I installed msys2 and gcc according to this tutorial. However, when I am using the g++.exe in C:\msys64\mingw64\bin\ , I could not run the following program after compilation:
#include <deque>
int main() {
std::deque<int> d;
d.push_back(1);
return 0;
}
with an error of The procedure entry point... | The problem is a dll conflict with the cygwin1.dll dll. You likely have a dll with the same name as one required by your application in one of the folders of your OS PATH environment variable that is a different version of the required dll or less likely a different dll with the same name.
The conflict could also be in... |
71,829,138 | 71,829,247 | Is it an ODR violation to have an inline templated function have different behavior due to if constexpr? | It's possible to detect if a type is complete https://devblogs.microsoft.com/oldnewthing/20190710-00/?p=102678
I have reason to want to provide a different (inlinable) implementation if a type is complete.
Is it an ORD violation for a templated function to behave differently in different translation units based on an i... | ODR is not based on "templated functions"; it is based on actual functions. Templates generate functions based on template parameters. Each unique set of template parameters represents a different function. Different functions generated from the same template are different functions. There are no ODR expectations betwe... |
71,829,150 | 71,830,225 | Build tools broken after uninstalling Xcode | When I use make to build my C++ project from the command line (cmake .., make) after installing and uninstalling xcode, make outputs make[2]: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++: No such file or directory
xcode-select -p output:
/Library/Developer/CommandLineTools
... | CMake stores the results of its system introspection - the full path to the compiler used is one of them - in a file called CMakeCache.txt.
If you change something in your system that invalidates these results you need to clear the cache, i.e. delete the CMakeCache.txt file in the build folder.
|
71,829,191 | 71,831,011 | The formal parameter in the function is a structure pointer. There will be no error in how to write the argument | This is a code I wrote today. The problem is as follows:
The school is doing the project. Each teacher leads 5 students, a total of 3 teachers. The demand is as follows.
Design the structure of students and teachers. In the structure of teachers, there are teachers' names and an array of 5 students as members
Students'... | The problem is that &tArray is a pointer to an array of 3 Teacher elements,
i.e. a Teacher (*)[3] while your parameter is of type Teacher**. You may
try this:
void allocateSpace(struct Teacher* tArray, int len) {
// ^ no need for len to be a pointer
string nameseed = "ABCDE";... |
71,829,344 | 71,829,495 | Can we write a function which returns a function pointer to a function template? | Is it possible to write a function or method which can return a pointer to a template function or template method?
Example:
#include <iostream>
struct X1 {
static void Do(auto n) { std::cout << "1" << n << std::endl; }
// static auto GetPtr() { return X1::Do; } // how to write such a function?
};
struct X2 {
sta... | No you cannot return a pointer to a function template, because a function template is not a function. It is a template.
// static auto GetPtr() { return X1::Do; } // how to write such a function?
You need & to get a pointer to a member function, though Do is not a member function it is a member function template. You... |
71,829,506 | 71,838,847 | How to truncate a string wrapped in a bounding rect in Qt? | I have a simple QGraphicsView with text written over it. That text is wrapped under a bounding rect. I want to truncate the leading characters of text according to width of the bounding rect.
If my string is "I am loving Qt" and if my bounding rect is allowing 7 chars then it should show like ...g Qt. Text should not ... | You may want to use QFontMetrics::elidedText by giving the font, width of your Text object and the actual text, and it will return the elided text. There are also a few Qt::TextElideMode options to choose from.
|
71,829,984 | 71,831,574 | Iterator traits on pointer to volatile | This code
#include <iterator>
#include <type_traits>
static_assert(std::is_same_v<typename std::iterator_traits<volatile int *>::value_type, volatile int>);
compiles on latest GCC and clang, but fails on MSVC 2019, that seems to remove volatile qualifier. See here on godbolt.
The const is removed, due to the standard... | Extending the link comment by @康桓瑋 to an answer:
This is LWG issue 2952. Before its resolution value_type would be volatile-qualified, but its resolution changes it to remove the volatile qualification.
The resolution is incorporated into C++20 and MSVC, GCC and Clang all seem to implement it as such. (Meaning that the... |
71,830,460 | 71,857,441 | DirectX11 with a multiple video adapter (GPU) PC | Usually the DirectX11 initialization starts from creating a DirectX11 device:
D3D_DRIVER_TYPE driverTypes[] =
{
D3D_DRIVER_TYPE_HARDWARE,
D3D_DRIVER_TYPE_WARP,
D3D_DRIVER_TYPE_REFERENCE,
};
UINT nNumDriverTypes = ARRAYSIZE(driverTypes);
// Feature levels supported
D3D_FEATURE_LEVEL featureLevels[] =
{
... | If you want to create a device that matches the adapter, you need a few changes in the call to :
D3D11CreateDevice
The idea is to provide the Adapter parameter yourself, so the process is :
1/Create the DXGI Factory yourself, using CreateDXGIFactory
2/Enumerate adapters from this factory, for this you use factory->Enu... |
71,830,787 | 71,843,515 | Make building for x86_64 but glfw installed from homebrew is for arm64 (aarch64) | My project was building fine with make, until I imported stb, now I get this error
ld: warning: ignoring file /opt/homebrew/lib/libglfw.3.4.dylib, building for macOS-x86_64 but attempting to link with file built for macOS-arm64
Undefined symbols for architecture x86_64:
"_glfwCreateWindow", referenced from:
Hel... | It seems as if CMake is building for x86_64 even though your processor runs on arm64. This is influenced by CMAKE_HOST_SYSTEM_PROCESSOR, so that should be arm64.
Setting the CMAKE_OSX_ARCHITECTURE should override that default so that it will build your application for arm64:
set(CMAKE_OSX_ARCHITECTURES "arm64")
That w... |
71,831,583 | 71,832,363 | ignoring #pragma comment ws2_32.lib [-Wunknown-pragmas] | I am trying to compile some C++ code using Qt creator that has to connect to a socket for sending and receiving data. I have linked the library file, added the flag win32: LIBS+= -lWS2_32. Attaching the code snippet below:
...
#include<winsock2.h>
#pragma comment(lib,"Ws2_32.lib")
#include<windows.h>
...
WSADATA wsa;
S... | Regarding the warnings (not errors), the #pragma you are using is not supported by most compilers (Microsoft and Embarcadero compilers do). So just remove it altogether (you already link to the library in the project makefile), or at least disable it with an appropriate #if/def.
As for the rest of the errors, send() an... |
71,831,619 | 71,831,722 | How to format unix time (sec+usec+nsec) string? | I have this function which works just fine. It gives me current system time the way I need:
struct Timer
{
struct timespec ts;
char buff[16];
char res[64];
public:
char* GetTimestampNow()
{
timespec_get(&ts, TIME_UTC);
strftime(buff, sizeof buff, "%T", gmtime(&ts.tv_sec));
s... | You don't need a timespec structure.
Notice how all the gmtime calls only use the tv_sec field of the structure? You can use the sec argument directly in the gmtime call.
As for the nanoseconds, you could multiply usec with 1000 to get the corresponding nanoseconds.
So something like:
char buff[16]; // No need to make... |
71,831,717 | 71,832,909 | How to link a C++ program to the NTL library using Bazel | I would like to using Bazel to build a C++ project that links to some external libraries such as NTL. However, I can't find a way to make Bazel to build any program that includes NTL. Here is an example. Consider the following file structure:
/project-root
|__main
| |__BUILD
| |__example.cc
|
WORKSPACE
where W... | I got Bazel to build my project and link to NTL by following the steps in this answer. Refer to this link for the specifics. However, the referred solution was not enough for the particular case of the NTL library. The "problem" is that NTL uses GMP by default. When I saw the build failing because Bazel "didn't recogni... |
71,832,233 | 71,832,390 | why does character_arrays.exe has stopped working error pop up? | my code is working fine. Its showing the right results in the file but after executing the code,an error message pops up saying "character_array.exe has stopped working". Can anyone tell why that error appears??
#include <iostream>
#include<cstring>
#include<fstream>
#include<string>
using namespace std;
int main()
{
... | I am assuming that your issue is an infinite loop, if your IDE supports breakpoints, I would recommend adding one to your while loop and seeing if it runs forever.
|
71,832,605 | 71,834,154 | operator+= between custom complex type and std::complex | I want my custom complex type to be able to interact with std::complex, but in certain cases, the compiler do not convert my type to std::complex.
Here is a minimal working example:
#include <complex>
#include <iostream>
template <typename Expr>
class CpxScalarExpression
{
public:
inline std::complex< double > ev... | Providing your own overload for the operator is the way to go.
However, there's a few things to keep in mind:
Since you already have a cast available, all you have to do is to use it and let the regular operator take it from there.
Since the type that is meant to "pose" as std::complex is CpxScalarExpression<Expr>, ... |
71,832,753 | 71,876,171 | could not find "vswhere" | I'm trying to install boost to run PyGMO properly. However, after I unpack it in a directory (did not use git).
After running bootstrap vc142 (I'm using VScode V1.63.2 and I'm on windows). I'm getting this error:
Building Boost.Build engine
LOCALAPPDATA=C:\Users\wojci\AppData\Local
could not find "vswhere"
Call_If_Exis... | I found the solution here (git)
Prerequisites:
First download and install MinGW installer mingw-w64-install.exe (I fot it from Sourceforge) and make sure you use x86_64 architecture.
Then download the boost file (boost_1_78_0.zip source)
Open and run cmd as admin
Enter the following command to link the MinFW folder... |
71,833,264 | 71,833,475 | C++ Weird behavior while giving a value to the the predecessor element of a matrix column (v[i][j-1]) | So I was trying to make a matrix where the elements of the main diagonal would increase by 3 one by one and I also wanted to change the values of the previous and the next element of the the main diagonal with their predecessor and succesor.
Something like this:
It all worked fine until the predecessor element. For som... | For starters there is no need to use nested for loops. It is enough to use only one for loop.
When i is equal to 0 and j is equal to 0 then this expression v[i][j - 1] access memory outside the array that invokes undefined behavior.
The same problem exists when n is equal to 22 for the expression and i and j are equal ... |
71,833,797 | 71,833,936 | Here is a C++ program where it is showing that my function is out of scope. Can someone please tell me the errors and how to fix them | Question
You have to create a class, named Student, representing the student's details, as mentioned above, and store the data of a student. Create setter and getter functions for each element; that is, the class should at least have following functions:
get_age, set_age
get_first_name, set_first_name
get_last_name, se... | You create one Student instance, z, and call misc. setter member functions on that instance. When you then call the functions to print some of the values you've set, you forgot to tell the compiler which instance you want to print the values for. Since you only have one instance, z, add that before the member functions... |
71,834,217 | 71,834,264 | What does 'NVP' mean in the context of C++ / serialization? | The C++ serialization library cereal uses the acronym NVP several times in its documentation without mentioning what it means.
A quick web search brings up further hits related to boost serialization, and on first glance I couldn't spot a full spelling of the acronym either. It seems to be some kind of C++ serializatio... | It means "Name Value Pair".
KVP (Key-Value Pair) is another common acronym for the same concept you may have run into. They are interchangeable.
It seems to be some kind of C++ serialization related slang.
Not really. It's an acronym specific to boost::serialization. As far as I can tell, cereal inherited it out of i... |
71,834,336 | 71,955,244 | How to correctly include and link a proprietary shared object library in C++ | I have a linux c++ sdk that i need to integrate as a dependency into a .NET 6.0 bigger project.
This sdk is only conditionally included for the linux version of the software, i do already have the windows version running with no problems.
This skd exposes only classes in very nested namespaces, and as far as i'm aware,... | So i figured it out.
makefile
The only problem here is that i did not know how to use a glob pattern to include stuff automatically (like -Ilib/*/include) but whatever.
CC := g++
SRC := wrapper.cpp
OBJ := wrapper.o
OUT := libWrapper.so
INCs := -Ilib/lib-name-api/include -Ilib/name-lib-module-A/include {etc. etc.}
LIB :... |
71,834,378 | 71,834,478 | Output numbers in reverse (C++) w/ vectors | I'm stuck for the first time on a lab for this class. Please help!
The prompt is:
Write a program that reads a list of integers, and outputs those integers in reverse. The input begins with an integer indicating the number of integers that follow. For coding simplicity, follow each output integer by a comma, including... | Firstly, you need to specify the size because you are not using the vector's push_back functionality. Since you are only using at, you must specify the size ahead of time. Now, there's a few ways to do this.
Example 1:
cin >> numInts;
vector<int> userInts(numInts); // set the size AFTER the user specifies it
for (i... |
71,834,788 | 72,159,147 | Why does the use of `std::aligned_storage` allegedly cause UB due to it failing to "provide storage"? | Inspired by: Why is std::aligned_storage to be deprecated in C++23 and what to use instead?
The linked proposal P1413R3 (that deprecates std::aligned_storage) says that:
Using aligned_* invokes undefined behavior (The types cannot provide storage.)
This refers to [intro.object]/3:
If a complete object is created ([e... | The paper appears to be wrong on this.
If std::aligned_storage_t failed to "provide storage", then most uses of it would indirectly cause UB (see below).
But whether std::aligned_storage_t can actually "provide storage" appears to be unspecified. A common implementation that uses a struct with alignas(Y) unsigned char ... |
71,834,820 | 71,834,862 | `std::launder` not returning correct data for Clang and GCC but is for msvc | Why doesn't std::launder return the correct value (2) in CLANG and GCC when the object is in the stack v in the heap? Even using std::launder.
std::launder is required. See this which says launder
is needed when replacing an object const qualified at the top level. This is because
basic.life disallows replacing complet... | std::construct_at(&x, X{2}); has undefined behavior.
It is not allowed to create a new object in storage that was previously occupied by a const complete object with automatic, static or thread storage duration. (see [basic.life]/10)
Other than that you are correct that std::launder is required in the second case for ... |
71,834,995 | 71,866,195 | CMake find specific package of multiple packages with different versions (NCurses) | I currently have a CMake file that finds and links a library (NCurses) to another library
...
set(CURSES_NEED_NCURSES TRUE)
find_package(Curses REQUIRED)
include_directories(${CURSES_INCLUDE_DIR})
add_library(myLibrary STATIC ${sources})
target_link_libraries(myLibrary ${CURSES_LIBRARIES})
target_compile_options(myLib... | Okay I have figured this out, to anyone else who might come across this.
First I installed the latest version of ncurses (6.3) from here: https://invisible-island.net/ncurses/#downloads-h2
(I downloaded the gzipped tar)
I then went through and deleted all references in my usr/local i could find to ncurses.
I then extra... |
71,835,065 | 71,835,136 | Is it better to have one large file or many smaller files for data storage? | I have an C++ game which sends a Python-SocketIO request to a server, which loads the requested JSON data into memory for reference, and then sends portions of it to the client as necessary. Most of the previous answers here detail that the server has to repeatedly search the database, when in this case, all of the dat... |
Is it better to have one large file or many smaller files for data storage?
Both can potentially be better. Each have their advantage and disadvantage. Which is better depends on the details of the use case. It's quite possible that best way may be something in between such as a few medium sized files.
Regarding perf... |
71,835,076 | 71,835,099 | Turning an unsigned integer into a double from 0 to 1. Dividing by integer limit not working | So I'm wanting to turn an unsigned integer (Fairly large one, often above half of the unsigned integer limit) into a double that shows how far it is between 0 and the unsigned integer limit. Problem is, dividing it by the unsigned integer limit is always returning 0. Example:
#include <iostream>
;
int main()
{
uint... | You have to convert the expression on the right to double, for example, like this:
double b = static_cast<double>(a) / 18446744073709551615;
or
double b = a / 18446744073709551615.0;
|
71,835,581 | 71,835,631 | strange std::list iteration behavior | #include <list>
#include <iostream>
#include <utility>
#include <conio.h>
std::list<int>&& asd()
{
std::list<int> a{ 4, 5, 6 };
return std::move( a );
}
int main()
{
std::list<int> a{ 1, 2, 3 };
std::list<int> &&b = std::move( a );
for( auto &iter : b )
{ std::cout<<iter<<' '; }
... | std::list<int> a{ 4, 5, 6 };
This object is declared locally inside this function, so it gets destroyed when the function returns.
std::list<int>&& asd()
This function returns an rvalue reference. A reference to some unspecified object.
What happens here is that this "unspecified object" gets destroyed when this fun... |
71,835,751 | 71,838,877 | How do I unit test and check the contents of a vector object of a custom struct using google mock? | If the structure is
struct Point{
double x;
double y;
};
and the output of a function is vector<Point> and has a size of 10, how do I write a Google Test or Google Mock(I think this is more suitable for this) to verify the contents of the vector? I can write the expected output in a Raw string.
| To start of: it's fine to just write you assertions by hand, checking the size and the content element by element:
std::vector<Point> MethodReturningVector();
TEST(MethodReturningVectorTest, CheckSizeAndFirstElementTest) {
const auto result = MethodReturningVector();
ASSERT_EQ(10, result.size());
ASSERT_N... |
71,835,844 | 71,835,964 | Does memcpy preserve a trivial object's validity? | If one has a valid object of a trivial type (in this context, a trivial type satisfies the trivially move/copy constructible concepts), and one memcpys it to a region of uninitialised memory, is the copied region of memory a valid object?
Assumption from what I've read: An object is only valid if it's constructor has b... | Copying an object of a trivial type with std::memcpy into properly sized and aligned storage will implicitly begin the lifetime of a new object at that location.
There is a category of types called implicit-lifetime type whose requirements are :
a scalar type, or
an array type, or
an aggregate class type, or
a class... |
71,836,532 | 71,836,851 | How to get rid of incompatible c++ conversion | I'm getting the following error during compilation:
Severity Code Description Project File Line Suppression State
Error C2664 'mytest::Test::Test(const mytest::Test &)': cannot convert argument 1 from '_Ty' to 'const mytest::Test &' TotalTest C:\Program Files (x86)\Microsoft Visual Studio\2019\Commun... | In TestFactory::CreateTest(), make_shared<Test>(new Test()) is wrong, as Test does not have a constructor that accepts a Test* pointer as input.
You need to use make_shared<Test>() instead, letting make_shared() call the default Test() constructor for you:
shared_ptr<Test> TestFactory::CreateTest(int testClass)
{
r... |
71,836,535 | 71,836,944 | The c++ 20 way to parse a simple delimited string | There are plenty of questions and answers here on how to parse delimited strings. I am looking for c++20 ish answers. The following works, but it feels lacking. Any suggestions to do this more elegantly?
const std::string& n = "1,2,3,4";
const std::string& delim = ",";
std::vector<std::string> line;
for (const auto& wo... | There is no need to create substrings of type std::string, you can use std::string_view to avoid unnecessary memory allocation.
With the introduction of C++23 ranges::to, this can be written as
const std::string& n = "1,2,3,4";
const std::string& delim = ",";
const auto line = n | std::views::split(delim)
... |
71,836,992 | 71,837,585 | Why My output is printing # in Huffman coding | So I was implementing Huffman coding problem in which i wrote the below code and below is the output attached. Can any one tell me why I am getting # in the output:-
#include<bits/stdc++.h>
using namespace std;
class HuffTree
{
public:
int val;
char letter;
HuffTree* left, * right;
HuffTree(int val, char lette... | if (root->val != '#') should be if (root->letter != '#').
|
71,838,930 | 71,839,908 | Singleton over microcontroller | I am trying to use Singleton pattern in an embedded project, but I can't compile the project. The class, now, is very simple and I don't understand the problem.
The error is (48, in my code is the last line of instance function):
RadioWrapper.h:48: undefined reference to `RadioWrapper::mInstance'
Any ideas?
#define RA... | A static member of a class, like static RadioWrapper* mInstance,
has to be defined (what you have in the H file is a declaration only).
You need to add:
/*static*/ RadioWrapper::mInstance = nullptr;
(the /*static*/ prefix is for documentation only).
This should be added in a CPP file, not H file (otherwise if the H fi... |
71,839,320 | 71,840,214 | Storing data from a file into array C++ | I would like to store the below txt file into a few arrays using C++ but I could not do it as the white space for the item name will affect the storing.
Monday //store in P1 string
14-February-2022 //store in P2 string
Red Chilli //store in P3 array, problem occurs here as i want this whole line to be store in the arra... | You can use std::getline instead of the operator>> for the P3 field:
constexpr int NumOfEntries = 3;
std::array<std::string, NumOfEntries> P3;
// ... and assuming P4, P5, P6 are declared similarly above
for (int i = 0; i < NumOfEntries; i++) {
std::getline(infile, P3[i]);
infile >> P4[i];
infile >> P5[... |
71,839,353 | 71,839,436 | Implicit cast to size_t? | I want to know - does C++ do implicit cast when we initialize unsigned size_t with some value?
Like this:
size_t value = 100;
And does it make sense to add 'u' literal to the value to prevent this cast, like this?
size_t value = 100u;
|
does C++ do implicit cast when we initialize unsigned size_t with some
value? Like this:
size_t value = 100;
Yes. std::size_t is an (alias of an) integer type. An integer type can be implicitly converted to all other integer types.
And does it make sense to add 'u' literal to the value to prevent this cast, like th... |
71,839,364 | 71,839,459 | c++ template type pack specialization for tuple | When trying to implement a tuple type i run into the problem an empty tuple.
This is the type structure i used:
template <class T, class... Ts>
struct Tuple : public Tuple<Ts...> {};
template <class T>
struct Tuple {};
As soon as i try to add an overload for no type the compiler complains: Too few template arguments ... | Your template expects at least one parameter. You can change it like this to allow zero or more:
template <typename ... Ts>
struct Tuple;
template <>
struct Tuple<> {};
template <class T,class... Ts>
struct Tuple<T,Ts...> : public Tuple<Ts...> {};
int main()
{
Tuple<int,int,double> t;
}
|
71,839,686 | 71,840,240 | Check if a path is valid, even if it doesn't exist | Let's say I have a program that takes paths to the input and output directories from a command line. If the output directory doesn't exist, our program needs to create it. I would like to check (preferably using std::filesystem) if that path is valid, before sending it to std::filesystem::create_directory().
What is th... | You gain nothing by doing (pseudo-code alert):
if (doesnt_exist(dir)) {
create_directory(dir);
}
Better to just do:
create_directory(dir);
And handle errors properly if necessary. You may not even need to handle errors here if you handle subsequent errors.
The "if exists" check introduces unnecessary complexity, ... |
71,840,559 | 71,842,690 | Using AWS Cloudwatch to monitor C++ (on-premises, not cloud) program | I am trying to create a simple C++ program that sends something like a real-time status message to AWS CloudWatch to inform that it is up and running, and the status goes offline when it's closed (real-time online/offline status). The C++ program will be installed at multiple users' computers, so there will be like a d... | The best way to monitor a process will be using AWS CloudWatch procstat plugin. First, create a CloudWatch configuration file with PID file location from EC2 and monitor the memory_rss parameter of the process. You can read here more.
For stats you can install CloudWatch Agent on each machine and collect necessary metr... |
71,840,940 | 71,841,195 | The dfs is not wroking | The problem I am seeing is that it outputted all of the ways, even the ones that cannot reach the end. But that is not how DFS is supposed to work.
As I know right now, DFS is within a recursive call chain, and when it goes deeper into the function, it should remove the ones that are not correct and keep the ones that ... | Herein lies the problem, all locations visited by DFS are marked:
if(vis[i1][j1] == 1){
endmap[i1][j1] = '!';
}
You should record the current path with a data structure (such as vector) in the DFS input parameter, and when DFS can reach the end, mark all coordinates in the vector with an exclamation point.
|
71,841,083 | 71,841,348 | Implementation of typed tuple wrapper | How can an implementation look like, that wraps around e.g. a std::tuple as a static list of type/value, plus a type (not contained in tuple) to refer to some kind of owner/visitor.
I want to instantiate like
constexpr auto data = data_of<a>(1, 2.0);
Background
The idea is to use a data_of<T>(...) kind of structure to ... | The issue inherent to your attempt is that class template argument deduction is simply not like its function counterpart. There will be no deduction if any of the class template's arguments is explicitly specified. You fail because the trailing pack is always specified (by omission) as empty.
The solution is to shift t... |
71,841,381 | 71,841,655 | range-based for loop and std::transform with input/output iterators not equivalent when applied to rows of opencv Mat(rix) | In a larger program, I came across the following problem, which I do not understand.
Basically, I am processing an opencv matrix of type float (cv::Mat1f) (docs here). OpenCV provides iterators to iterate over a matrix. When I iterate over the matrix using range-based iterators and a reference to the matrix members, th... | Each call to row creates a new object, and these objects have distinct iterators.
So, row(r).begin() will never be equal to row(r).end().
Get the iterators from the same object instead:
void test2(cv::Mat1f& img) {
for (int r = 0; r < img.rows; r++)
auto row = img.row(r);
std::transform(
... |
71,841,567 | 71,842,877 | std::variant and ambiguous initialization | Consider the following code:
void fnc(int)
{
std::cout << "int";
}
void fnc(long double)
{
std::cout << "long double";
}
int main()
{
fnc(42.3); // error
}
It gives an error because of an ambiguous call to fnc.
However, if we write the next code:
std::variant<int, long double> v{42.3};
std::cout << v.ind... | Before P0608, variant<int, long double> v{42.3} also has the ambiguous issue since 42.3 can be converted to int or long double.
P0608 changed the behavior of variant's constructors:
template<class T> constexpr variant(T&& t) noexcept(see below);
Let Tj be a type that is determined as follows: build an imaginary funct... |
71,841,608 | 71,842,030 | The actual and formal parameters of the array use the same block address, while the variables use different addresses | When using the address transfer of function, View address blocks of formal parameters and actual parameters, I find that the arguments and formal parameters of array share one address block, while the arguments and formal parameters of variables use two address block. What is the reason?
The code is as follows:
#includ... | You are passing pointers to the functions. The value of the pointers are not modified, ie in the function they point to the same objects as they do in main.
However, you are not printing what you think you print:
void test(int *i,int * arr) {
cout << &i << endl;
cout << arr << endl;
}
The pointer i gets the pa... |
71,841,726 | 71,841,904 | How C/C++ compiler distinguish regular two dimensional array and array of pointers to arrays? | Regular static allocated array looks like this, and may be accessed using the following formulas:
const int N = 3;
const int M = 3;
int a1[N][M] = { {0,1,2}, {3,4,5}, {6,7,8} };
int x = a1[1][2]; // x = 5
int y = *(a1+2+N*1); // y = 5, this is what [] operator is doing in the background
Array is continuous region o... | For this declaration of an array
int a1[N][M] = { {0,1,2}, {3,4,5}, {6,7,8} };
these records
int x = a1[1][2];
int y = *(a1+2+N*1);
are not equivalent.
The second one is incorrect. The expression *(a1+2+N*1) has the type int[3] that is implicitly converted to an object of the type int * used as an initializer. So t... |
71,842,109 | 71,842,349 | C++ possible to create macros with non-alpha names? | Is it possible to make preporcessor to replace an arbitrary string with an arbitrary string?
I would like to replace {+} with {:.{}}
|
C++ possible to create macros with non-alpha names?
I would like to replace {+} with {:.{}}
No, you cannot achieve this using the standard pre-processor. Macro names are identifiers. Identifiers may contain digits (except first char), latin alphabet, underscore, and characters in XID_Start/XID_Continue classes.
P.S.... |
71,842,175 | 71,842,327 | How to search a file using an array as search term | I'm trying to parse a csv file and search it to find values that match my randomly generated array.
I've tried a few methods but im getting lost, I need to access the entire file, search for these values and output the index column that it belongs to.
my code for my random array generator as well as my search csv funct... | I'd recommend looking at the find function in more detail. None of its overloads take in an integer, the nearest match (and one that would be used) takes in a char ... So it would not be looking for strings like "12" it would be looking for the character which has a value of 12.
You need to first convert the number(s) ... |
71,842,556 | 71,842,691 | Why is there a narrowing conversion warning from int to short when adding shorts? (C++) | I have a code similar to this for the following array:
long int N = 424242424242; //random number
short int* spins = new short int spins[N];
std::fill(spins, spins+N, 1);
Now let's suppose for some reason I want to add a couple of elements of that array into a short int called nn_sum:
short int nn_sum = spins[0] + sp... | This happens because of integer promotion. The result of adding two short values is not short, but int.
You can check this with cppinsights.io:
short a = 1;
short b = 2;
auto c = a + b; // c is int
Demo: https://cppinsights.io/s/68e27bd7
|
71,843,080 | 71,843,175 | end_unique algorithm, element disappear | #include <iostream>
#include <string>
#include <vector>
#include <list>
#include <iterator>
#include <algorithm>
using namespace std;
void elimdups(vector<string>& words) {
sort(words.begin(), words.end());
for(auto a : words)
{
cout << a << " ";
}
cout << endl;
auto end_unique = unique... | auto end_unique = unique(words.begin(), words.end());
for (auto a : words)
//...
Any items from [end_unique, words.end()) have unspecified values after the call to std::unique. That's why the output in the "erased" range seems strange.
If you want to preserve the "erased" words and keep the relative order, std::sta... |
71,843,100 | 71,843,166 | Get the length of an template<typename> array in c++ | I am trying to figure out how i get the length of an array in c++ without iterate over all index. The function looks like this:
template<typename T>
void linearSearch(T arr[], int n)
{
}
| You can't. T arr[] as argument is an obfuscated way to write T* arr, and a pointer to first element of an array does not know the arrays size.
If possible change the function to pass the array by reference instead of just a pointer:
template <typename T, size_t N>
void linearSearch(T (&array)[N], int n);
Things get mu... |
71,843,222 | 71,843,359 | Compile-time error in uninstanciated function template | My understanding of function templates has always been: if they contain invalid
C++ and you don't instanciate them, your project will compile fine.
However, the following code:
#include <cstdio>
#include <utility>
template <typename T>
void contains_compile_time_error(T&& t) {
int j = nullptr;
}
int main() {}
Co... |
My understanding of function templates has always been: if they contain invalid C++ and you don't instanciate them, your project will compile fine.
Nope, if the code in the template is invalid, then so is the program.
But what does "invalid C++" mean? You can have syntactically valid C++ that is still invalid semanti... |
71,843,237 | 71,844,764 | OpenCV::LMSolver getting a simple example to run | PROBLEM: The documentation for cv::LMSolver at opencv.org is very thin, to say the least. Finding some useful examples on the internet, also, was not possible.
APPROACH: So, I did write some simple code:
#include <opencv2/calib3d.hpp>
#include <iostream>
using namespace cv;
using namespace std;
struct Easy : public L... |
What does the return value of LMSolver::Callback::compute() report to the caller?
Thankfully, opencv is opensource, so we might be able to figure this out simply by checking out the code.
Looking at the source code on Github, I found that all of the calls to compute() look like:
if( !cb->compute(x, r, J) )
return... |
71,843,879 | 71,844,202 | Weird symbols in copied/truncated character array | #include <iostream>
using namespace std;
void truncate(char* s1, char* s2, int n) {
for (int i = 0; i < n; i++) {
s2[i] = s1[i];
}
}
int main() {
char s1[15] = "Hello World";
char s2[10];
int n{ 5 };
truncate(s1, s2, n);
cout << s2; // this should display: Hello
}
When I run this ... | Your truncate function doesn't add the required nul terminator character to the destination (s2) string. Thus, when you call cout in main, that will keep printing characters until it finds its expected nul (zero) character at some unspecified location following the garbage-initialized data that pre-exists in the parts ... |
71,844,237 | 71,846,645 | c++ std::function callback | I have the below five files.
I am trying to call a function in two_b.cpp from one_a.cpp using a std::function callback, but I get the following error:
terminate called after throwing an instance of 'std::bad_function_call'
what(): bad_function_call
Aborted (core dumped)
one_a.h
#include <functional>
using Callback... | std::function throws a std::bad_function_call exception if you try to invoke it without having a callable target assigned to it.
So, you need to actually assign a target to f1 before you try to invoke f1 as a function. You are doing that assignment in Boat's constructor, so you need to create a Boat object first, eg:
... |
71,844,989 | 71,845,241 | How to wrap iterator of boost::circular_buffer? | I'm trying to use boost::circular_buffer to manage fixed size of the queue.
To do that, I wrap boost::circular_buffer by using class Something.
class Something {
public:
Something();
private:
boost::circular_buffer<int> buffer;
};
Here, the problem is that class Something should wrap iterator of buffer.
Fo... | You can do the exact same thing as you do with the std::vector.
typedef std::vector<int>::iterator Iterator; declares a local type called Iterator that is an alias for std::vector<int>'s iterator type.
So logically, you should be able to just swap out the std::vector<int> for a boost::circular_buffer<int> and it should... |
71,844,996 | 71,846,759 | Use case for `&` ref-qualifier? | I just discovered this is valid C++:
struct S {
int f() &; // !
int g() const &; // !!
};
int main() {
S s;
s.f();
s.g();
}
IIUC, this is passed to f by reference and to g be passed by const-reference.
How was this useful to anyone?
| They are useful for both providing safety and optimizations.
For member functions returning a pointer to something they own (either directly or via view types like std::string_view or std::span), disabling the rvalue overloads can prevent errors:
struct foo {
int* take_ptr_bad() { return &x; }
int* take_ptr() &... |
71,845,084 | 71,845,499 | Copy part of texture to another texture OpenGL 4.6 C++ | If I have to texture IDs
SrcID and DestID
How can i copy a part of srcID to DestId
Given the normalised coordinates of the part to be copied, width and height of both src and dest
By normailsed I mean they are between 0 and 1
| You can attach the textures to a framebuffer, and then use glBlitFramebuffer. I can't test the code below, but it should be about right. You only need to specify the coordinates in pixels, but it's easy to compute by multiplying normalized coordinates by texture dimensions.
GLuint FboID;
glGenFramebuffers(1, &FboID);
g... |
71,845,120 | 71,845,207 | Resource leak or false positive | I have a code like this:
std::string getInfo(FILE *fp)
{
char buffer[30];
if (fread(buffer, 19, 1, fp) == 1)
buffer[19] = '\0';
else
buffer[0] = '\0';
return buffer;
}
I'm using cppcheck for static analysis and it spits a warning:
error: Resource leak: fp [resourceLeak]
return buffer;... |
error: Resource leak: fp [resourceLeak]
You are not leaking any resource from this function. So, if you're only analyzing this function, this is a bug in your cppcheck. However, as @Taekahn points out - maybe the leak is elsewhere in your program.
Also, since you're returning std::string, you can use a constructor ta... |
71,845,313 | 71,847,235 | Using GMP, omit mpz_clear() after mpz_roinit_n()? | The GMP library provides a big int C API and a C++ API which wraps the C API. Usually you initialize an mpz_t struct (C API) by doing
mpz_t integ;
mpz_init(integ);
(see 5.1 Initialization Functions). When doing so, you later have to free the memory with mpz_clear(integ);. The C++ API's mpz_class handles this deallocat... | mpz_clear does nothing on a mpz_t set with mpz_roinit_n. So you don't need to call it, but it is still safe if it gets called.
|
71,845,818 | 71,845,891 | MSVC vs GCC & Clang Bug while using lambdas | I was trying out an example presented at CppCon that uses lambdas. And to my surprise the program don't compile in gcc and clang(in either C++14 or C++17) but compiles in msvc. This can be verified here.
For reference, the example code is as follows:
#include <stdio.h>
int g = 10;
auto kitten = [=]() { return g+1; };
... | This is a problem with MSVC. clang and g++ are correct.
From [expr.prim.lambda.capture]/3 (C++17 draft N4659)
A lambda-expression whose smallest enclosing scope is a block scope (6.3.3) is a local lambda expression; any
other lambda-expression shall not have a capture-default or simple-capture in its lambda-introducer... |
71,846,557 | 71,940,201 | Importing C++ library installed using vcpkg on mac? | My goal is to install a library (rbdl-orb) on my Mac and import the library in a C++ program.
My first attempt was to clone the library and run the included example directly. The program "example.cc" starts with the following two lines:
#include <iostream>
#include <rbdl/rbdl.h>
The CMake file follows:
PROJECT (RBDLEX... | Reinstalled the library using "sudo" and started using the vcpkg installation and made the following change to the CMake file:
SET(CMAKE_CXX_STANDARD 11)
After these changes, the library is running correctly.
|
71,847,007 | 71,847,066 | Pointer to an array has it's elements freed once outside scope | I am trying to read from a binary file, and then convert the binary information from a char[] pointer to an int[] pointer.
I was wondering, is there something similar to static int var[], but for dynamically allocated arrays?
I am trying to find a way to tell C++ to not free up the memory after exiting the function.
im... | Edit: This is most likely not what the OP needs, but it is what they asked, so I'll keep this answer around instead of deleting it in case anyone else lands here.
I am trying to find a way to tell C++ to not free up the memory after exiting the function.
The normal reason people want this is in to recycle the dynamic... |
71,847,035 | 71,847,085 | Operator precedence - increment versus member access | Consider this:
++iterator->some_value
Will the iterator be forwarded before some_value is accessed?
According to cppreference increment and member access both have the same precedence of 2. Does the order in which they are listed matter? Or is this undefined - compiler specific?
| Note that preincrement and postincrement have different precedences, so the code snippet you've posted doesn't quite match the explanatory text you've linked.
The preincrement operator has a lower precedence than the member access operator, so ++iterator->some_value is the equivalent of ++(iterator->some_value).
If ins... |
71,847,341 | 71,847,384 | last character of a string in c++ using n.back() and casting | my input is 12. Why is the output 50?
#include <iostream>
#include <string.h>
using namespace std;
int main() {
string n;
cin>>n;
cout << (int)n.back();
}
|
my input is 12. Why is the output 50?
Because the value that encodes the code unit '2' in the character encoding that is in use on your system happens to be 50.
If you wish to print the symbol that the code unit represents, then you must not cast to int type, and instead insert a character type:
std::cout << n.back(... |
71,847,724 | 71,849,987 | How to write custom input function for Flex in C++ mode? | I have a game engine and a shader parser. The engine has an API for reading from a virtual file system. I would like to be able to load shaders through this API. I was thinking about implementing my own std::ifstream but I don't like it, my api is very simple and I don't want to do a lot of unnecessary work. I just nee... | The simple solution, if you just want to provide a string input, is to make the string into a std::istringstream, which is a valid std::istream. The simplicity of this solution reduces the need for an equivalent to yy_scan_string.
On the other hand, if you have a data source you want to read from which is not derived f... |
71,847,803 | 71,847,966 | How to iterate over a map and match its key values with enum class members? | I have a quick question.
Is there any trick to iterate through the keys of a map and use them to access an enumerate class items.
For example, lets say we have the Color class as defined below.
enum class Color {blue = 0, green = 1, yellow = 2};
unordered_map<string, string> mp {
{"blue",""},
{"green",""},
{"yel... | A clean way to do is is to pre-cache the results of fGetVal() in a map and just do a simple lookup:
const unordered_map<string, string> colorStringsMap = {
{"blue", fGetVal(Color::blue)},
{"green", fGetVal(Color::green)},
{"yellow", fGetVal(Color::yellow)},
};
int main() {
unordered_map<string, string> mp {
... |
71,847,915 | 71,848,466 | C++ overloading '+' operator to get sum of data from 2 different linked lists | I am asked to overload operator '+' into the list class. I want the sum of all cgpa points of students from 2 different linked lists but don't know how to do it.
#include <iostream>
#include <cstring>
#include<algorithm>
using namespace std;
class StudentGroup
{
public:
struct Node
{
char* name;
double cgpa;
... | It's as simple as looping through both lists/groups and adding up their cpga:
// put inside class declaration
double operator+(const StudentGroup& student2);
// function definition
double StudentGroup::operator+(const StudentGroup& student2)
{
double ret = 0.0;
Node* pStudent;
for (pStudent = this->head; ... |
71,848,371 | 71,849,380 | Deep copying a vector of pointers in derived class | I have a pure virtual class called Cipher
class Cipher
{
public:
//This class doesn't have any data elements
virtual Cipher* clone() const = 0;
virtual ~Cipher() { };
//The class has other functions as well, but they are not relevant to the question
};
Cipher has a few other derived classes (for examp... | Thank you Marius Bancila, you are right, the problem was that I was just copying the pointers, and not creating new objects in the new vector. I called clone() on each object, and now it works perfectly! Here is the working clone function, in case anyone stumbles upon this thread in the future:
CipherQueue* clone()... |
71,848,820 | 71,849,107 | Understand std::map::insert & emplace with hint | map insert comparison
Question> I try to understand the usage of insert & emplace with hint introduced to std::map. During the following test, it seems to me that the old fashion insert is fastest.
Did I do something wrong here?
Thank you
static void MapEmplaceWithHint(benchmark::State& state) {
std::vector<int> v{... | First, let's create a dataset more meaningful than 12 integers:
std::vector<int> v(10000);
std::iota(v.rbegin(), v.rend(), 0);
Results from all functions are now more comparable: https://quick-bench.com/q/HW3eYL1RaFMCJvDdGLBJwEbDLdg
However, there's a worse thing. Notice that looping over state makes it perform t... |
71,848,888 | 71,850,806 | Generated window with GLFW, background color not changing | I'm trying to change the background color in a window generated by OpenGL/GLFW and I'm using a similar code than the one in the GLFW docs. I'm on Ubuntu 20.04 and the window background is always black, no matter the parameters in the glClearColor() function.
I tried this on Windows 10 using VS and it worked perfectly, ... | You need an appropriate loader after glfwMakeContextCurrent(window).
If you are using glad, you should call gladLoadGL(glfwGetProcAddress) after glfwMakeContextCurrent(window) as the official doc suggests here.
|
71,849,467 | 71,851,038 | C++ proto2 nested message has field checks | In C++ proto2 is it required to do a has_ check before trying to access nested proto message fields?
message Foo {
optional Bar1 bar_one = 1;
}
message Bar1 {
optional Bar2 bar_two = 2;
}
message Bar2 {
optional int value = 3;
}
Foo foo;
if (!foo.has_bar_one() || !foo.bar_one().has_bar_two() || !foo.bar_one().... | After checking the generated code, it seems your second approach will do just fine. The generated code for bar_one is:
inline const ::Bar1& Foo::_internal_bar_one() const {
const ::Bar1* p = bar_one_;
return p != nullptr ? *p : reinterpret_cast<const ::Bar1&>(
::_Bar1_default_instance_);
}
inline const ::Bar1... |
71,849,786 | 72,738,589 | glXSwapBuffers glitchy timing | I have been getting very glitchy timings in my render loop causing rendering to stutter. I have set up timing around my glXSwapBuffers call like so:
Timer timer;
glXSwapBuffers(display, window);
timer();
if (timer.elapsed_seconds > 0.1)
printf("stutter(%f)\n\r", timer.elapsed_seconds);
And am getting results like:
st... | After much testing and debugging I found that my Timer class was computing the difference between two timestamps wrong. The tv_nsec component was being incorrectly divided causing elapsedSeconds to return varying results.
After correcting this the stuttering went away immediately.
|
71,849,922 | 71,850,184 | c++ map insert fails to compile when inserting an object that contains a unique_ptr | I am having trouble (compile time, gcc 17) inserting an object in an std::map which contains a unique_ptr. If I use a regular pointer it compiles (if I take the copy constructor out!).
Here is the struct containing a unique_ptr. With a ctor, copy ctor, etc, with std::move semantics everywhere. Has anyone seen this issu... | Struct1(Struct1& other)
As per language standard, it's the copy constructor; what you did here (by typo or on purpose, I don't know) is a auto_ptr-style neither-move-nor-copy-semantics. Though with that done, the copy assignment is auto-generated, while the move operations are completely removed (unless defined manual... |
71,850,472 | 71,850,736 | Return an error for two inputs of numbers if not an integer | I am trying to make the program return an error if the user input characters/strings to num1, num2 and then take a right input instead
I searched the internet and found the solution with cin.fail() but it works only for the first number or doesn't work at all
I was advised to do it by figuring out the type of variable ... | You need to check the error state of std::cin before you act on the value returned by operator>>. Try something more like this instead:
#include <iostream>
#include <fstream>
#include <limits>
using namespace std;
int main () {
int num1, num2; // two integers
int choice; // chosen integers
int ch1 = 0, ch... |
71,851,235 | 71,851,359 | How can I convert Python3 code to C++/Assembly language? | I want to convert a simple print(“Hello, World!”) code into the assembly language. I read a post, which showed that you can try to convert it to C++, and then to assembly, but that doesn’t work. Can someone help me covert Python3 to Assembly language(or to C++)?
| Here is a Stackoverflow thread that asks a similar questions (at least how to get Python to C) and has a few links to different projects that should do just that: Writing code translator from Python to C?
Also here is another project called PyPy that seems to be a replacement and faster version of CPython mentioned in ... |
71,851,305 | 71,851,619 | Construct cv::Mat via C++ 1D array | I took over a program, which use 1d array to construct cv::Mat. I'm confuse about it, and I make a demo:
int main()
{
short data[] = {
11, 12, 13, 14,
21, 22, 23, 24,
31, 32, 33, 34,
43, 42, 43, 44
};
cv::Mat m{ 4, 4, CV_8U, data};
cv::imwrite("test.png", m);
retur... | The 3rd parameter in the constructor you used for cv::Mat (CV_8U) specifies the format of the data buffer.
Your data is an array of short, i.e. each entry is 2 bytes. When you use values small values like you did, it means one of the bytes for each short will be 0.
When you use this buffer to initialized a cv::Mat of t... |
71,851,356 | 71,851,470 | How to initialize a static array in C++ | Given the following very basic function, how would I initialize arr to all random values, and how would I initialize arr to a set of given values, say the numbers 0-11?
void func() {
static int arr[2][2][3];
}
With my limited knowledge of static variables and C++ in general, I think that the static array needs to ... | Technically if you try to assign the value of arr in a separate line, it will never be re-initialzied after the first time it was initialized. It will be re-assigned. But based on what you described, I assume that's the behavior you want to prevent.
So to initialized arr in the same line, what you could do is first cre... |
71,851,439 | 71,851,579 | C++ rvalue shared_ptr and rvalue weak_ptr | std::shared_ptr<std::string> test() {
return std::make_shared<std::string>("sdsd");
}
cout << *test() << endl;
The above code works. Can someone please let me know where is the "sdsd" string stored. I was expecting it to error out as rvalue is a temporary object. Where is the rvalue copied to and stored in?
With we... | In
std::shared_ptr<std::string> test() {
return std::make_shared<std::string>("sdsd");
}
the constructed shared_ptr is returned and lives on as a temporary variable long enough to be used by the caller before going out of scope and freeing the string allocated by make_shared.
The "sdsd" string is stored in dynamic s... |
71,851,994 | 71,852,063 | Private Struct only returnable with private listed first in a class | So I have run into the case where returning an object of type Node is not allowed if the private variables have been listed after the public as can be seen by the two screenshots below. There CLion is giving me an error as can be seen with Node being red. I understand why this is, however I am wondering if there is any... | The problem is that when the return type Node* is encountered in the member function getCurrentPalyer definition, the compiler doesn't know that there is a struct named Node. So you've to tell that to the compiler which you can do by adding a forward declaration for Node as shown below:
class Palyer
{ private: struct ... |
71,852,071 | 71,852,350 | How to create a "factory function" for a templated class? | How would someone go about implementing a factory function for a templated class? Either my google searches aren't looking for the right thing, or I am misunderstanding the results. As an example:
template<typename T>
class Test
{
public:
T data;
void SizeOfData() { std::cout << "Data Size:" << sizeof(data) <... | The type T of a templated function has to be determined in compile time.
Therefore you cannot do it the way you mentioned.
However - you can use the following pattern to achieve a similar result:
#include <assert.h>
class TestBase
{
public:
virtual void SizeOfData() = 0;
};
template<typename T>
class Test : publi... |
71,852,819 | 74,590,280 | Multiple audio tracks for video playback in Qt | I'm developing a small video editor to make quick edits to a multiple audio track video, using Qt. I'm a bit confused about whether it is possible or not to handle multiple audio tracks in payback and processing in Qt.
What I want to do with the video
list audio tracks
for each track, manage its volume, and choose to ... | After a bit of searching around, I found that it is impossible to do in with Qt as for now.
I found several libraries able to fulfill such purpose (list is non exhaustive for sure) :
libvlc, which was able to render easily on a QWidget surface, but at the time I looked, was not able to play multiple channels at a time... |
71,853,780 | 71,854,590 | How to read data in a specific memory address in c++ | I have created an integer variable using the following code in first.cpp:
#include <iostream>
using namespace std;
int main()
{
int myvar = 10;
cout << &myvar;
// I only need two steps above.
// The following steps are coded to make this program run continuously.
cout << "Enter your name" << endl;
st... | To elaborate on my comment above:
As I wrote each program will run in a different process.
Each process has a separate adddress space.
Therefore using the address of a variable in another process doesn't make any sense.
In order to communicate between processes, you need some kind of IPC (inter-process communication):
... |
71,854,883 | 71,855,004 | Pointer to temporary object | Why does this code work correctly?
struct A {
std::string value = "test"s;
A() { std::cout << "created" << std::endl; }
~A() { std::cout << "destroyed" << std::endl; }
};
int main() {
A* ptr = nullptr;
{
A a;
ptr = &a;
}
std::cout << ptr->value << endl; // "t... | Both codes have undefined behavior.
Here:
{
A a;
ptr = &a;
}
std::cout << ptr->value << endl; // "test"
ptr becomes invalid once a goes out of scope and gets destroyed.
Similar in the second example, you are also dereferencing an invalid pointer because the temporary string is gone after the call to the const... |
71,854,988 | 71,858,066 | How to iterate in-macro integer value in a variable-parameter-length C++ macro (... and VA_ARGS)? | I am trying to write a C++ macro which would substitue a frequently-needed verbose code like
switch (id) {
case 0:
s << myFloat;
break;
case 1:
s << myInt;
break;
default: break;
}
with something like DESERIALIZE_MEMBERS(myFloat, myInt). s and id will not change names for the use case, so they don't ne... | In c++17, here is a solution.
First a compile-time constant type and value:
template<auto X>
using constant_t = std::integral_constant<decltype(X), X>;
template<auto X>
constexpr constant_t<X> constant_v;
Next, a variant over such constants:
template<auto...Is>
using enum_t = std::variant<constant_t<Is>...>;
this let... |
71,855,331 | 71,856,031 | How do I make my function return different results depending on type it's been called using templates in C++ | I've been looking for quite a while for an answer to my question, but couldn't find anything that worked.
Basically, I have a Binary Search Tree and a Search function:
T BinarySearchTree::Search(Node *tree, int key) const {
if (tree == nullptr) // if root is null, key is not in tree
return false;
if (ke... | What you are asking for can be done using if constexpr in C++17 and later, eg:
#include <type_traits>
template<typename T>
T BinarySearchTree::Search(Node *tree, int key) const {
static_assert(
std::is_same_v<T, bool> ||
std::is_same_v<T, Node*> ||
std::is_same_v<T, int>,
"Invalid ... |
71,855,546 | 71,857,751 | How to transform a recursive function to an iterative one | I'm trying to convert this recursive function to an iterative one using a stack:
void GetToTownRecursive(int x, Country &country, AList *accessiblesGroup, vector<eTownColor> &cities_colors)
{
cities_colors[x - 1] = eTownColor::BLACK;
accessiblesGroup->Insert(x);
List *connected_cities = country.GetConnect... | The action taken after the recursive call is the whole remainder of the while loop (all the remaining iterations). On the stack, you have to save any variables that could change during the recursive call, but will be needed after. In this case, that's just the value of curr_city.
If goto was still a thing, you could ... |
71,855,689 | 71,855,869 | How delete int* dynamic array? | I get a problem
"free(): invalid pointer
Process finished with exit code 6"
when I am trying to delete dr[1].
Please say why there is the error in current input (str1, str2)?
'''
#include <iostream>
using namespace std;
int64_t myMin(int64_t first, int64_t second) {
return first > second ? first : second;
}
int ... |
dp[0][i] = 0;
When n2 > n1, this will write over the array dp[0] as i grows.
Adding a bound-check will fix this problem:
if (i <= n1)
dp[0][i] = 0;
In addition, I'd strongly recommend to learn how to debug program.
|
71,856,512 | 71,856,934 | Method of object as method argument of another class in c++ | I have an istance of a class A, that has some methods like:
class A
{
...
public:
bool DoOperation_one(Mytype* pSomeValue);
bool DoOperation_two(Mytype* pSomeValue);
...
bool DoOperation_th(Mytype* pSomeValue);
...
}
Another class, class B, has a pointer to A class and a method BMethod.
Class B
{
...
A* ... | You can pass a member function pointer but then you'll need an A instance to call it and a Mytype* to be passed as parameter:
struct Mytype {};
struct A {
bool DoOperation_one(Mytype* pSomeValue) { return true;}
bool DoOperation_two(Mytype* pSomeValue) { return true;}
bool DoOperation_th(Mytype* pSom... |
71,856,749 | 71,856,864 | c++ which format is used in this swprintf() | What format does this specify in int swprintf (wchar_t* ws, size_t len, const wchar_t* format, ...); ?
L"x%04.4x "
| A break-down of the parts:
the L prefix specifies a wide format string (wchar_t *, as opposed to char * in [s]printf)
the leading x is not part of the format specifier, same as the trailing space
%x results in a hexadecimal representation of the argument
the 0 specifies the padding - i.e., if the given number is less ... |
71,856,845 | 71,861,695 | How to detect if function is implemented in installed library? | I have my program for windows, which uses windows system library (let's name it "sysLib"), and it implements function "libFun1". My program can look like this:
#include <sysLib.h>
void myFunction() {
//some magic here
}
int main() {
myFunction();
libFun1();
return 0;
}
later, library gets update, in ... | Solution is pretty simple:
#include <sysLib.h>
#include <delayimp.h>
int CheckDelayException(int exception_value)
{
if (exception_value == VcppException(ERROR_SEVERITY_ERROR, ERROR_MOD_NOT_FOUND) ||
exception_value == VcppException(ERROR_SEVERITY_ERROR, ERROR_PROC_NOT_FOUND))
{
// This example j... |
71,857,372 | 71,857,716 | Why does a method with the same type argument with "const" at the end give an ERROR 0308? | code:
class InArgClass
{
InArgClass(int In) { }
};
class ToolClass
{
public:
void TestFunc(const InArgClass& Name) { }
void TestFunc(int index) const { } // E0308
//void TestFunc(int index) { }; // NO ERROR
};
int main()
{
//std::cout << "Hello World!\n";
ToolClass* m = new ToolClass();
m... | So, here you are the problem. InArgClass defines a (private) constructor from an int which is not marked explicit.
When you try to call m->TestFunc(100), the compiler has to decide whether:
To promote m (which is non-const) to const and call the int overload (gcc issues a warning but does that);
To try and construct a... |
71,858,429 | 71,858,543 | Iterators in C++. How to modify a vector knowing its iterators? | Trying to understand iterators in C++. For example, in the code below we print a vector.
using Iterator = vector<int>::iterator;
void PrintRange(Iterator range_begin, Iterator range_end) {
for (auto it = range_begin; it != range_end; ++it) {
cout << *it << " ";
}
}
int main() {
vector<int> numbers... |
How to modify a vector knowing its iterators?
You can indirect through an input iterator to access the element that it points to. Example:
auto it = std::begin(numbers);
*it = 42;
For example, the function my_sort sorts a vector
A sorting function generally swaps elements around. You can swap to elements pointed b... |
71,858,509 | 71,865,025 | How to deserialize a std::string to a concrete message in Cap'n Proto C++? | I need to decode a message from a std::string object.
I can see how to do this in Java by using a ByteBuffer, but I failed to find a simple C++ equivalent.
More precisely, how to implement this?
const std::string serialized_data = ...; // Source
SomeDataType data = ???; // How to convert from serialized_data to data?
| You can write code like this:
std::string serialized_data = ...;
kj::ArrayPtr<const capnp::word> words(
reinterpret_cast<const capnp::word*>(serialized_data.begin()),
serialized_data.size() / sizeof(capnp::word));
capnp::FlatAraryMessageReader reader(words);
Note that this assumes that the backing buffer of an... |
71,858,556 | 71,858,709 | How to handle the ownership transfer of a unique pointer's stored raw pointer? | How to handle a scenario where I have a unique pointer with custom deleter, but a 3rd party library's function expects a raw pointer and I pass the stored pointer in the unique_ptr with .get(), but this function takes ownership of the raw pointer.
Example:
Initialize the unique pointers with custom deleter:
std::unique... |
I pass the stored pointer in the unique_ptr with .get(), but this function takes ownership of the raw pointer.
If the function takes ownership, then you should release the ownership from the unique pointer. Otherwise the ownership won't be unique and you will get undefined behaviour due to multiple calls to the delet... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.