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 |
|---|---|---|---|---|
65,312,627 | 65,344,268 | Is it false positive containerOutOfBoundsIndexExpression error of cppcheck? | I have the following code which I want to check with cppcheck tool:
void f()
{
std::string str = "123";
const char* end = &str[str.size()];
}
But when I run cppcheck it reports the following errors which I think are false positives:
$ cppcheck oob.cpp
Checking oob.cpp ...
oob.cpp:4:27: error: Out of bounds acc... | I believe this is a false positive. I created this ticket: https://trac.cppcheck.net/ticket/10048
|
65,312,682 | 65,313,415 | Why does print the pointer directly give a diffrent result when print it by a function in my code? | whats wrong here?
why the 2 "cout" didn't give the same results?
#include<iostream>
#include<string>
using namespace std;
template <class t>
class stack{
private:
struct node{
t val;
node *next;
};
public:
node *top;
stack(){
... | Refer to the possible picture of you program's stack (not your stack stack, but stack that contains all data of your program from start to finish)
:
The first state is after you execute stack <int> s, it contains your local variable s and the content of stack object (i.e. the pointer top, which now points to NULL).
Th... |
65,312,727 | 65,312,898 | Why in particular should I rather pass a std::span than a std::vector& to a function? | I know this might overlap with the question What is a “span” and when should I use one?, but I think the answer to this specific part of the question is pretty confusing. On one hand, there are quotes like this:
Don't use it if you have a standard library container (or a Boost container etc.) which you know is the rig... | The equivalent of passing a std::vector<int> const& is not std::span<int> const, but rather std::span<int const>. The span itself being const or not won't really change anything, but more const is certainly good practice.
So when should you use it?
I would say that it entirely depends on the body of the function, which... |
65,313,193 | 65,313,449 | Frequent hash collisions when hashing 3d coordinates | I'm trying to hash a 3d coordinate to make a unique ID for an index to a map
my approach is currently
return hash(x + hash(y + hash(z)));
Or in c++
struct ChunkHasher
{
std::size_t operator()(FLOAT3 const& vec) const
{
return std::hash<float>()(
vec.x + std::hash<float>()(
v... | vec.y + std::hash<float>() (vec.z) is adding std::size_t and float. The result will be a float, but since the integer will be on average 32-digit long, adding a small float with 7 digits to it will easily yield the same float value.
std::size_t operator()(FLOAT3 const& vec) const
{
std::hash<float> h;
return h... |
65,313,216 | 65,313,328 | C++ Set default argument for a function parameter? | C++ Set default argument for a function parameter? I'm trying to set a Void Function as a default arg for a param but I get a
C++ no suitable constructor exists to convert from to
Error.
Current Code,
void VoidFunction(int a, int b, int c){}
inline void Center(function<void()> Func = VoidFunction(0,1,2));
| You might mean "how to make the default an anonymous callable that executes VoidFunction(0,1,2)", in which case there's lambda and std::bind:
Live On Coliru
#include <functional>
#include <iostream>
void VoidFunction(int i, int = 0, int = 0) {
switch(i) {
case 0: std::cout << "Hello\n"; break;
cas... |
65,313,532 | 65,316,944 | Morton curve for non cubic areas that are a power of two | While optimizing a ray tracer I was trying to improve data locality for the intersection datastructure using a Morton space filling curve, except that my 3D space is not cubic (eg. 512x512x256). All sides are a power of two, but not all sides are the same length.
I have been unable to find any examples for non square M... | It would probably break for, say, nz=11, but for half of the size of the XY square it seems to work for me
#include <cstdint>
#include <iostream>
static inline uint32_t spread(uint32_t x)
{
x = (x | (x << 10)) & 0x000F801F;
x = (x | (x << 4)) & 0x00E181C3;
x = (x | (x << 2)) & 0x03248649;
x = (x | (x <... |
65,313,711 | 65,313,745 | ;=10 Is there such a use in Arduino? | I saw such an if loop in a project : ;=10
if (minute<10)
{
// Serial.print("0");
// Serial.print(minute, DEC);
}
else if (minute>=10)
{
// Serial.print(minute, DEC);
}
// Serial.print(":");
if (second<10)
{
// Serial.print("0");
// Serial.print(second, DEC);
}
else if (secon... | It's code that was HTML encoded. < is the encoding for the < character and > is the encoding for the > character.
So this:
#include <TinyGPS.h>
#include <String.h>
...
if (minute<10)
{
...
}
else if (minute>=10)
{
...
}
if (second<10)
{
...
}
else if (second>=10)
{
..... |
65,314,268 | 65,314,539 | Aliases, templated functions and specialization | I should start by saying that my knowledge of C++ is pretty limited. I have some understanding of templates and specialization, but I'm by no means an experienced C++ programmer. For example I've today learnt about "aliases" which are not quite the same as "typedefs" and this is completely news to me.
I've been reading... | When you've made an alias (using typedef or using) that alias is indistinguishable from the original type. You could consider making int24_t an enum though.
Example:
#include <cstdint>
#include <iostream>
enum int24_t : std::int32_t {};
template<typename T>
void foo(T v) {
std::cout << "base " << v << '\n';
}
te... |
65,314,660 | 65,315,670 | Is there a way to force a template argument within a certain range? | Forgive me, as I've tried searching and maybe I'm just using the wrong keywords. I'm almost positive there is a way where I can bound an integer template argument to a positive value. I just know from bitter experience that it's probably not intuitive at all.
Just so you know, STL widgets for doing this (if there are s... | In C++11, you could just use a static_assert inside the class:
template<std::size_t TCapacity> class Buffer
{
static_assert(TCapacity > 0, "The size must be greater than zero");
// ...
};
If the expression is true, this declaration has no effect. Otherwise a compile-time error is issued, and the text is includ... |
65,314,699 | 65,314,808 | How to make a for loop input data within a while loop until a patient's name is reached | Input file that has the name, some number, another number, then an identification number, followed by a cost:
Jennifer Jones
145634
2
EX1 50.00
BD1 25.00
Paul Peters
173409
4
EX2 75.00
BD2 120.00
XR1 250.00
EQ1 50.00
The code I have so far:
//Input the patient's name from the input file
getline(fin, patientNa... | Just read numberOfServices times:
for (int i = 0; i < numberOfServices; ++i) {
fin >> serviceName >> serviceCost;
// do whatever you want with the info.
}
|
65,314,871 | 65,326,222 | Why does std::shared_ptr call my destructor twice? | In this program, why is the destructor on line 14 is called twice for the same instance of mystruct_t?
I'm assuming that all pointer manipulation in this program is thread safe. I think the atomic updates do not work on my system or compiler.
I tried this on MSVC 2017, MSVC 2019 and on clang
/* This crashes for me (lin... | As several users here already mentioned, you're running into undefined behavior since you globally (or foreign threaded) alter your referred object while thread-locally, you try to copy assign it. A drawback of the sharedPtr especially for newcomers is the quite hidden danger in the suggestion, you're always thread saf... |
65,315,106 | 65,315,209 | How to remove single white space but not multiple? | I know there are some questions concerning this topic, but I would like to know how one should approach this problem without the use of regex?
Regex solutions are also welcome because the best solution I currently know is / (?! ), but this one still removes one white space from all of them.
For example, I would like to... | "how one should approach this problem without the use of regex?"
You would use a state machine (much like regexes do). Algorithmically, you could track transitions and count spaces.
Start with SPACE = 0
while there is input
read a character
if (is space) {
switch (SPACE) {
case 0:
... |
65,315,182 | 65,318,166 | Is there an function in C++ for picking numbers inside a string | I have a calculator from stacks in c++, and when i try to insert a formula on it like 1+2*3 I wish i had a function that would get the numbers until each character that isn't a number.
Example 12+2 it would get 12, then would skip the + because the code would get in other section and then again get the number 2.
I made... | There isn't exactly one function to do what you want, but there's still more support for it than most people realize. When you read a number from a stream, it knows to skip white space before the digits, so even if the stream contains something like " 1234", you can just read an integer, and get 1234.
The stream, i... |
65,315,241 | 65,315,462 | How can I fix "& requires l-value" | So, I created a project and copied this tutorial in it. When I tried to run it, it gave me this error: C2102 & requires l-value at
m_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_renderTargets[m_frameIndex].Get(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET));
I searched ... | This is essentially the same build error reported under Issue #652 Error building D3D12MeshShaders (on VS 16.8.0 Preview 3.0) in the DirectX-Graphics-Samples repo.
I'm getting error C2102: '&' requires l-value on many of the lines. Usually it's when a CD3DX12 constructor is directly used with an &, for example [...]
... |
65,315,773 | 65,316,045 | Why does ofstream work here, but not fstream? | I am trying to understand a difference between std::ofstream and std::fstream. I have this code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
//create an output stream to write to the file
//append the new lines to the end of the file
ofstream... | I see no practical difference between the two cases you describe.
The ONLY technical difference is that ofstream always has the ios::out flag enabled, which will be added to any flags you specify. Whereas fstream has the ios::in and ios::out flags enabled by default, but will be overriden by any flags you specify.
So, ... |
65,315,896 | 65,316,917 | How can I inspect the contents of a static thread_local variable on a heap dump with windbg? | Given the following source code:
namespace EventThreadLocal {
static thread_local std::unique_ptr<std::vector<EventInfo>> Stack;
static const EventInfo* Top()
{
auto stack = Stack.get();
if (!stack)
return nullptr;
if (stack->empty())
return nullptr;
return &(stack->back());
}
}
... | You don't need know the TLS slot associated the the static thread_local variable, the debugger already resolves that with x command. See below sample output that x resolves Stack to different addresses for different threads in WinDbg.
0:000> x test_exe!Stack
00000296`a5437410 test_exe!Stack = empty
0:000>~1s
0:001> x t... |
65,316,195 | 65,326,609 | Why would omp_set_num_threads( omp_get_num_threads() ) change anything? | I've run across something odd. I am testing an MPI + OMP parallel code on a small local machine with only a single, humble 4 core I3. One of my loops, it turns out, is very slow with more than 1 OMP thread per process in this environment (more threads than cores).
#pragma omp parallel for
for ( int i = 0; i < HEIGHT; +... |
I've run across something odd. I am testing an MPI + OMP parallel code
on a small local machine with only a single, humble 4 core I3. One of
my loops, it turns out, is very slow with more than 1 OMP thread per
process in this environment (more threads than cores).
First, without any explicit binding of the OpenMP thr... |
65,316,471 | 65,336,242 | Problems trying to use the C++ auto type for object attributes (member variables) and deducing the return type of std::bind | I have the following code which attempts to generate a random hexadecimal digit.
#include <random>
#include <functional>
using std::mt19937;
using std::uniform_int_distribution;
class
RandomHexDigitGenerator
(
public :
// Other functions omitted for the sake of brevity.
RandomHexDigitGenerator... | Your code is way more convoluted and verbose than I'm comfortable with. Here's what I would do:
#include <random>
#include <ctime>
class RandomHexDigitGenerator
{
public:
char generateRandomHexDigit() {
return static_cast<char>(dist(rng));
}
private:
std::mt19937 rng{static_cast<std::mt1993... |
65,316,817 | 65,317,065 | How to create a struct that creates a different amount of variables based on its input | I want to be able to have a basic struct that will only contain x amount of variables of the same type. This is so I can create child structs that can be called something else like a Vector struct or a Position struct. My question is there a way to vary how many variables that an instance of the basic_struct will creat... | I think what you want is std::array<T, N>.
|
65,317,083 | 65,317,362 | Set sys_seconds to the epoch i.e. zero | Am struggling to find a good way to reset sys_seconds to zero
date::sys_seconds st;
//st = date::sys_seconds(0); //no matching conversion for functional-style cast from 'int' to 'date::sys_seconds'
//st = date::sys_seconds{date::sys_seconds(0)}; //no matching conversion for functional-style cast from 'int' t... | st = {};
Explanation: The default constructor of sys_seconds sets things to zero. So this just default constructs a sys_seconds and assigns it to st. Other ways to do this include:
st = date::sys_seconds{};
and:
using namespace std::chrono_literals;
st = date::sys_seconds{0s};
|
65,317,382 | 65,318,576 | How do i clear the array | I am trying to write a program that can read a string from Serial Monitor Input and count the size of characters as the input data and store the input to the array, but i have some trouble that the Serial monitor will remain the last input data for example if I input ABC it will show "Size of input data = 3 character... | According to the Arduino manual the String [] operator does the same as charAt().
As there is also a setCharAt() function I suppose [] and charAt() are read only.
The manual doesn't say that but why would they have a setCharAt() then.
Just assign an empty string to Msg to clear it.
Msg = "";
|
65,317,428 | 65,317,791 | C++ object management without pointers | It is often repeated to not manage your own memory when possible. When writing an object that manages other objects in a map or vector, how then should objects be created and added to it.
If your object management using new and pointers, this make sense.
// Manager::AddObj(Obj* obj);
// std::map<int, Obj*>
Obj* obj = n... | Let's assume that AddObj calls std::map::insert. If so, then you can do something like this:
#include <map>
#include <iostream>
class Obj
{
public:
int num;
Obj(int n = 0) : num(n) {}
};
std::map<int, Obj> m_ObjectMap;
Obj& CreateObj(int value)
{
Obj obj(value);
auto pr = m_ObjectMap.insert(... |
65,317,897 | 65,318,549 | C++ & Lua registering custom lua library at runtime | I'm currently trying to implement LUA into my CPP program however I am having the following issue: I have a library in lua lets say lib.lua that I'd like to be ran into runtime so that other lua scripts can access it however I'm having issues with that here's my code:
/* initialize Lua */
L = luaL_newstate();
... | In Lua, when you declare a variable as local, it's only available in that lexical scope. You did local class = require 'middleclass' in one file, and then tried to use class in another file, which has its own scope. You need to either get rid of local so that class is a global variable instead, or move that line into t... |
65,318,027 | 65,318,126 | Expected expression before > token in template class | I'm trying to instantiate a template class inside one of its functions, but for some reason I am unable to do so. It tells gives me the error and points to the beginning of the line, which doesn't make sense.
template<typename O>
class ray{
...
color<O> ray_color(const ray<O>& ray, const hittable_list<O>& world, O t_... | One of your parameters is named ray, so in the function body any references to ray refer to that parameter, not the class name the function is defined in.
The solution is simple: call your parameter something else.
|
65,318,177 | 65,318,266 | How to convert Point2f[] to Point[] OpenCV | Other than creating a function that puts elements one by one, is there a method that converts Point2f[] to Point[] datatype?
| You can use Opencv convertTo method.
cv::Mat A = loadMat("mymat.xml"); // See function loadMat in the question!
A.convertTo(A, CV_64F);
Picked from here. Pick your appropriate data type.
|
65,318,409 | 65,318,563 | Operator overloading, Rvalues, C++ | Consider a struct
template<typename T, size_t N>
struct Something {
std::array<T,N> args;
// Some constructors
};
Now let's overload = operator for Something<T>. In fact I can implement it two ways.
First Way
Something& operator=(const Something& rhs){
// an implementation with copy semantics
}
Somethin... | For this particular case you should not implement the assignment operator. The compiler does that already for you:
#include <array>
#include <cstddef>
template<typename T, size_t N>
struct Something {
std::array<T,N> args;
};
int main() {
Something<int,42> a;
Something<int,42> b;
a = b;
}
Demo
For th... |
65,318,822 | 65,319,092 | Calling mangled class instance methods from function marked extern C | I have a typically declared class:
class Task {
public:
int test(int &c);
};
int Task::test(int &c) {
c += 8;
return c;
}
For compiling to WASM, I was trying to instantiate this class and call the test method, like so:
extern "C" {
Task t;
int scratch() {
int c = 123;
t.t... | Mangling is close to a hack that was invented to allow the low level linker to make a difference between int foo(int) and int foo(void). You can use extern "C" to explicitely forbid mangling, but you declare symbols to have that linkage, so it should only be used for plain functions and not for classes nor class member... |
65,319,188 | 65,319,424 | How to fix problems when linking cpp files? | Config.h:
#ifndef CONFIG_H
#define CONFIG_H
class Config {
public:
static int GetDefult();
};
#endif //CONFIG_H
Config.cpp:
#include "Config.h"
int Config::GetDefult(){
return 1;
}
main.cpp:
#include "Config.h"
#include<iostream>
using namespace std;
int main()
{
cout << Config::GetDefult() << endl;
}
When my ... | Playing with the shown code (the more useful one from first versio of your question and after fixing the differences to a MRE with wild guesses),
I got mostly "is not a member of class Config".
I got it to build like below; because obviously you can fix that error by making them members of that class. I chose private b... |
65,319,358 | 65,320,339 | parse char array and don't delete delimiter c++ | I have the next code:
char str[] = "%fds%f%dssa%sss";
char* tokenStr = strtok(buffer, "%");
while (tokenStr != NULL)
{
std::cout << tokenStr << '\n';
tokenStr = strtok(NULL, "%");
}
Output:
fds
f
dssa
sss
but I don't need to delete %.
Expected output:
%fds
%f
%dssa
... | If you do not want to go with regexes (may be overkill here), the pair strspn, strcspn from the C standard library (which is a subset of the C++ standard library) should be enough:
char str[] = "%fds%f%dssa%sss";
char *first, *last;
for(first=str;;) {
last = first + strcspn(first, "%");
if (first != str) { ... |
65,320,302 | 65,327,682 | Access to own private constructors via derived class constructor inheritance | Consider:
struct B {
void f();
private:
B(int, int = 0);
};
struct D : B { using B::B; };
void B::f() {
auto a = D{0};
auto b = D(0);
auto c = D(0, 0);
D x{0};
D y(0);
D z(0, 0);
}
GCC accepts (since 7.1; previously rejects all).
Clang accepts b and xyz but rejects a and c.
MSVC rejects... | There were a lot of issues with the original specification of inheriting constructors (as they were then called), several of which involved access control. They were fixed retroactively, which is supposed to be official for C++14 only (as the most recently published standard at the time). Many compilers choose to app... |
65,321,594 | 65,321,790 | Is there no way to have shared_ptr be silently created? | Consider the following code:
#include <memory>
class A {};
class B : public A {};
void func( std::shared_ptr<A> ptr )
{
}
int main( int argc, char* argv[] )
{
func( std::shared_ptr<A>( new B ) );
}
The syntax std::shared_ptr<A>( new B ) requires A class to be specified. It's a pain if the class is in a namespac... |
but that's not what std::make_shared is meant for.
On the contrary, this is an ideal use case for std::make_shared:
func(std::make_shared<B>());
Not only was no need to specify A, but also we have the advantage of the pointed object and the control block having a shared allocation.
Your example has undefined behav... |
65,321,817 | 65,323,986 | How to save value from class in TextCtrl | I'm trying to print the result of oblicz.suma(rzeczywiste,urojone) in TextCtrl5.
I'm getting error:
cannot convert 'Zespolona' to double in initialization
My code:
struct Zespolona
{
double re {0.0};
double im {0.0};
};
class Obliczenia
{
public:
Zespolona suma( const Zespolona& a, const Zespolona& b )
... | For people who have a similar problem.
wxString wynik;
wynik.Printf("%.f+%.fi", liczba_suma.re, liczba_suma.im);
TextCtrl5->SetValue(wynik );
|
65,321,868 | 65,322,263 | How to define std::tuple<...> with number of arguments | I need to interface with code that uses (misuses) tuples on the form:
using Tuple = std::tuple<double, double, double, double, int, int, int, int>; // etc..
I wonder if there is a way to define this tuples with templates instead in the form:
using Tuple = SomeType<4, double, 4, int>::Type; // expands to the above tupl... | I am not aware of some std facility that does what you want directly.
The tricky part is to have a variadic template with mixed non-type and type parameters. The issue can be avoided by using a helper:
template <typename T,size_t reps>
struct repeated_type {
using type = T;
static const size_t N = reps;
};
Usa... |
65,322,071 | 65,322,328 | -1073741571 (0xC00000FD) error in code block c++ | I need to generate a large number of random alphanumeric string, it is okay with the size below 10000, but when I tried to create the size 100,000, it returned the error -1073741571 (0xC00000FD) and my code won't run. Please tell me what is the error and how to solve it.
Below are my codes:
#include <iostream>
#include... | The error is because of these lines:
const int n = 100000;
string data_set[n];
because you are storing this on the function stack, so that stack of the program is not big enough that can hold this that causes bug. If you decrease the size of n it compiles and runs fine.
to avoid this better use heap allocation... |
65,322,311 | 65,322,403 | How to create vector<Mat>? | I try to run this code to crate a vector<Mat>
vector<Mat> scoreImgs(8, Mat(size, CV_32FC1));
I found it was not deep copy. I don't want to use for or while like:
for (int i = 0; i < 8; ++i)
{
scoreImgs[i] = move(Mat(size, CV_32FC1));
}
So how can I create a vector<Mat> with deep copy.
| vector<Mat> scoreImgs;
std::generate_n(std::back_inserter(scoreImgs), 8,
[]() { return Mat(size, CV_32FC1); });
It might be useful to write helper function:
std::vector<Mat> vectorOfNClonedCvMat(cv::Mat toClone, size_t n)
{
std::vector<Mat> r;
r.reserve(n);
std::generate_n(std::back_inserte... |
65,322,339 | 65,346,343 | How to use Julia special functions inside c++ | Hi I want to use the special functions of Julia implementation
(https://juliamath.github.io/SpecialFunctions.jl/dev/functions_list/) inside c++.
Following the manual (https://docs.julialang.org/en/v1/manual/embedding/) I could not achieve so far.
For functions like sqrt we have something like
jl_function_t *func1 = jl_... | I answered this question in the other stackoverflow thread.
Basically, the easiest thing to do is to use the Julia @cfunction construct to let Julia compile the code into a C++ function pointer, which you can then call normally without worrying about unboxing etcetera.
(For passing complex numbers, @cfunction can explo... |
65,322,510 | 65,322,560 | Rewrite C++ bitshift operator in Python | I have this code in C++:
#include <iostream>
using namespace std;
int main()
{
unsigned char v1;
v1 = 23 << 6;
cout << "v1: " << (int)v1;
return 0;
}
When I execute it, it gives me result of 192.
But when I do the same (23 << 6) in Python I get 1472 instead of 192.
What am I doing wrong here? Do you... | 23 << 6 is performed as an int in C++, but assigning it back to an unsigned char truncates it to its bits size (8 on any platform where Python runs). So, to obtain the same value in Python you have to do (23 << 6) & 0xFF.
On the other hand, to obtain the "correct" (non-truncated) result in C++ just assign it to an unsi... |
65,322,633 | 65,323,484 | Can I / how can I treat a pointer to a field's member as a pointer to member? | I have to create a mapping between an enum, and the fields of my object.
enum E {
FIRST,
SECOND,
THIRD
};
struct A {
int i;
int j;
};
I could do that the simple way with a get and set function and a switch-case, but let's suppose I'm a maniac and writing two lines instead of one for every enum value bo... | You could use a map of function pointers instead of member pointers.
Also, since your keys are integers starting from 0 and the structure is presumably not dynamic, a more efficient map is an array.
Example:
using get = int&(B&);
constexpr get* m[] = {
[](B& b) -> int& { return b.k; }, // FIRST
[](B& b) -> in... |
65,323,028 | 65,328,336 | Thread local real usage of the underlying segment registers | I read a number of articles and S/O answers saying that (on linux x86_64) FS (or GS in some variants) references a thread-specific page table entry, which then gives an array of pointers to the actual data that is in sharable data. When threads are swapped, all the registers are switched over, and the threaded base pag... | In 64-bit mode, the actual contents of the 16-bit FS and GS segment registers are normally the "null selector" (0), because other mechanisms are used to set the segment bases with 64-bit values. (MSR or wrfsbase)
Like in protected mode, there are separate "FSBASE" and "GSBASE" registers within the CPU, and when you sp... |
65,323,612 | 65,323,776 | User overloads of std::size? | Is it standards-compliant to add overloads of size in the std namespace? I have a class which I can't change, but I'd like std::size also to work for it; in a generic setting.
| From cppreference:
It is undefined behavior to add declarations or definitions to namespace std or to any namespace nested within std, with a few exceptions noted below
And further down on the same page (until C++20):
It is allowed to add template specializations for any standard library function template to the nam... |
65,323,706 | 65,325,015 | c++ write vectors to hdf5-file without storing in array | I'm trying to store 4 vectors (of variable size, but all 4 have the same size) in an .h5 file.
Until now, I did it like this:
void write_file_h5(std::string filename,
std::vector<int16_t> &x,
std::vector<int16_t> &y,
std::vector<int8_t> &p,
std::vector<int32_t> &ts)
{
s... | This line
struct myEvent myEvents[x.size()];
creates a variable-length array which is a non-standard (in C++) array that is likely placed on the stack.
Replace that with a std::vector<myEvent> to allocate the memory on the heap instead.
void write_file_h5(std::string filename,
std::vector<int16_t> &x,
... |
65,324,170 | 65,324,429 | Find nearest bigger value for all elements of array | I'm looking for a fast algorithm (or any hints) to do this;
Formally, for each element ai of an array, find the index j which
j > i
ai < aj
j - i is minimum
Here is a sample and O(n^2) implementation
std::vector<double> v = { 3, 1.5, 4, 2, 5 };
std::vector<int> out(v.size());
for (int i = 0; ... | It could be done easily using stack in O(n) time complexity by following the steps mentioned below:
Step-1: Maintain a stack that could store indices.
Step-2: Iterate through the array and check the following condition:
Condition: If the element of the array at the index at top of the array is less than the element at... |
65,325,455 | 65,325,556 | C++ recursive struct comparator | I have created a struct to use as a key in a map to avoid having duplicate elements.
The struct contains pointers to children and siblings of its own type.
For the map, I have created a custom comparator that is supposed to recursively look at the element, the children and the siblings until a difference is found to ma... | Consider A = (child = 5, next = 6) and B = (child = 6, next = 5). Now A<B is true as (A.child < B.child) is true and it just returns that. Now consider B<A. B.child < A.child is false, so it checks the next fields.. Now B.next < A.next is true, so your comparison returns true.
So this is nonsensical -> A<B is true and ... |
65,325,683 | 65,326,149 | Is b2Body::SetUserData deprecated | I'm setting up a box2d body, using some old code for reference, in my old code I have right at the end of setting up the body, this line
body->SetUserData(this);
and if I look at the box2d source code, I can find this function
inline void b2Body::SetUserData(void* data)
{
m_userData = data;
}
however when I try s... | After further investigation I found the function had been depracated, as the set up for user data had been changed to have a wrapper struct.
the old set up was as follows:
class b2Body
{
public:
/// Get the user data pointer that was provided in the body definition.
void* GetUserData() const;
/// Set the u... |
65,325,841 | 65,371,093 | AMediaExtractor gives an error in one case and doesn't in other, why? | I need to pass to MediaExtractor the data, for this purpose I use this method SetDataSource
https://developer.android.com/ndk/reference/group/media#amediaextractor_setdatasourcefd
Like this:
int32_t NDK_extractor::decode()
{
FILE *fp = nullptr;
media_status_t err;
AMediaExtractor *ex = AMediaExtractor_n... | As a result, the problem turned out to be that AMediaExtractor_setDataSourceFd method accepts a file descriptor as a parameter. In order to get a file descriptor from FILE, you need to call fileno() method on FILE that was opened with fopen() then everything works well, but if the file was opened with fmemopen() then f... |
65,325,944 | 65,373,441 | no member named 'KInt16' in namespace 'torch' | I am working on a cpp extension for pytorch, and followed the official tutorial, using libtorch and cmake to compile the program. But I met the problem of creating tensor.
This code can work.
#include <torch/torch.h>
#include <iostream>
int main(){
std::vector<int64_t> test_data = {1, 2, 3, 4, 5, 6, 7, 8, 9};
t... | As explicitly stated by the error message, you made a typo : you should have written
torch::kInt16 instead of torch::KInt16. The k should not be capitalized.
|
65,326,092 | 65,326,532 | User Input in 2-D array of dynamic size in C++ | I am trying to create a 2-D vector that as column 0 it would have integers and column 1 would have vectors.
For example:
column[0] column[1]
2 {2}
5 {1,2,0}
12 {4,7,9,0,0,1,6,0,0}
3 {6}
column 0 would be user input while column 1 I will calculate it on my own - I don't mind if it ha... | Seems like you need to use class:
#include <iostream>
#include <vector>
using namespace std;
template<class T1, class T2>
class Columns{
public:
vector<T1> input;
vector<T2> output;
};
int main(){
Columns<int, int> columns; //Or, if you need to have vector in "output": \
... |
65,326,140 | 65,326,461 | C++ Array Element Memory Alignment | Hi i've tried to give an array of for example point light positions to a shader. But this shader wants the vec3s to be aligned by 16 bytes not the 12 bytes from glm. For one vec3 there was no problem, you could just put "alignas(16)" in front of it. But for an array c++ just thinks that the whole array should be aligne... |
But for an array c++ just thinks that the whole array should be aligned by 16 and not its individual elements.
Indeed. That is what specifying alignas for an array means. The alignment of the array is affected; not the alignment of the elements.
two: to create a new struct like "16ByteAlignedVec3" , which contains t... |
65,326,306 | 65,743,146 | How to ofstream a numeric value in a .txt file and read same data through ifstream in same program | #include <iostream>
#include <fstream>
using namespace std;
int main()
{
string mobile;
int N[10];
ofstream file;
file.open("my.txt");
cout<<"enter mobile ";
getline(cin, mobile);
file<<mobile<<endl;
cout<<"enter number ";
cin>>N[10];
file<<N;
file.close();
int a;
cin... | #include <iostream>
#include <fstream>
using namespace std;
const int NUM = 10;
int main()
{
string mobile;
int n[NUM];
ofstream file;
file.open("my.txt");
cout << "enter mobile: ";
getline(cin, mobile);
file << mobile << endl;
cout << "enter number ";
file << n[0];
file.close(... |
65,326,399 | 65,326,429 | C++ weird rounding when decimal passed into function | I'm new to C++ and messing around with functions. I have two cpp files and one header. One of my cpp files is main.cpp where the following code is:
a->change(42.57);
I then have another cpp where the following code for change is:
bool Student::change(float mark)
and then the header where the following code is:
bool c... | 42.57 is a double type. (The nearest double is 42.57000000000000028421709430404007434844970703125).
Use 42.57f for a float type. (The nearest float is 42.56999969482421875).
Both therefore are approximations (the float is a looser approximation than the double) but at least your debugger will display the float more app... |
65,326,459 | 65,327,479 | Total running time calculation using Big-O Asymptotic analysis | int f1(int n)
{
int sum = 73;
for (int i=0; i < n; i++)
{
for (int j=i; j >= 5; j/2)
{
sum--;
}
}
}
I am calculating the Total Running time of this algorithm determining the cost of each statement.
I have got so far is this:
for(int i=0; i < n; i++) // runs in n t... | I think the Big-O will be O(n*Log2(n))
for(int i = 0; i < n; ++i) // n
for(int j = i; j >= 5; j /= 2) //log2(n) Because j is divided by 2 each step
sum--; // 1
|
65,326,489 | 65,326,765 | How to pass a two dimensional array parameter of a function as parameter of an inner function | I found out how to pass a two dimensional array as a parameter to a function and then do operations with its elements. My case however is more specific: A function has a two-dimensional array as a parameter, and its body contains another function, the parameter of which is that same array.
Here is my code:
#include <io... | The problem is in your function headers. The parameter value within the brackets is illegal. Change your code to work with array pointers instead:
double LineSUM(int N, double** matrix, int line)
{
double sum = 0;
for (size_t i = 0; i < N; i++)
{
sum = sum + matrix[line][i];
}
return sum;
}
... |
65,327,205 | 65,327,725 | std::shared_ptr concurrent access sanity check | I'm trying to make sure I correctly understand the semantics of std::shared_ptr, where:
Modifications to the underlying shared reference counter (std::_Sp_counted_base in the stdc++ implementation that ships with GCC) are thread-safe.
Access to a given instance of an std::shared_ptr is not thread-safe.
With that in m... | The other question you linked seems to provide the answer: it depends on what other threads may be doing.
A shared_ptr is not thread safe if it is used in a non-const way. However, you are only passing it in to the copy constructor (9), which accepts it as a const reference. If all other threads are accessing it in the... |
65,327,284 | 65,327,392 | C++ Undefined Reference When Compiling .h and .cpp in Subfolders | Long story short I want to put my .h and .cpp files in subfolders (include and src respectively) and reference them in my main.cpp file but I am receiving an error of:
main.cpp:(.text+0x47): undefined reference to `Kmer::Kmer()'.
when compiling using:
g++ -I /path/to/MyFolder/include main.cpp.
My files are structured l... | You are not compiling Khmer.cpp. You need to add it to your g++ compile line
g++ -o <YOUR APPLICATION NAME> -I /path/to/MyFolder/include main.cpp src/Khmer.cpp
|
65,327,938 | 65,439,495 | simple reading of a json file using Jsoncpp | If I have a json file:
{
"key1" : "value1",
"key2" : "value2"
}
using:
Json::Value root;
Json::Reader reader;
std::ifstream in(filePath.c_str());
if (!in)
{
std::string errReason("Cannot open the settings file '");
errReason += filePath;
errReason += "'";
throw std::domain_error(errReason);
}
bool... | The type of the variable 'names' is a Json::Value::Members, which is a vector of string (std::vector<std::string>) and is not a Json::Value, so you don't have to add asString() method.
so if you want modify the content of the 'key' value in 'root':
for (int index = 0; index < names.size(); ++index)
{
std::string ke... |
65,328,075 | 65,330,174 | Same Template struct, C++ | Consider I have structs RGB and ARGB.
template<typename T>
struct RGB {
T r,g,b;
};
template<typename T>
struct ARGB {
T a,r,g,b;
}
Now I define them by following.
using RGB_888 = RGB<unsigned char>;
using RGB_Float = RGB<float>;
using ARGB_8888 = ARGB<unsigned char>;
using ARGB_Float = ARGB<float>;
At some ... | It seems you want overloads
template<typename Source, typename Dest>
void convert(const RGB<Source>& source, RGB<Dest>& dest)
{
// ...
}
template<typename Source, typename Dest>
void convert(const RGB<Source>& source, ARGB<Dest>& dest)
{
// ...
}
with usage
RGB_888 rgb888{123,22,311};
RGB_Float rgbFloat;
convert(rgb8... |
65,328,541 | 65,332,855 | How can I autoselect the Terminal when I run Visual Studio Code? | I have the C/C++ extension in Visual Studio Code. Whenever I build and run the program ( usually I do that by the keyboard shortcut CTRL+ALT+N, instead of clicking on the Run icon ) I find it annoying to press every single time on the Terminal zone, in order for me to give my program an input. Can I select a setting in... | You can't really run and focus on the terminal with the same shortcut unless you install some extensions. But you can focus on the terminal by using ctrl + `. You can also change the binding for that by going into:
file -> preferences -> Keyboard Shortcuts
And there you need to search for workbench.action.terminal.foc... |
65,328,779 | 65,330,919 | Why does this C++ snippet assigning a value to an rvalue compile? | I was reading through the third edition of Effective C++ and I was surprised that a snippet on page 18 compiles. Here is a snippet inspired from that (compiler explorer link):
struct Rational {
Rational(int numer, int denom): numer(numer), denom(denom) {}
int numer, denom;
};
Rational operator*(const Rational&... | a*b = c; calls the assignment operator on the Rational returned by a * b. The assignment operator generated is the same as if the following were defined:
Rational& Rational::operator=(const Rational&) = default;
There is no reason why this shouldn't be callable on a temporary Rational. You can also do:
Rational{1,2} =... |
65,328,784 | 65,329,198 | C++ function `getline()` doesn't work correctly for char[] | I need to extract the first 150 characters from a line and save them in a char[] array (no strings allowed). My code below doesn't work and i just can't find the reason why:
#include <ifstream>
#include <iostream>
using namespace std;
int main()
{
ifstream myFile;
myFile.open("message.txt");
if(!myFile.is_o... | If you are trying to read the first 150 characters of the 1st line, then you don't need the while loop. And you don't need to null-terminate the buffer manually, istream::getline() will do that for you, eg:
#include <ifstream>
#include <iostream>
using namespace std;
int main()
{
ifstream myFile("message.txt");
... |
65,329,201 | 65,333,235 | Behaviour of uninitialized C++ structs | Say we declare an array of structs in a local scope:
int main()
{
RandomStruct array [1000];
}
Currently the structs in the array are uninitialized. While this means that the struct variables are also uninitialized, does this also mean anything else? Like if I, for example, set all the variables from an unitia... |
Currently the structs in the array are uninitialized
No, they are default-initialized.
While this means that the struct variables are also uninitialized
The effect on the members depends on the definition of RandomStruct. Depending on that definition, default-initialization of RandomStruct may have the effect of de... |
65,329,306 | 65,329,883 | Arrays - using user input | I am creating a code where we take an array of float and print its contents to the nearest integer - the rounding couldn't be done by a special library. I spent time doing the rounding portion, but I need to have the array's contents come from the keyboard and am trying to figure out where (at what point) that needs to... | Try something like this. To have more flexible application you need to create dynamic array of floats. After that use it and when array is not needed anymore you need to deallocate memory which is occupied by size of array which contains floats. Here is some source to learn more about dynamic memory.
std::cin (cin) is... |
65,329,332 | 65,330,479 | How do I solve the Visual studio 2019 'invalid profile ms_6_5' error when building a solution? | Specs are Window 10 Pro, VS 2019.16.8.3, MS DX12 shader samples.
I installed VS2019 just for this project to migrate my shader efforts into.
1>D3D12MeshletGenerator.cpp
3>dxc failed : Unknown argument: '-Qembed_debug'
2>FXC : error : invalid profile ms_6_5
This:
D3D12_FEATURE_DATA_D3D12_OPTIONS7 comes up undefined in t... | You need to install the Windows 10 SDK (19041).
D3D12_FEATURE_DATA_D3D12_OPTIONS7 was added to d3d12.h for this release.
The DXIL Compiler (DXC.EXE which unfortunately Visual Studio still calls 'FXC' in the output) was updated to support amplification & mesh shaders,
To install the new SDK you need to run the Visua... |
65,329,616 | 65,329,754 | Sort a string based on the order of another string | I was tasked with ordering a string based on another string assuming everything in the string is also in the sorting string
E.G.
s = "Hello World"
orderString = " odlehwr"
output: " oodlllehwr"
I managed to do it in O(nlogn) time, but I was told after that it should be O(n + m) time and I just don't see how it's possib... | You actually don't need to do any sorting at all here. Since you know that you only have m unique characters, you can make m buckets (in code, this would probably look like a dictionary or a hash table). Then you just need to keep a count for each character.
After that, it's just a matter of looping through the sorted ... |
65,329,846 | 65,332,129 | Abstract variable to be initialized on constructor | I have a class (let's call it Example) that has itself a variable child.
This variable is an object of either class Child1 or Child2 which are both childs of an abstract class Father. I would like for this to be defined on the constructor. This is what I try:
class Example {
public:
Father child; //This does not w... | Assuming your Child1 and Child2 are derived from Father, this is a standard case for dynamic polymorphism. You need to hold a pointer (usually a smart pointer) instead of the object itself:
class Example {
public:
std::unique_ptr<Father> child;
};
Example::Example(bool use_1) {
if( use_1 ) { child = std::make_... |
65,329,850 | 65,330,094 | Evenly distribute number into array of n elements with equal values | I'm trying to divide x into y parts and they should be as evenly distributed as possible.
As an example:
if x = 5 and y = 3 I'd like to have arr = [1, 2, 2].
The solution I came up with basically prints [1, 1, 3] which isn't as evenly as possible distributed.
int *arr= (int *)malloc(y* sizeof(int));
for (int i = 0; i... | I simplified to only printing the numbers you want.
First print x/y+1 as often as you have remainder (I.e. modulo), then print for the rest of the needed numbers only x/y.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 5;
int y = 3;
int i=0;
for (; i < x%y; i++)
{
printf("... |
65,330,067 | 65,330,362 | Perfect forwarding fails to link with explicit template instantiation directives (EIDir; a.k.a. manual instantiation) | The question is why does the linker fail (g++, ver. 7.5, Ubuntu 18.4) to perfect forward a constructor of a template class, when the constructor definition is hidden in the implementation file (*.cpp) but explicitly instantiated in the main.cpp?
Specifically:
fwd_machine.hpp:
#include <memory>
#include <stdexcept>
tem... | Class template @ cppreference
The complete definition must appear before the explicit instantiation of a class template
This is not the case in your program when you try to instantiate it in main.cpp.
The correct way to explicitly instantiate some_type<int> would be to add
// in fwd_machine.hpp
extern template class ... |
65,330,385 | 65,330,418 | find a value in a C++ map: no matching function for call | Please consider this C++ code:
#include <iostream>
#include <map>
// Global vars
std::map<int, char *>OurMap;
std::map<int, char *>::iterator it;
// prototypes
void populate();
void iterate();
int main(){
puts("Hello, world!");
populate();
iterate();
return 0;
}
void populate(){
//char temp[51... | When you iterate over a map using a range-based for loop, you are not getting iterators back, but instead the (key, value) pairs themselves. So
for (auto i : OurMap){
printf("i: %d\n", i);
std::cout << "Value: " << OurMap.find(i)->second << std::endl; // <- blows up
}
Should simply be
for (auto i : OurMap){
... |
65,330,399 | 65,330,727 | Print Vector from Class | I am trying to read a data file into a vector and print the values through class. When compiled there are no errors, but the program just stops after opening the file. Can't seem to figure out the problem.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstring>
#include <vector>
#include <cmath>
us... | I've debugged it. Just take out
for (int i = 0; i < time.size(); i++)
{
}
but leave in the
time.push_back(t);
inside it, and it works fine.
I gave it a text file with four numbers in it separated by spaces, and it printed them out.
Since time never gets anything pushed back into it, it is always zero size; thus the l... |
65,330,460 | 65,331,535 | How do I get binary equivalent string of a given uint512_t integer | I'm using a boost/multiprecision uint512_t and I've tried using bitset library but it wont work for big integers like uint512_t. How can I convert it?
This is what I've tried with no success
#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
#include <string>
using namespace boost::multiprecision;
int ma... | There are probably more elegant ways to do this, but I couldn't find any, so here goes.
You can use a bit mask to extract bit-by-bit and put it in a bitset<512>.
#include <boost/multiprecision/cpp_int.hpp>
#include <bitset>
#include <iostream>
int main() {
using namespace boost::multiprecision;
uint512_t num... |
65,331,522 | 65,337,926 | c++ template argument deduction in function prototype. possible workaround in this case? | Primer
I have a Vector class that does some math. Among other things, it has a mean() function that calculates the mean of all values inside the vector. It uses a sum() function that i added here just for completeness.
Vector
template <std::size_t N, typename T>
class Vector{
public:
// ...
T sum() cons... | Thanks to @Jarod42 and @HTNW i was able to hack it into a single function.
With class U = void and std::conditional it is possible to make the specification of U optional for the caller.
template <class U = void, std::size_t N, typename T>
auto mean(const Vector<N, T> &v) {
return v.template mean<std::conditional_t<s... |
65,331,719 | 65,331,786 | How can I implement a function, which is specified with an "extern" clause in a C header, within a C++ class? | I'm gonna use a driver library implemented in C in my project written in C++. The library's header file contains a number of function stubs declared as extern I will have to implement:
extern uint8_t ADS1x1x_i2c_start_write (uint8_t i2c_address);
My C++ code now contains a class named vfd, which will contain static me... | You cannot. You can implement these C functions in your C++ file separately and make them call your static functions inside the class:
extern "C" uint8_t ADS1x1x_i2c_start_write (uint8_t i2c_address) {
vfd::ADS1x1x_i2c_start_write(address);
}
They're static, right? Otherwise you also have to provide a this object ... |
65,332,141 | 65,490,942 | Cant compile c++ on OS X Big Sur, "ld: library not found for -lgcc_s.10.4" | After upgrading my MacBook Pro to OS X 11.1 Big Sur, I am unable to get compilation of c++ programs using gcc to work.
I am using CLion with CMake, and I get the following error when reloading the CMake configuration
ld: library not found for -lgcc_s.10.4
The things that I have tried are installing Xcode, it installed... | Thank you for all the answers highlighting different things that could solve the issue. What ended up working was to run brew reinstall gcc, and pointing CLion (or plainly CMake as Mike mentioned) to use the correct compiler (something that I had already done, but I want to mention it here if anyone else finds this que... |
65,332,198 | 65,332,343 | Template of method and vector of virtual object pointers | class Inventory
{
public:
Inventory();
~Inventory();
private:
//std::vector<std::shared_ptr<IItem*>> ItemList;
std::vector<IItem*> ItemList;
public:
template <class T>
void AddItem(T &item) {
this->ItemList.push_back(*item);
}
std::string Test(int);
void MoveItem(int, int);... | I'd probably not use templates for this.
if IItem is a base impl, then you could probably cast the object you push like so
inv->AddItem(static_cast<IItem*>(sword)) and define the AddItem method like so:
void Inventory::AddItem(IItem *itm){
this->ItemList.push_back(itm);
}
|
65,332,449 | 65,332,459 | How to fix arduino sequencer always outputting | I'm trying to code an Arduino rhythm sequencer I made, and there's a problem with the code right now, im using LEDs as outputs. When I turn it on, all of the LEDs blink on every beat, even though I have the array of notes all set to zero. I see no errors when verifying or uploading the code.
const int outPins[4] = {3,... | if (beats[i][j] = 1) is assignment. You wanted if (beats[i][j] == 1)
|
65,332,486 | 65,332,830 | how do i fix this logical error for displaying with 3d vector | i am receiving logical error where the expected ouput is not displayed, it should display do new, but only do is displayed.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<vector<vector<string>>> vec = {{{"do", "new"}}};
auto i=0,j=0,x=0;
for(i=0;i<vec.size();i++){
... | looks like you missed to index vec[i][j] while getting the size of the innermost vector.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<vector<vector<string>>> vec = {{{"do", "new"}}};
auto i=0,j=0,x=0;
for(i=0;i<vec.size();i++){
for(j=0;j<vec[i].size();j++){
... |
65,332,583 | 65,332,938 | C++ timezone offset to parsed time | I have some code that uses Howard Hinnant's date Library to parse microsecond enabled timestamps:
std::string time_test = "13:45:04.747334";
std::istringstream input(time_test);
std::chrono::microseconds current_time;
input >> date::parse("%T", current_time);
This yields the microseconds since midnigh... | To deal with local time you will need to install the "date/tz.h" library. This involves compiling one source file: tz.cpp and either allowing an automatic downloading the IANA timezone database, manually installing it yourself, or using your OS's copy (if available).
The easiest way to get the current local time is t... |
65,332,620 | 65,332,817 | Force C++ to assign new addresses to arguments | It seems that when I pass different integers directly to a function, C++ assigns them the same address as opposed to assigning different addresses to different values. Is this by design, or an optimization that can be turned off? See the code below for an illustration.
#include <iostream>
const int *funct(const int &x... | The function const int *funct(const int &x) takes in a reference that is bound to an int variable.
a and b are int variables, so x can be bound to them, and they will have distinct memory addresses.
Since the function accepts a const reference, that means the compiler will also allow x to be bound to a temporary int va... |
65,333,155 | 65,333,196 | Is possible to use container's size as priority_queue's priority in C++? | #include <iostream>
#include <queue>
using namespace std;
int main() {
priority_queue<vector<int>> q;
q.push({1, 2, 3});
q.push({3});
q.push({1, 2});
q.push({0, 1, 2, 3, 4});
while (!q.empty()) {
cout << q.top().size() << endl;
q.pop();
}
}
The above code will output
1
3
2
5
I want to get
1
2... | Looking at the documentation, something like this might work:
// Using lambda to compare elements.
auto cmp = [](const std::vector<int> &left, const std::vector<int> &right)
{
return left.size() < right.size();
};
std::priority_queue<std::vector<int>, std::vector<std::vector<int>>, decltype(cmp)> q(cmp);
|
65,333,678 | 65,333,768 | Is there a way to set an object member array size from a project's main program file that #includes the .h file used to declare/define the object? | For context, I'm working in c++ on a stm32f ucontroller doing embedded audio and trying to avoid dynamic allocation.
One of the classes I've written is a wavetable oscillator that is, for the scope of my question, essentially just a bunch of c-style arrays.
I have these files, among others, in a separate folder from th... | Since you include the c++ tag in your question and c++ language includes templates, then you can parametrize the size of a static array declared in another file from a MAIN.cpp file like this:
In MYCLASS.cpp (declared in MYCLASS.h)
template <unsigned int BYTES>
class CBase
{
public:
char Arr[BYTES];
int Fn1(vo... |
65,334,390 | 65,635,992 | C++: How do I create a collection field for storing a finite number of instances of a class? | I have a problem that requires I track tickets sold at a theatre. To do this I need to create a ShowTicket class. The class should contain a collection field for the rows, seat numbers, and whether the tickets have been sold or not. The class only needs to support 10 sold tickets. Assume a ticket that is not referenced... | Credit to Jerry Jeremiah:
#include <iostream>
#include <string>
#include <map>
class ShowTicket {
using TicketsMap = std::map<std::pair<std::string,std::string>,bool>;
static TicketsMap tickets; // needs to be defined outside the class
public:
bool is_sold(std::string row, std::string seat_num){return tick... |
65,334,687 | 65,334,715 | Compose functions with template in C++ got segmentation fault | I'm trying to write a demo to chain various functions into one, just like chain(f, g)(x) = g(f(x)), it is OK when I chain lambdas, but with named functions, I got a segmentation fault, I'm now struggling with it.
My code:
template <typename F, typename G>
constexpr auto chain(F&& f, G&& g) {
return [&](auto x) {
... | Your non-variadic chain function template returns a lambda that captures the arguments f and g by reference. These references are dangling when you return from chain, and invoking the returned lambda invokes undefined behavior.
As is the case with undefined behavior, it can appear to work sometimes, and can cause a seg... |
65,334,850 | 65,334,964 | How to create ofstream file with the name of (integer type) variable? | int a
cin>>a;
ofstream file;
file.open("a.txt");
I want to create a .txt file with the code entered by the user. Please help.
| Need to convert the input to std::string:
int a;
cin>>a;
ofstream file(std::to_string(a) + ".txt");
|
65,335,058 | 65,335,085 | get non-type template parameters into tuple | How does one construct a tuple with non type template parameters
template <auto... args>
void func()
{
std::tuple<decltype(args)...> t(args...);
cout << get<3>(t) << endl;
}
template <auto... args>
struct ZZ
{
std::tuple<decltype(args)...> t(args...);
};
int main()
{
func<1,2,3,4>();
ZZ<1,2,3> z;
}
Whil... | The problem is, the default member initializer (since C++11) supports braces and equal-sign initializer, but not parentheses initializer. You can change the code to:
template <auto... args>
struct ZZ
{
std::tuple<decltype(args)...> t{args...};
// ^ ^
};
Or
template <auto... args>
... |
65,335,423 | 65,335,524 | C++ Copy Raw std::bytes to std::vector<std::byte> | I have an FILE_NOTIFY_INFORMATION struct which i have filled like this:
FILE_NOTIFY_INFORMATION* fni = new FILE_NOTIFY_INFORMATION;
fni->Action = 1;
wcscpy_s(fni->FileName,12, L"example.txt");
fni->FileNameLength = 12;
fni->NextEntryOffset = 0;
I have then castet this Struct to an std::byte*.
auto fni_as_byte = reinte... | Your code is corrupting memory, as the actual size of FILE_NOTIFY_INFORMATION is variable length. See Why do some structures end with an array of size 1?. You are not allocating enough memory to hold the string you are copying into the FileName. To allocate your FILE_NOTIFY_INFORMATION correctly, you would need to do ... |
65,335,454 | 65,336,698 | Target based members in ANTLR4 | Is there a way to distinguish language targets and provide appropriate version of @members in a grammar file? Different language targets use different comment and syntax. I would like to maintain the same grammar file for different target languages.
For Cpp (C++) target:
@members {
// C++ target:
bool a_boolean =... | Nothing of that is possible. It's a simple copy-paste operation which ANTLR4 performs on parser generation, including all whitespaces like indentation + line breaks.
The only option you have is to distinguish between C++ and all other targets, because for C++ I have introduced additional named actions, like @parser::de... |
65,335,773 | 65,335,877 | How to overload object = constant int + object | #include<iostream>
using namespace std;
class mango
{
public:
int qnt;
mango(int x = 0)
{
qnt = x;
}
mango operator+(const int a)
{
mango temp;
temp.qnt = a + this->qnt;
return temp;
}
};
int main()
{
mango obj(5);
obj = obj + 5;
cout<<obj.qnt<<e... | It's simple, define the overload out of class
class mango
{
...
};
mango operator+(const int a, const mango& b)
{
...
}
In fact it's generally reckoned that all symmetric and anti-symmetric operators should be defined out of class. So your mango + int should also be moved out of the class.
mango operator+(con... |
65,336,095 | 65,336,151 | How would I go about storing words from a plain text file to an array using C++? | I've been tasked with writing a C++ program that opens a text file, determines the length of each word, then produces output stating how many times a particular word length occurs.
I've figured how to open and read the contents of the file.
How would I take each word and store them in an array?
#include <iostream>
#inc... | You do not store words in an array.
You only need to store the word lengths and how often each of them occurred.
If you have a guaranteed and low maximum word length you can even simplify by using an array where the length of the current word is used as an index. Init all entries with 0. Then count entries up when the ... |
65,336,494 | 65,357,594 | How to read the battery level in Ubuntu? | I've searched for a while on how to do this without any special library or anything, and it took a while to find something that's working properly.
It's possible to use
/sys/class/power_supply/BAT0/subsystem/BAT0/charge_now
/sys/class/power_supply/BAT0/subsystem/BAT0/charge_full
I was wondering, is there a better way ... | In case this is never answered.. this is my solution:
#define PATH_BATT_CHARGE_NOW "/sys/class/power_supply/BAT0/subsystem/BAT0/charge_now"
#define PATH_BATT_CHARGE_FULL "/sys/class/power_supply/BAT0/subsystem/BAT0/charge_full"
int getBattState(void)
{
int chargedPercent = 0;
FILE *battChargeNow;... |
65,336,866 | 65,337,887 | Arduino: how to move a servo based on difference of resistance in photoresistors | I am trying to make a solar panel that tracks the sun and in order to do that I am using 4 photoresistors. I am very new to coding but I have already coded the part that determines the resistance of the photoresistors (for now I'm only trying with 2). I need to get a servo to move in a certain direction depending on w... | Your for loop is wrong, it has four arguments. I would suggest putting the R1 < R part around your for-loop in an if-condition. Right now, your for loop also starts at pos = 180, is incremented, but the condition is pos <= 0. Vice versa for the second loop. Your increment/decrements and conditions are wrong. This loop ... |
65,337,021 | 65,339,080 | error: declaration of ‘operator*’ as non-function | I have some problems with bound template friend functions of template classes.
I've refered the page which has the similar and simple problem as me: vect.hpp:13:33: error: declaration of ‘operator<<’ as non-function
, but I still confused, the problem cannot be solved. Here are my codes:
#include<iostream>
#include<v... | I found that the most robust way to deal with friend operators in template classes was to put the full definition in the class itself:
//forward declaration
template<typename ElemType, size_t row, size_t col = row>
class matrix;
/*
template<typename ET, size_t R, size_t C>
matrix<ET, R, C> operator*(ET multier, matrix<... |
65,337,094 | 65,338,810 | How to mock a Function arguments with no operator== using Gmock | I am using Gmock for unit tests.
I have function who receive protobuf message as an argument.
The problem is that when I'm testing the function with expected value it gives me an error of missing operator==.
I found similar problem here google-protocol-buffers-compare
class ClientReaderWriterMock : public ClientReaderW... | When an expect call is set on a function with some arguments, the Eq matcher is used (implicitly), so the line:
EXPECT_CALL(*clientReaderWriterMockObj, Write(msg));
is actually:
EXPECT_CALL(*clientReaderWriterMockObj, Write(Eg(msg)));
Eq matcher will try to invoke operator== (which is missing as you noticed). In such... |
65,337,213 | 65,337,260 | percentage calculation in my function is not working | so what I am trying to do is take a vector of numbers, find the number of time each element occurs then calculate the percentage equivalent of its number of occurances in the vector.
it works perfectly well on a vector with a few elements of only one number but not at all with a vector of different elements (2 to be e... | unsigned __int64 percentage = static_cast <unsigned __int64> (round((counts[y] / total) * 100));
should be something like
double percentage = round((100.0 * counts[y]) / total);
Your problem is that when you divide one integer by another you always get a integer. So (counts[y] / total) is always going to be 0 or 1.
S... |
65,337,571 | 67,950,394 | FFTW reentrancy in plug-in based programs | I'm developing a cross-platform application (Win / Mac / Linux). This application loads plug-ins that I don't control as dynamic libraries, which may do various things, mostly audio and image processing.
Some of these plug-ins may use FFTW as part of their implementation details. (This is not an hypothetical case - I a... | It turns out that FFTW provides the void fftw_make_planner_thread_safe(void) function which does ensure that plug-ins will be able to run plans in separate threads.
Calling it at the beginning of the program is enough.
|
65,337,598 | 65,337,815 | Why is there no warning or error when initializing a const pointer to null? | This might be a very basic question, but I tried to find the answer in SO and couldn't find the exact answer to it.
What's the point of initializing a const pointer with nullptr?
int *const pi = nullptr;
Why does the compiler not emit a warning or error, seeing how pointer pi can't be used effectively anywhere in the ... | Although I agree that initializing a const pointer to nullptr isn't generally especially useful, one situation where it may me appropriate is where you would conditionally define the const pi pointer to either nullptr or some other (valid) address, depending on a compile-time setting, like in the following example. (Th... |
65,337,716 | 65,338,949 | Can child class use a template parent's static methods? | I have a template parent class, and multiple child classes. I want to make a static method that takes any child class and returns a child class, but I want to write that in the parent class, so I don't have to manually write it for each child. How do I do that? I have:
#include<iostream>
using namespace std;
template... | Consider the statement...
Child2 B = Child2::Inverse(&A);
Child2::Inverse has return type Parent so you are trying to implicitly convert a Parent to a Child2. That won't work.
One option would be to use CRTP to inject the subclass name into Parent...
template<typename P, typename T>
class Parent
{
public:
T x;
T ... |
65,337,821 | 65,337,893 | I can't get it to display the updated temperature | I'm trying to make it so that if the user chooses 1, it should increase the temp by 5, and decrease if the user chooses 2. the problem I'm having is that it doesn't update the value of the temperature.
UPDATE: I've finally got the math part to work but for some reason when i print the value of temperature it doesn't sa... | In int heater::warmer(int temperature) parameter named temperature shadows class member called temperature and you only modify that local parameter.
Simply remove that parameters and modify your class member:
#include <iostream>
using namespace std;
class heater
{
public:
int temperature;
heater()
{
... |
65,337,885 | 65,338,178 | How to call c++ function from windows form | My c++ function is given below,
# define MyFunction _declspec(dllexport)
extern "C" {
MyFunction int AddNumbers(int a, int b)
{
return a + b;
}
MyFunction int SubtractNumbers(int a, int b)
{
return a - b;
}
}
Calling c++ function from windows application is given below
private void btnNumber_Click(object... | Please try hard code the absolute dll path or put in your corresponding debug bin folder.
The msvc will resolve path in current directory / System folder: e.g. C:\windows\system32 / $Path environment variable.
|
65,338,355 | 65,339,036 | buttons are all highlighted | I have two buttons. Each button is highlighted instead of just the first one. How do I make the first button to be only the one highlighted?
BTW This is the code for the two buttons:
openFileButton = CreateWindowA("button", "Open File and start hashing", WS_VISIBLE | WS_CHILD | SS_CENTER, 220, 210, 200, 50, hWnd,
... | First, stop calling the A versions of WinAPI functions. Those went obsolete back in the '90s. Use the W versions instead, with L prefixes on your string literals and wchar_t as your character type.
Second, you are passing the wrong style flags for buttons. Specifically, you are passing SS_CENTER. This is a style for st... |
65,338,601 | 65,338,813 | Why I have StackOverflow in DFS? | I'm trying to implement a DFS algorithm in c++. I use it to answer the question: "are two vertexes connected or not?", but something went wrong.
Sometimes the program gives correct answer, sometimes crashes with 0xC00000FD code. I've google it and know now, that is a StackOverflow error.
Here's the code:
const int N = ... | This is because your code is visiting a particular node more than once, because of which your code runs into an infinite recursion.
Because of the infinite recursive calls, the stack memory gets filled up completely and finally results into a stack overflow error.
Solution: Allow every node to be visited almost once by... |
65,338,697 | 65,338,766 | Are the addresses of two temporaries guaranteed to be different in the same expression? | Consider the following program:
#include <iostream>
int const * f(int const &i)
{
return &i;
}
int main()
{
std::cout << f(42); // #1
std::cout << f(42); // #2
std::cout << f(42) << f(42); // #3
}
Depending on the compiler, and optimization level that is set, the addresses printed on lines #1 and #2 ... | Two alive objects in C++ (almost) always have different addresses.
Since temporaries in #1 #2 have non-overlapping lifetimes, the compiler is free to reuse the storage of #1 for #2 .
But in #3 all temporaries are alive until the end of the expression (for obvious reasons) and in this case they have to have different ad... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.