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 |
|---|---|---|---|---|
70,411,048 | 70,411,599 | Memory allocate in c++ | I have a project in which I have to allocate 1024 bytes when my program starts. In C++ program.
void* available = new char*[1024];
I write this and I think it is okay.
Now my problem starts, I should make a function that receives size_t size (number of bytes) which I should allocate. My allocate should return a void* ... | It looks like you're trying to make a memory pool. Even though that's a big topic let's check what's the minimal effort you can pour to create something like this.
There are some basic elements to a pool that one needs to grasp. Firstly the memory itself, i.e. where do you draw memory from. In your case you already dec... |
70,411,072 | 70,411,282 | How to make a loop to determine if 2 numbers belong in a given range | I am having problems making a loop which stops when both x and y are in the range/interval [0,1] in c++.
double x;
double y;
while(condition)
{
if(x < 0)
{
x = -x;
}
else
{
x = 2 - x;
}
if(y < 0)
{
y = -y;
}
else
{
y = 2 - y;
}
}
This me... | while ( !( (x>=0 && x<=1) && (y>=0 && y<=1) ) ) should be the combined conditional check.
|
70,411,268 | 70,411,403 | Should we NULL every raw pointer after it is used? | int *a;
if (true)
*a = 2;
else
*a = 3;
As you see, a is not a dynamically allocated pointer. Should I assign it to nullptr before exiting? Does unique_ptr do for me automatically? What about the memory pointer to by a? If I null a before it goes out of scope, will it cause a memory leak?
|
int *a;
if (true)
*a = 2;
The behaviour of this program is undefined. a does not have a valid pointer value, so you may not indirect through.
Should we NULL every raw pointer after it is used?
It depends. For example, if the lifetime of the pointer is about to end, then it's redundant to assign it to null.
Do... |
70,411,286 | 70,419,938 | SVM allocation in OpenCL C++ | In the case of cl_context and cl::Context, we can do:
cl::Context context_ = cl::Context(device);
cl_context context = context_();
Now, I have an OpenCL program, with the following snippet in it:
...
void* svm_data = clSVMAlloc(context, svm_flags, svm_buffer_size, 0);
...
I would like to do something similar here to ... | Looks like you need to allocate the shared virtual memory using the allocator to get the pointer to it:
cl::SVMAllocator<int, cl::SVMTraitAtomic<>> svm_allocator(context);
std::size_t num_elements = 4;
int* svm_data = svm_allocator.allocate(num_elements);
The SVM allocator holds only the context and the flags that ar... |
70,411,314 | 70,411,808 | Is it possible to initialize the template inner class in the C++20 requires clause? | Consider the following class A that defines a template inner class B:
struct A {
template<class = int>
struct B { };
};
We can use the following expression to initialize inner B, where typename is optional: (Godbolt)
int main() {
A::template B<>();
typename A::template B<>();
}
I want to use concept to detect... | My understanding of concepts is, that if you want to check such cases, you have to use the compound statement.
struct A
{
template<class = int>
struct B { };
};
template<class T>
concept C = requires
{
{ typename T::template B<>() };
};
static_assert(C<A>);
I believe you can't use it within a simp... |
70,411,448 | 70,411,524 | Cpp predefined structs? | Last time I used C++ was when I attended university, therefor I am not very fluent in it.
I wanted to create a small game, and because I am used to C# I wanted to create predefinded struct objects.
Here is the C# code for reference:
public struct Vector2 : IEquatable<Vector2>
{
private static readonly Vector2 _zeroV... | First off, with recent versions of C++, you can simplify your struct definition like this:
struct Vector2 {
float x{}, y{};
};
This guarantees that x and y are initialized with 0, you don't need the separate constructor as you show it. You can then use the struct like this:
Vector2 myVec; // .x and .y are set to ... |
70,411,495 | 70,581,660 | using unique_ptr with custom deleter for GError | using unique_ptr with custom deleter for c functions that return a ptr is pretty straight forward, but how would i use it for functions that take ptr of ptr as parameter (like GError)
I have faced this in couple of cases but but did not find a straightforward way to do this. am i missing something?
using Element = std:... | I found returning a tuple from a lambda to be marginally better,
auto [pipeline, err] = [&]() noexcept {
GError* err = nullptr;
auto* pipeline = gst_parse_launch(str, &err);
return std::tuple{Element{pipeline, object_unref}, Error{err, error_free}};
}();
|
70,411,580 | 70,411,690 | How to check whether a string input from the user contains a number or not? | The title says it all. I'm looking to check if a string contains even a single digit somewhere. No idea how to do this. If there is a pre-built function for this, I'd still like an unorthodox, long way of actually doing it (if you know what I mean).
Thanks!
|
If there is a pre-built function for this, I'd still like an unorthodox, long way of actually doing it (if you know what I mean).
You could just use a simple for-loop and check if any of the characters present in the string are digits and return true if any is found, otherwise false:
#include <string>
#include <cctyp... |
70,412,334 | 70,412,456 | How to filter inherited objects? | I have class Set which consists of dynamically allocated IShape where IShape is inherited by Square, Rectangle etc. and I need to make filter function to create new set of only certain type (E.g. Squares). Basically to go through existing set and pick only shape which is defined somehow (through parameters?) and create... | To avoid using dynamic_cast, have your IShape class declare a pure virtual function called (say) GetTypeOfShape. Then override that in each of your derived classes to return the type of shape that each represents (as an enum, say). Then you can test that in your filter function and proceed accordingly.
Example code:
... |
70,412,425 | 70,412,460 | Overriding method shadows overloaded final version | I have the following code:
struct Abs {
virtual void f(int x) = 0;
virtual void f(double x) final { std::cout << 2; }
};
struct Sub: public Abs {
void f(int x) final { std::cout << 1; }
};
Abs is an abstract class which comprises a pure member function void f(int) and its overloaded version void f(double... | Given x.f(1.01);, the name f is found in the scope of class Sub, then name lookup stops; the scope of Abs won't be examined. Only Sub::f is put in overload set and then overload resolution is performed.
... name lookup examines the scopes as described below, until it finds at least one declaration of any kind, at whic... |
70,412,738 | 70,412,759 | Why this string is not converting to Integer? | I'm trying to convert the string r to an int(num). But it keeps returning 0. Note: When I was returning the string, the answer(reversed number) was correct. My code looks like this:
string n, r = "";
cin >> n;
for (int i = n.length(); i >= 0; i--)
{
r += n[i];
}
in... | The value of the character n[n.length()] is equal to '\0'
That is when the index of the subscript operator is equal to the size of the string then it "returns a reference to an object of type
charT with value charT(), where modifying the object leads to undefined behavior." (The C++ Standard)
So your reversed string st... |
70,413,195 | 70,413,403 | Partial specialization of a nested class | How to partially specialize nested class without partially specializing the nesting class?
Implementation of class C is the same for all N.
Implementation of C::iterator is special for N=1.
template<class T, int N>
class C
{
class iterator;
...
};
template<class T, int N>
class C<T, N>::iterator
{
...
};
... | If you do not want to specialize whole class then just move the iterator out of class and make it template:
template<class T, int N>
class C_iterator
{
...
};
If needed make your specializations:
template<class T>
class C_iterator<T, 1>
{
...
};
Then use it in your class as iterator, if needed befriend it:
te... |
70,413,446 | 70,429,200 | Linearize nested for loops | I'm working on some heavy algorithm, and now I'm trying to make it multithreaded. It has a loop with 2 nested loops:
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
for (int k = j + 1; k < n; ++k) {
function(i, j, k);
}
}
}
I know, that the number of function calls w... | Yet another take on your problem. As said in the comments, what you are looking for is basically finding the successor and the unranking of combinations. For this I use the algorithms from the book 'Combinatorial algorithms' of Kreher and Stinson.
Here is the corresponding code consisting of the two functions next and ... |
70,414,371 | 70,490,852 | Usage of lambda in constant expression | Take the following code:
template <typename T, typename U>
constexpr bool can_represent(U&& w) noexcept
{
return [] (auto&& x) {
try {
return T(std::forward<U>(x)) == std::forward<U>(x);
} catch(...) {
return false;
}
} (std::forward<U>(w));
}
I am using this fun... |
[gcc] was getting hung up on the try, that normally wouldn't be allowed in a constexpr function.
This is correct for a C++17 program. (C++20 relaxed this, so a try block can now be used in a constexpr function. However, it is only the try that is allowed; it is not allowed for execution to hit something that throws a... |
70,414,405 | 70,414,422 | What am i missing that texture isn't working OpenGL | I'm trying to apply textures to a face for now until i get it to work properly, but everytime the application runs the face is just a white color as it is for default, yet i don't know what is going wrong.
LoadTexture function:
GLuint LoadTexture( const char* texture )
{
GLuint textureID = SOIL_load_OGL_texture( ... | The parameter of glActiveTexture is the texture unit:
`glActiveTexture(tex);
glActiveTexture(GL_TEXTURE0);
The texture object is bound to a texture unit. The current texture unit can be stet with glActiveTexture. The default texture unit is 0 (GL_TEXTURE0).
You cannot execute an OpenGL statement until you have a vali... |
70,414,454 | 70,414,523 | How function-level exception handling works? | There is the following code, from here
class Base {
int i;
public:
class BaseExcept {};
Base(int i) : i(i) { throw BaseExcept(); }
};
class Derived : public Base {
public:
class DerivedExcept {
const char* msg;
public:
DerivedExcept(const char* msg) : msg(msg) {}
const char* ... | Derived(int j) try : Base(j) {
// Constructor body
cout << "This won't print" << endl;
}
catch (BaseExcept&) { // why the thrown exception is not caught here
throw DerivedExcept("Base subobject threw");;
}
The only way for the program to output Base subobject threw is if the ... |
70,414,652 | 70,414,687 | How do I pass in a file name when creating them in C++? | I am newer to C++ and I am trying to make a simple log in system. I am currently working on the signing up a new user and I want to create a directory for that user that I can then save their information in later. I am able to make a directory called "User" but instead of User I want to pass in an argument but I am no... | Add #include <string> to the top of your source file
Change your MakeNewUserDir() function to be declared and defined as follows:
void User::MakeNewUserDir(const std::string& path)
You may need to make a similar change in your class declaration as well.
Then you invoke mkdir as follows:
check = mkdir(path.c_str(), 077... |
70,415,047 | 70,420,393 | How to decode (from base64) a python np-array and reload it in c++ as a vector of floats? | In my project I work with word vectors as numpy arrays with a dimension of 300. I want to store the processed arrays in a mongo database, base64 encoded, because this saves a lot of storage space.
Python code
import base64
import numpy as np
vector = np.zeros(300, dtype=np.float32) # represents some word-vector
vector... | Thank @Holt for pointing out my mistake.
First, you can't save the storage space by using base64 encoding. On the contrary, it will waste your storage. For an array with 300 floats, the storage is only 300 * 4 = 1200bytes. While after you encode it, the storage will be 1600 bytes! See more about base64 here.
Second, yo... |
70,415,053 | 70,449,886 | Qt(c++) Keybinding with button(for my developing application) | I want to write a function that will work with keybinding for the application I am developing on the Qt platform, but I could not find any example that will work for me, like the picture I added from the discord application, can you help me?
Discord keybinding
| If you want user to hit a key combination for a selection then just create a class inheriting QLinEdit (even QLabel would work) and override keyPressEvent,
void QLineEdit::keyPressEvent(QKeyEvent *event);
and then use QKeyEvents function to get key and modifiers (shift, ctrl etc.). Just read the Qt Docs about it. Depen... |
70,415,110 | 70,415,173 | Getting "No valid copy constructor" in C++ on return struct | I'm currently working on implementing a simple 2D vector class Vector2f in C++ using Visual Studio Community Edition 2019.
When I try to return a newly constructed one in a method, such as:
return Vector2f((this->x/sum),(this->y/sum);
I'm getting a hint:
no suitable copy constructor for Vector2f
and an on-compile er... | The parameter of the copy constructor has a non-constant referenced type
Vector2f(Vector2f& og);
In the member function normal there is returned a temporary object that is copied. You may not bind a temporary object with a non-constant lvalue reference.
Redeclare the copy constructor like
Vector2f(const Vector2f& og);... |
70,415,131 | 70,415,274 | How can I get a reference of the values in a map in C++? | I want the player of my game to not move if it will collide with other entities.
One solution I've thought would be keeping track of all entities in the game, and when trying to move, check if it will collide with any of those.
The problem is that when looping the vector, I don't get a reference of the entities, but ne... | You can return vector of type std::vector<std::reference_wrapper<Actor>> from EntityTracker::entities(), an example of such use is below:
// Original data
std::vector<std::string> vec;
vec.push_back("one");
vec.push_back("two");
// Now its copied as references to rvec
std::vector< std::reference_wrapper<std::string>> ... |
70,415,450 | 70,415,492 | C++ does not alter registry even though running without errors | Trying to write code to change the registry keys with c++ after endless amount of time I reached this point but this code still does not edit the registry even when running as admin
to change the registry 4 functions are needed according to this question which I used and every single one of them returns a zero which me... | I suspect you are compiling as a 32-bit program but looking at a 64-bit registry. Switch to compiling as 64-bit instead. (There is a 32-bit registry instead, which can be found buried within the 64-bit hives but you likely want to change the actual 64-bit version).
|
70,415,752 | 70,628,000 | How to use the QVector container with a custom class? | Here's a custom class I implemented for a personal project:
#include <QtCore/QCommandLineOption>
#include <QtCore/QSharedPointer>
#include <genepy/cli/CommandLineArgument.h>
#include <genepy/cli/CommandLineOption.h>
class QCommandLineParser;
namespace genepy {
class CommandLineParserBuilder;
class ConsoleApplicatio... | Finally, I changed QVector<CommandLineArgument> to QVector<QSharedPointer<CommandLineArgument>> since CommandLineArgument wasn't an assignable data type (it was missing a default constructor among others). Now, it works.
|
70,415,777 | 70,415,897 | how to improve my class to create output files | As I need this quite often, I would like to write a class handling main ofstream activities.
Something that I could use like this:
OutputFile out("output.txt");
for (int i = 0; i < 10; ++i)
out << i << "\n";
To this end, I wrote the following class:
class OutputFile {
std::string filename;
std::ofstream out;
... | You can overload operator<< in your class.
class OutputFile {
std::string filename;
std::ofstream out;
public:
explicit OutputFile(const std::string &filename)
: filename(filename), out("output/" + filename) {}
template<typename T>
OutputFile& operator<<(const T &value) {
out << value;
return *... |
70,416,040 | 70,416,046 | If statement on args giving odd outputs | When running this code: ./a.out 5 + 5 i am supposed to get 10. but instead i get Unkown operator. does anyone know why this may be happening?
#include <iostream>
#include <string>
int main(int argc, char *argv[]){
if (argv[2]=="+"){
std::cout << std::stoi(argv[1])+std::stoi(argv[3]) << "\n";
}
else ... | This line is comparing pointer values, and not the strings data they point to...
if (argv[2]=="+"){
Either use strcmp:
if (strcmp(argv[2], "+") == 0){
}
Or something along these lines:
if (std::string(argv[2]) == "+"){
}
|
70,416,078 | 70,416,191 | In C or C++, is memory layout of uint64_t guaranteed to be the same as uint32_t[2] ? Can one be cast as the other? | In C or C++, is memory layout of uint64_t guaranteed to be the same as uint32_t[2] ? Can I cast one to the other and have them always work as expected? Does it depend upon if the CPU is 32bit or 64bit or is it compiler implementation dependent?
|
In C or C++, is memory layout of uint64_t guaranteed to be the same as uint32_t[2] ?
No. Endianess.
Can one be cast as the other?
Maybe, maybe not, in C. A pointer to an array of 2 uint32_t may not be aligned to uint64_t. When the resulting pointer is not properly aligned, it's undefined behavior. https://port70.ne... |
70,416,086 | 73,300,814 | Correct way to exclude files from source tar ball using CPack | When configuring cpack I would like to not include a few files that are in the source directory when running make package_source, everything works fine when using CPACK_SOURCE_IGNORE_FILES I get the correctly generated source package with the file test.cpp not included in the resulting tar ball.
set(CPACK_SOURCE_IGNORE... | The documentation is pretty confusing for someone (including me) who doesn't already know what it's referring to. I believe it's referring to the command "strip", which is one of the GNU development tools, and is used to "discard symbols and other data from object files". I'm not sure why this would be useful for sourc... |
70,416,207 | 70,427,995 | What is the callgraph expansion stage in g++? | I am profiling my program;s compilation and looking for bottlenecks. I originally thought template instantiation would be the most expensive part but seems to be callgraph funciton expansion. Problem is, I have no idea what that stage refers to.
callgraph functions expansion : 28.98 ( 80%) 0.95 ( 39%) 29.98 ( ... | It appears to be part of the optimization process implemented by GCC. I was able to find one reference, The GCC call graph module, which describes it as the final step performed by the front-end of the compiler:
Expansion: We proceed in reverse DFS order on functions that are still present in the call-graph, applying... |
70,416,618 | 70,420,294 | Finding all possible occurrences of a matrix in a larger one | This question is a general algorithmic question, but I am writing it in C++ as it is the language in which I have faced this problem.
Let's say I have the following function:
using Matrix = std::array<std::array<uint8_t, 3>, 3>;
void findOccurrences(std::vector<Matrix>& output, const std::vector<std::vector<uint8_t>>& ... | You were already somehow on the right track.
Logically it is clear what has to be done.
We take the upper left edge of the sub pattern. Then we calculate the resulting upper left edges in the target matrix.
The column offset in the resulting matrix, where we will copy the pattern to, will start at 0 and will be increm... |
70,416,911 | 70,417,003 | How to generate preprocess and assmeble code by cmake? | I am trying to get intermediate .i .s file by CMake when compiling .cpp file, but cmake default only output .o file. Is there any command to manipulate cmake to keep these intermediate file, thanks a lot!
| If you are using gcc, try adding this line.
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -save-temps=obj")
|
70,417,120 | 70,418,912 | Template specialization of operator[] within a class with multiple template parameters | I'm having trouble specializing 2 methods of a tokenizer class that's declared with 2 template parameters. I've referenced Template specialization of a single method from a templated class but I am still encountering a few errors with my implementation. Some code (specialized functions near EOF):
#pragma once
#include ... | As your operator[] is not a template, you can't specialize it inside your class. What you want is to specialize the non template method for a template class.
But you can't do a partial specialization for the class to add definitions of members to it.
Working example:
template <class stringT = std::string, class delimit... |
70,417,145 | 70,417,196 | error: use of deleted function ‘Node::~Node()’ | Here is an oversimplified version of my code
#include <vector>
#include <string>
#include <unordered_map>
#include <iostream>
struct ElementData
{
std::string tagName;
std::unordered_map<std::string,std::string> attributes;
};
enum NodeTypeEnum
{
None=-1,... | You have a union with a member that has a non-trivial destructor. So the union can't know how to destruct itself. That's why NodeType::~NodeType is deleted by default. That's what the message tells you.
You need to define the destructor yourself and properly call the destructor on the correct member.
Or, better yet, do... |
70,417,195 | 70,417,335 | Range-For loop over a string adding a null or empty char at the end | Here is a loop that goes through each character in "(Level:". It adds something to the end which is messing up the rest of my code.
#include <iostream>
int main() {
std::cout << "Output:" << std::endl;
for (char letter : "(Level:") {
std::cout << "'" << letter << "'" << std::endl;
}
return 0;
}... | "(Level:" has type const char[8], and is equivalent to { '(', 'L', 'e', 'v', 'e', 'l', ':', '\0' }.
You can easily see this is the case by casting the letter to int before printing. Demo
This happens, because string literals (anything "...") are C-strings, which are zero terminated. If you want strings to have a size i... |
70,417,414 | 70,417,468 | Can't open existing semaphore from another process C++ | I'm trying to get existing semaphore from another process. To create semaphore i used:
Semaphore(std::string name, int startState) {
name = "Global\\" + name;
Sem = OpenSemaphore(SYNCHRONIZE | SEMAPHORE_MODIFY_STATE, true, (LPCWSTR)name.c_str());
int s = (startState > 0);
if (Sem == NULL) {
Sem ... | If you ever feel the need to use C-style casting (like in (LPCWSTR)name.c_str()) you should take that as a sign you're doing something wrong.
Like you do here: std::string is a narrow character (i.e. char) string, while you use the wide characer (wchar_t) functions. That means the names won't be what you expect.
If you... |
70,418,364 | 70,418,687 | Range transformations with stateful lambdas and std::views::drop | it's my first time digging into the new <ranges> library and I tried a little experiment combining std::views::transform with a stateful lambda and 'piping' the resulting range to std::views::drop:
#include <iostream>
#include <ranges>
#include <vector>
using namespace std;
int main() {
auto aggregator = [sum = 0... | transform_view is required to be a pure function. This is codified in the regular_invocable concept:
The invoke function call expression shall be equality-preserving and shall not modify the function object or the arguments.
This is important to allow transform_view to not lie about its iterator status. Forward itera... |
70,418,554 | 70,418,831 | I am not getting the error message in VScode without running it | Earlier I used to get error lines in the file name section and in the line also which contain error, but now I am not getting that. I have to run the program to know about the error in the code. Like in which line I am getting error.
As shown in the image also without running the program I am not getting the error mess... | Enable Your Squiggles to resolve this:
click ctrl+shift+p
Search c/c++: enable error squiggles
click on it.
It will enable your error messages.
|
70,418,599 | 70,419,756 | replacing string based on user input c++ | i want to receive an input from user and search a file for that input. when i found a line that includes that specific word, i want to print it and get another input to change a part of that line based on second user input with third user input. (I'm writing a hospital management app and this is a part of project that ... | You cannot replace the string directly in the file. You have to:
Write to a temporary file what you read & changed.
Rename the original one (or delete it if you are sure everything went fine).
Rename the temporary file to the original one.
Ideally, the rename part should be done in one step. For instance, you do not ... |
70,418,840 | 70,436,462 | Initializer list for struct deriving from class (C++) | Can you tell me what is wrong in the following example? I am using C++17, where I thought the following should be supported.
class Base {
public:
virtual ~Base() = default;
};
struct Derived : public Base {
int m1;
};
int main() {
/* Results in a compilation error
* error C2440: 'initializing': cann... | It does not work because Derived is not an aggregate since it has a base class with virtual members.
The code compiles and runs when removing the virtual destructor in Base and using C++17.
If Base requires a virtual destructor, Derived can implement a custom constructor allowing initialization using curly brackets.
cl... |
70,418,894 | 70,418,996 | Is there a way to merge / concatenate precompiler lists with C++ macros? | I have two lists:
#define LIST1 {1, 2, 3}
#define LIST2 {4, 5, 6}
and using C++ macros I would like to write something like this:
// Obviously doesn't work
#define MERGE LIST1 ## LIST2
int my_array[] = MERGE;
to yield:
int my_array[] = {1, 2, 3, 4, 5, 6};
during compile-time.
Is something like this possible? There a... | Don't use macros unless there is no other option, prefer templates.
They are typesafe.
For example you can make a compile time evaluated function (constexpr)
that merges two lists (arrays) and returns an array.
#include <array>
// type_t is the type held by the array (an int in this example)
// N = size of first array... |
70,418,924 | 70,458,361 | View creation works in Firebird 3.0 but not in version 4.0 | I created a music database application a few years ago in C++ (Code::Blocks + wxWidgets + SQLAPI++) and Firebird as the database server (running as a service in classic mode) on the Windows platform (v10). It creates a SQL database with tables, views, triggers, generators.
So far, it has been running perfectly up to Fi... | I have added 'DataTypeCompatibility = 3.0' to both databases.conf and firebird.conf.
The datatype for Album_NrSeconds is now NUMERIC.
My application runs flawlessly under Firebird 4.0 as a service after these 2 edits.
Thank you Mark Rotteveel for your suggestion. Its much appreciated.
|
70,420,518 | 70,420,980 | Confusion on return type deduction with unpacking references | The following code
#include <functional>
#include <tuple>
#include <iostream>
struct Point
{
int x;
int y;
};
decltype(auto) memrefs(Point &p)
{
return std::make_tuple(std::ref(p.x), std::ref(p.y));
}
int main()
{
Point p;
auto& [x, y] = memrefs(p);
x = 1;
y = 2;
std::cout << p.x << "... | decltype(auto) memrefs(Point &p);
is
std::tuple<int&, int&> memrefs(Point &p);
In structured_binding,
auto& in auto& [x, y] applies to the "tuple", not to x, y.
and you cannot have
std::tuple<int&, int&>& tup = memrefs(p);
but you can have
std::tuple<int&, int&> tup = memrefs(p);
then x, y refers to the appropriate... |
70,420,542 | 70,420,795 | Injecting class into the JNIEnv in android jni | C++ code:
extern "C" JNIEXPORT void JNICALL
Java_com_example_afl_MainActivity_stringFromJNI(
JNIEnv* env,
jobject /* this */) {
// env->DefineClass(...)
}
I'm calling the above function from Java side code:
public class MainActivity extends AppCompatActivity {
static {
System.load... | Impossible. Android does not implement DefineClass:
All JNI 1.6 features are supported, with the following exception:
DefineClass is not implemented. Android does not use Java bytecodes or class files, so passing in binary class data doesn't work.
Even if that worked, your app's user very probably does not have acces... |
70,420,709 | 70,420,765 | std::fuction calling convention | I've have observer implementation in my code. It looks like this:
template <typename... Args>
class Event {
std::map<size_t, std::function<void(Args...)>> m_observers;
mutable std::mutex m_mutex;
public:
virtual ~Event() = default;
[[nodiscard]] size_t Register(const size_t& object_id, std::function<vo... | This is unrelated to calling convention: all member functions have the same calling convention in C++ (sometimes called “thiscall”), and std::function<T>::operator() is a member function.
Instead, the issue is that your function prototype for a function taking a std::function<T> is incorrect. The signature goes in the ... |
70,420,794 | 70,420,925 | c++ vector [-2] index returns weird value | I'm new to c++ and just learned about vectors. I'm coming from Python, so of course I checked if I could use negative indexing in c++, which did not seem to work.
While trying to check if it works, I met a very weird behaviour for negative indexes in different environments.
Using negative indexes with the .at() functio... |
Are these values contents of previous memory locations, or what do they represent? Is this what's called undefined behaviour?
No, it's not actually accessing a memory location prior to the beginning of the backing array, but one past the end:
If you use numbers [index], the compiler interprets this as numbers.operato... |
70,421,258 | 70,503,119 | How to print actual(derived) object properties in LLDB | Code example:
class IA
{
public:
virtual int getA() = 0;
};
class A:public IA
{
public:
int getA() override
{
return m_a;
}
private:
int m_a = 10;
};
void main()
{
A* a = new A();
IA* ia = a;
}
In GDB with set print object on I can easily print a object contents using ia pointer.
... | lldb has two methods for accessing typed values from the target program, expr (aliased to p) and frame variable (aliased to v).
expr is a full expression evaluator that uses the clang front & backends to parse and evaluate the expression you pass it "as if it were inserted into the code at the point where you are stopp... |
70,421,335 | 70,425,757 | How do I convert std::chrono to int | I have been trying to make a wpm counter and, long story short, am running into an issue:
After using the high resolution clock, I need to divide it by 12, but I can't convert std::chrono to int. Here is my code:
#include <iostream>
#include <chrono>
#include <Windows.h>
#include <synchapi.h>
using namespace std;
usin... | std::chrono will elegantly do this problem with a few minor changes...
Instead of Sleep(1000);, prefer this_thread::sleep_for(1s);. You'll need the header <thread> for this instead of <Windows.h> and <synchapi.h>.
cin >> text; will only read one word. To read the entire line you want getline(cin, text);.
It is eas... |
70,421,369 | 70,421,422 | C++ specialized function template alias syntax | I have
class ClassA {};
class ClassB {};
auto func_a() -> ClassA {
return ClassA(); // example implementation for illustration. in reality can be different. does not match the form of func_b
}
auto func_b() -> ClassB {
return ClassB(); // example implementation for illustration. in reality can be different. d... | You might do something like (c++17):
template <typename T>
auto func()
{
if constexpr (std::is_same_v<T, ClassA>) {
return func_a();
} else {
return func_b();
}
}
Alternative for pre-C++17 is tag dispatching (which allows customization point):
// Utility class to allow to "pass" Type.
templ... |
70,421,465 | 70,421,504 | Switching from a 2D vector into a 1D vector | I have heard that a vector of vectors is bad in terms of performance. For example, I have the following 2D std::vector:
std::vector< std::vector<char> > characterMatrix;
// for iterating
for ( int row = 0; row < getY_AxisLen( ); ++row )
{
for ( int column = 0; column < getX_AxisLen( ); ++column )
{
std... | "have heard" together with performance is never the right approach.
To address performance, the golden rule is: Benchmark first!
Also, performance isn't always the most important thing. Typically, you should only optimize for performance if you find that your application isn't fast enough for your purposes. Then, follo... |
70,421,805 | 70,422,381 | How can I do to keep the value of a variable after a do while loop? | I have been coding a program to simulate a roulette of a casino, thing is that every time I try to repeat the game after is finished I want the game to keep going and the money to be the same, so if you have lost money you start with that certain money, here is the code (It's in Spanish but I think it's pretty clear):
... | So, it should be pretty easy to do that.
Initialize the starting amount outside the loop before the betting begins.
At the end of the loop, ask if user wants to bet more.
Would that work for you? Or do you need it to be initialized when you start the code itself? You could use static
I am just changing a few things fro... |
70,421,874 | 70,422,461 | How to convert a char* to a char array | I'm receiving some data over serial of variable names and values in char. The variable name gets stored in an array pointed to by the char*. I'm trying to compare the char array data I received, to several other char arrays so I can determine which variable I have received data for.
How can I convert the char* to a cha... | As @stark mentioned in comment, you just can pass name to the strcmp() function. A char array is internally just a char pointer char *
|
70,422,421 | 70,422,452 | Creating vector of class with parametrized constructor | I am trying to create a vector of a class with parametrized constructor.
#include <iostream>
#include <vector>
using namespace std;
struct foo
{
foo() {
cout << "default foo constructor " << endl;
}
foo(int i)
{
cout << "parameterized foo constructor" << endl;
}
~foo() {
cout << "~foo dest... |
What is happening here ?
You can add a user defined copy constructor to see what happens in your code:
#include <iostream>
#include <vector>
struct foo {
foo() { std::cout << "default foo constructor\n"; }
foo(int i) { std::cout << "parameterized foo constructor\n"; }
~foo() { std::cout << "~foo destructor... |
70,423,351 | 70,426,260 | Why override operators aren't working with pointer? | I need to write a class Matrix with override operators + - * = and I've got some code that is works, but there is error.
//Matrix.h
template <class T>
class Matrix
{
public:
Matrix(int rows, int columns);
Matrix(const Matrix<T> &m);
Matrix<T>& operator=(Matrix<T>& m);
Matrix<T> operator+(Matrix<T>& m) ... | Type information is crutal in C++.
This:
Matrix<int> matrix(2, 2);
matrix = matrix + matrix;
Here the type of matrix is Matrix. You have defined what the operator + for the type Matrix so this works fine.
This second one is different:
Matrix<int>* matrix = new Matrix<int>(2, 2);
matrix = matrix + matrix;
Here the t... |
70,423,353 | 70,427,545 | How iteration over parameter pack going through initializer_list? | Sorry for being vague with my question, but I just don't understand what does this function does and how. Code from here:
template<typename ... T>
auto sum (T ... t)
{
typename std::common_type<T...>::type result{}; //zero-initialization?
(void)std::initializer_list<int>{(result += t, 0)...}; //why 0 is here
... | Thanks to the comments, I figured out the answer.
I haven't ever come across comma operator, so the line (result += t, 0) made to me no sense until your comments about EXISTENCE of comma operator and this question. So basically we initializing our list with zeros. And since I made type of initializer_list for integers,... |
70,423,468 | 70,424,919 | How do you check how many times each digit from 0 - 9 appears in an input number | I just can't seem to come up with a way to go about this problem. I've been searching online for logic for this but no luck. One way would be to store the number in an array then comparing each value of the array but in this case your only limited to enter a limited amount of digits because of the size of the array and... | I understand that you would like to have an explanation and not just a code dump or some comments.
So, let me try to explain you.
As you know: Numbers like 12345 in a base 10 numbering system or decimal system are build of a digit and a power of 10. Mathematically you could write 12345 also a 5*10^0 + 4*10^1 + 3*10^2 +... |
70,423,627 | 70,424,478 | C++ return new instance of object from dictionary | How to achieve something like this in C++? I'd like some method to return instances of object based on provided string. I suspect map might be solution but I don't know how to pass method to it?
class Container {
dictionary = {
A: () => new A(),
B: () => new B(),
C: () => new C(),
};
method(choice: s... | I can propose the following solution:
a base class:
class Base {
}
a factory singleton:
class Factory
{
public:
static Factory &instance()
{
static Factory inst;
return inst;
}
bool Register(const std::string &name, CreateCallback funcCreate)
{
m_classes.insert(std::make_pai... |
70,423,691 | 70,423,854 | C++ access statically allocated objects' members | So I am trying to understand the state of the memory when I run the below code. From my understanding, the two sub-trees left and right that are initialized within the if-statement should be considered non-existent once the if-block ends. However, when I run this code, the output from within the if-block is the same as... | Suppose you own a plot of land and bury a body in it. Later you sell the land to someone else. Then you remember the body and freak out, so you go back and dig it up in the night. Luckily for you, it's still there.
Yes, you were trespassing, and there was no guarantee you'd find it, but since the new owner hadn't do... |
70,424,014 | 70,424,239 | Building boost for different versions of Visual Studio | I have Visual Studio 2019 and 2022 installed. I want to build boost libraries for 2019 vc142. How do I build vc142 libs instead of vc143?
My current method for building is as follows. I'm using Developer Command Prompt for 2019, and running the following,
bootstrapper.bat
b2.exe install --prefix=MY_PATH
Unfortunatel... | adding toolset=msvc-14.2 to the b2.exe builds the correct version.
b2.exe install --prefix=MY_PATH toolset=msvc-14.2
|
70,424,038 | 70,424,154 | Compiler warning for statement on same line as #endif | Consider code:
#include <stdio.h>
int main() {
int a = 4;
#if 1
printf("Hello world\n");
#endif a++;
printf("a is %d\n", a);
}
Inadvertently, statement a++; is on the same line as a #endif and is not evaluated. As a result, the final output is:
Hello world
a is 4
On x86-64 clang 12, this is captured as a... | There's compiler warning C4067. It looks like you need to set the flag /Za for it to apply to #endif directives.
In the Visual Studio properties page, this flag is controlled by the setting "Disable Language Extensions" in the Language subsection of the C/C++ section.
|
70,424,070 | 70,424,264 | What is wrong with below C++ regex code to extract names and value? | #include <iostream>
#include <regex>
using namespace std;
int main()
{
string s = "foo:12,bar:456,b:az:0,";
regex c("(.*[^,]):([0-9]+),");
smatch sm;
if(regex_search(s, sm, c)) {
cout << "match size:"<<sm.size()<<endl;
for(int i=0; i < sm.size();i++){
cout << "grp1 - " << s... | You confuse multiple match extraction with capturing group values retrieval from a single match (yilded by the regex_search function). You need to use a regex iterator to get all matches.
Here, match size:3 means you have the whole match value (Group 0), a capturing group 1 value (Group 1, the (.*[^,]) value) and Group... |
70,424,212 | 70,484,957 | C++ MFC reading Cstring from editbox for file reading (std::filesystem Exception unhandled memory problem) | What my code is suppose to achieve is to read in the file names after given a file path input and output (switch 1: the files under the same folder)(switch 2: all the file names under the directory including sub-directories), and to not store the folder names into vector (1.png 2.png 3.png but not ChildFolder).
If you ... | After some research,I changed my code and finally got it working
//Answer
string a;
CString stri;//Read text from edit control box and convert it to std::string
GetDlgItem(IDC_EDIT1)->GetWindowText(stri);
a = CT2A(stri);
//This code is something I also tried but the string a it passed back is ""
/*CString b;
b = enter... |
70,424,243 | 70,424,438 | How to use the return value from one function in another in C++ | Is it possible to use the return value from one function in another?
The code is something like this:
double process () {
//doing something
return result;
}
double calculation () {
double sum = 0;
sum = result + 10; //Want to use the result from the previous function here
... | You have two options - you could store the return value in a variable and then use that variable, or you can use the function call directly.
Store in a variable like this -
double sum = 0, result = process();
sum = result + 10;
or use the call directly like this -
double sum = 0;
sum = process() + 10;
|
70,424,244 | 70,424,509 | there is a problem in this code its deleting everything in cur->calendar linked list not just the one in the condition | I tried everything and i have no idea what to do now so any help is appreciated!
void DeleteAtPosition(Appointment* head, int pos) {
Appointment* cur = head->next;
Appointment* prev = head;
int i = 1;
if (isEmptylist(head)) {
cout << "LIST IS EMPTY" << endl;
}
if (pos == 0) {
del... | The problem is that you are doing cur->Calendar = cur->Calendar->next;. You are moving the original pointer over the list, so at the end of the inner while loop, cur->Calendar going to be null.
You should instead use the curr variable to go over the list like this:
void cancel(Company* c, string title) {
Employee* ... |
70,424,260 | 70,424,535 | I am very much new at coding in c++ i can not setup vs code giving error | I am very much new at coding in c++. I am following code with harry youtube channel for coding.
in the first video vs code installation setup
I followed every step he did in the same but in my vs code,it is displaying an error. see in image
image
| I think your code is not saved.
Do Ctrl+S and then try running it again.
|
70,424,379 | 70,425,013 | What does the PACKED keyword mean in Android aosp? | When I read some C++ code in the Android aosp, I see some classes are declared with a PACKED keyword. For example, in <android_source_root>/art/runtime/image.h, a class ImageSection is declared this way:
class PACKED(4) ImageSection {
public:
ImageSection() : offset_(0), size_(0) { }
ImageSection(uint32_t offset, ... | It is defined in <android_source_root>/art/libartbase/base/macros.h
#define PACKED(x) __attribute__ ((__aligned__(x), __packed__))
|
70,424,712 | 70,448,182 | Call C++ Hello World from Julia | I have a C++ program that parses a binary file and outputs a std::string. I would like to call this function directly from Julia and convert the steam into a DataFrame. I need it to work in Linux and Windows. Currently, I have the program write the output to a text file, and then I read it into Julia. Cxx is no lon... | There's a new package which might fit your needs here:
https://github.com/eschnett/CxxInterface.jl
It is intended as a successor to Cxx.jl and more stable, so I'd recommend giving it ago although I haven't tried it myself!
|
70,425,047 | 70,425,241 | How to remove an item of Vectors c++ | i have this code and i want to find a word in my vector and delete the item that includes that word but, my code will delete from the first line until the item that i want, how can i fix that?
std::string s;
std::vector<std::string> lines;
while (std::getline(theFile, s))
{
lines.push_back(s);
}
//finding item in v... | The erasing loop is broken. The proper way is to use iterators and use the iterator returned by erase. Like so:
// finding item in vector and changing it
for (auto it = lines.begin(); it != lines.end();) {
if (it->find(name) != std::string::npos) {
it = lines.erase(it);
} else {
++it;
}
}
O... |
70,425,137 | 70,425,867 | Exporting template function requiring std concepts | IDE : MSVS 2022, /std:c++latest, /experimental:module, x86 ;
Goal : to export T add(T,T) that requires std::integral<T> ;
This compiles (test.ixx) :
export module test;
template < typename T >
concept addable = requires ( T t1, T t2 ) {
t1 + t2 ;
};
export template < typename T >
requires addable<T>
T add ( T t1,... | The thing is, you shouldn't use #include after the module declaration export module xxx.
The introduction of modules does not change what #include means (well, in most cases), #include still means "copy-paste this file here". Your #include-ing of <concepts> pasted all its content and its transitive includes into your m... |
70,425,876 | 70,426,111 | How to convert extremely small exp values to 0? | I'm doing Gram-Schmidt Orthogonalization process. At some point I'm getting output 3D vectors with values extremely small. Basically the values are zeros. How to deal with values such as -3.5527136788005009 * 10^-15?
How to convert them to zero or compare if it is almost zero?
| I did research on my old code and I've found this little func:
static const double eps = 1e-10;
bool isZero(double value) const
{
return std::abs(value) <= eps;
}
|
70,425,955 | 70,426,134 | Is the compiler required to emit stores to raw addresses? | Two popular compilers (gcc, clang) emit a store instruction in the body of the following function:
void foo(char x) {
*(char *)0xE0000000 = x;
}
This program might behave correctly on some hardware architectures, where the address being written to is memory-mapped IO.
Since this access is performed through a pointer... | The C standard does not require an implementation to issue a store because C 2018 5.1.2.3 6 says:
The least requirements on a conforming implementation are:
— Accesses to volatile objects are evaluated strictly according to the rules of the abstract machine.
— At program termination, all data written into files shall ... |
70,426,203 | 70,435,624 | Iterate Through All Nodes In yaml-cpp Including Recursive Anchor/Alias | Given a YAML::Node how can we visit all Scalar Nodes within that node (to modify them)? My best guess is a recursive function:
void parseNode(YAML::Node node) {
if (node.IsMap()) {
for (YAML::iterator it = node.begin(); it != node.end(); ++it) {
parseNode(it->second);
}
}
else if... | The most obvious way to identify nodes would be to use their m_pNode pointer; however that is not publicly queryable. The next best way is to use bool Node::is(const Node& rhs) const, which sadly doesn't allow us to do any sorting to speed up performance when searching for cycles.
As you probably do not only want to av... |
70,426,294 | 71,421,615 | boost::python::init<>() undefined reference | I'm trying to expose a simple class and constructor using boost python. I have the following:
files:
boost_test
├── boost_test.cpp
└── CMakeLists.txt
CMakeLists.txt:
cmake_minimum_required(VERSION 3.22.1)
project(boost_test)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED YES)
find_package(Python... | It turned out boost was installed incorrectly. I'm not sure what I did wrong, but rebuilding the boost library fixed the issue.
|
70,426,472 | 70,426,580 | c++ How do I initialize a member array in a constructor? | I am trying to initialize a member array in the default constructor of a class which I've created. However, nothing I've tried has worked. I'm quite new to c++ and programming in general, and I haven't found the answer I was looking for online yet. In my .hpp file I have:
class thing
{
private:
std::string array[8]... | Either use a constructor initializer list, or use a default member initializer.
#include <string>
class thing {
std::string array[8][8];
public:
thing();
};
thing::thing()
: array{
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", "d", "e", "f", "g", "h"},
{"a", "b", "c", ... |
70,426,700 | 70,426,725 | Vector constructor identified as function | Consider this piece of code:
#include <iostream>
#include <sstream>
#include <iterator>
#include <vector>
#include <string>
int main() {
std::istringstream ss("abcabc abc a b e");
std::vector<std::string> words(std::istream_iterator<std::string>(ss), std::istream_iterator<std::string>());
std::string d... | This is what is known as most vexing parse, in this case you should use the braced initialization syntax which will let the compiler know you are trying to construct an instance of a class instead of declaring a function.
i.e std::vector<int> a{} instead of std::vector<int> a()
|
70,426,702 | 70,427,201 | Constrain template template parameter to be one of two types | I have the following classes:
template <typename T, int N0, int N1, int N2>
struct A{};
template <typename T, int N0, int N1, int N2>
struct B{};
I want templated functions to only be able to take one of these two types:
template <typename AorB>
void foo(AorB& arg)
{
}
Where all A<T,N0,N1,N2> and B<T,N0,N1,N2> are ... | You could define a helper variable like this:
template<typename T>
constexpr static bool is_ab = false;
template <typename T, int N0, int N1, int N2>
constexpr static bool is_ab<A<T, N0, N1, N2>> = true;
template <typename T, int N0, int N1, int N2>
constexpr static bool is_ab<B<T, N0, N1, N2>> = true;
And then the ... |
70,426,877 | 70,427,050 | How does std::array constructor initialize its array? | Im trying to understand how std::array constructor work and how can he take a array and initialize it to its array.
I was searching on the standard library file and i find this piece of code
#if _HAS_CXX17
template <class _First, class... _Rest>
struct _Enforce_same {
static_assert(conjunction_v<is_same<_First, _Re... | As already mentioned in comments above, std::array is an aggregate type, so you are not calling a constructor but actually initializing a data member.
The code you point at in the question allows creation of std::array without stating array's type and size. This is done, with deduction guides, as seen in the code below... |
70,427,057 | 70,427,447 | sfinae vs concepts with non type template parms | For academic reasons I want to implement an example which select a template if a non type template parameter fulfills a given criteria. As example I want to have a function which is only defined for odd integer numbers.
It can be done like:
template < int N, bool C = N%2>
struct is_odd: public std::false_type{};
templa... | After some more experimental work I found that concepts can be used for non type template parms. I simply did not find anything about that in the docs I read.
template < int I >
concept ODD = !(I%2);
template< int N >
requires( ODD<N> )
void Check() { std::cout << "odd number template spezialisation " << std::endl; ... |
70,427,098 | 70,428,870 | QSerialPortInfo::serialNumber() always returns an empty string | QSerialPortInfo::serialNumber() always returns an empty string, which happens when it's unavailable.
I tried connecting different ports, everything seems allright, but it doesn't show a Serial Number of a port no matter what I do!
Port name, manufacturer, product ID, however, can be correctly outputted.
I didn't connec... | If you take a look at the relevant source code parseDeviceSerialNumber() you will see quite some fancy logic where Qt tries to isolate a serial number from some device-identification string. That's the string you are likely also seeing in the Windows device manager way down in the details.
Why can serial number be una... |
70,427,135 | 70,428,469 | Implement a struct in WASM text format | Does WASM text format have structs?
(module
(type (; can a type be a `struct` like in C or rust? ;) )
(; rest of module ;)
)
I've compiled the following c++ to wasm using this WasmExplorer tool
struct MyStruct {
int MyField;
long MyOtherField;
};
MyStruct returnMyStruct(int myField){
return MyStruct {
... |
Does WASM text format have structs?
It does not. Like with other low-level assembly languages, wasm only has a few integer data types, and views memory as a big block of bytes. This is a simplification, but when a high level language like C is compiled to assembly, struct variables are allocated a spot in memory, wit... |
70,427,448 | 70,427,645 | Remove dot prefix "./" from std::filesystem::path | Is there a simple way to strip away the starting ./ of a path. For example: I have a path ./x/y and i want to convert it to x/y (without the first dot and slash). Is there a standard way of doing it?
#include <iostream>
#include <filesystem>
namespace filesystem = std::filesystem;
int main() {
auto path = filesys... | Apparently the problem could be solved with std::filesystem::relative():
#include <iostream>
#include <filesystem>
namespace filesystem = std::filesystem;
int main() {
auto path = filesystem::path{"./x"};
std::cout << path << std::endl;
std::cout << filesystem::relative(path, "./") << std::endl; //
}
Pr... |
70,427,890 | 70,428,027 | std::vector to Eigen::VectorXf | I have a vector
int N = 100;
std::vector<float> v(N, 1.0f);
which I'd like to convert to an Eigen vector type ( Eigen::VectorXf?) I have tried
Eigen::VectorXf ev(N);
ev = Eigen::Map<Eigen::VectorXf>(&v[0], N);
but I am not sure if it right or wrong. I can only see ev has 1 value in my visual studio.
| Your code seems correct. No need to initialize ev(N), though. You can just write
Eigen::VectorXf ev = Eigen::VectorXf::Map(&v[0], N);
|
70,428,046 | 70,429,098 | trying to break a line into multiple tokens | My problem is this, i have this string RGM 3 13 GName 0005 32 funny 0000 44 teste 0000\n and i want to split it like this
13 GName
32 funny
44 teste
so i can save the numbers and names in an array, but the problem is for some reason declaring an "" like i did is invalid in c++ and it is breaking the line at all.
Prog... | If your lines are always going to have the format A B n1 str1 code1 ... nn strn coden, where you seem to discard A B, the simple C++ code below will suffice:
[Demo]
#include <iostream> // cout
#include <sstream> // istringstream
#include <string>
int main()
{
const std::string line{"RGM 3 13 GName 0005 32 funny ... |
70,428,563 | 70,428,826 | Union's default constructor is implicitly deleted | The following code:
struct non_trivially {
non_trivially() {};
};
union U {
bool dummy{false};
non_trivially value;
};
int main() {
U tmp;
}
https://godbolt.org/z/1cMsqq9ee
Produces next compiler error on clang (13.0.0):
source>:11:7: error: call to implicitly-deleted default constructor of 'U'
U... | This is CWG2084. Clang and gcc are just wrong in deleting the default constructor if you provide a default member initializer.
The relevant quote that was added to the standard after the change was adopted (in [class.default.ctor]):
A defaulted default constructor for class X is defined as deleted if:
X is a union th... |
70,428,773 | 70,432,964 | references are a pain for my mocks in TDD | I am new with c++/tdd, embraced gtest/gmock, and fell in love.
One thing kind of puzzles me though. Are reference pointers really the way to go?
I find myself producing a lot of boiler plate injecting all mocks (even when I don't have any business mocking that behavior).
Example:
namespace
{
class set_configuration... | Found a better alternative. Providing interfaces (pure virtual classes) heavily reduces the need to provide an entire tree of mocks.
e.g
class flash_api : public iflash_api
{
public:
flash_api(iflash_peripheral &flash_peripheral) : _flash_peripheral(flash_peripheral)
{
}
virtual ~flash_api()
{
... |
70,429,220 | 70,430,463 | C++ Write Macro for finding an integer type given another integer type | I have a function which looks like this:
template<class T, class E, class U = T> T function(T input1, E input2) {
// implementation here
}
Instead of the above declaration, I want the default for U to be a macro which takes T for input. More specifically, I want the default for U to be boost::multiprecision::cpp_i... | Defined a custom boost multiprecision int using a macro, and hid the function backends behind another function which checks types. U is void so that the user has the option of customizing it. If T is fixed precision, the function calls the macro, otherwise passes cpp_int as a template argument. The type deduction of th... |
70,429,512 | 70,429,883 | c++ - how to list all keys inside a boost::bimap | What would be a simple way to iterate through and store all keys of boost::bimap into a vector.
Would it work just like we would for std::map
| This would be one way:
#include <boost/bimap.hpp>
#include <vector>
template<class L, class R>
std::vector<L> to_vector(const boost::bimap<L, R>& bm) {
std::vector<L> rv;
rv.reserve(bm.size()); // or bm.size() * 2 if you want to store the right keys too
for(auto&[l, r] : bm) { // loop through all the e... |
70,429,541 | 70,429,749 | Overloading static and non-static member function with constraint | Is this code valid?
template<bool b>
struct s {
void f() const {
}
static void f() requires b {
}
};
void g() {
s<true>().f();
}
clang says yes, but gcc says no
<source>: In function 'void g()':
<source>:10:20: error: call of overloaded 'f()' is ambiguous
10 | s<true>().f();
| ... | If we go through [over.match.best.general], we get:
a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2), and then [...]
The only argument is the object argument, and we have earlier that:
If F is a s... |
70,429,668 | 70,429,868 | Segmentation Fault from a While Loop C++ | I'm trying to do a search from inside a map that would push all related children and later generations into a stack. mined is a json object declared before.
if ( !mined[source].empty() ) {
std::vector<std::string> minedDataVec = mined[source];
while ( !minedDataVec.empty() ) {
for (std::... | First, the vector named minedDataVec declared in the if block seems meaningless...
As for the Segmentation Fault, maybe it's because minedDataVec.clear() "Invalidates any references, pointers, or iterators referring to contained elements." (source).
The range-for loop for (std::string s: minedDataVec) has an implicit i... |
70,429,673 | 70,429,682 | std::thread in constructor referencing it's deleted copy constructor? | I'm having a surprising amount of trouble with a constructor I'm writing. It's something incrediably basic, but I'm having a bad day because I'm totally stumped.
class RenderThread {
public:
RenderThread(std::thread && threadToGive)
: m_renderThread(threadToGive) {}
private:
std::thread m_renderThrea... | You have to std::move() the RenderThread constructor's parameter into the constructor of the m_renderThread member:
: m_renderThread(std::move(threadToGive)) {}
|
70,429,993 | 70,430,055 | How to get data in resource file? | I get the NULL(hRsrc) when it is running.
.cpp
HINSTANCE hInstance = AfxGetInstanceHandle();
HRSRC hRsrc = FindResource(hInstance, MAKEINTRESOURCE(IDR_EXE1), _T("EXE"));
if (hRsrc == NULL) {
MessageBox(NULL, TEXT("LoadEmbedded"), TEXT("1"), MB_OK);
}
HANDLE hRes = LoadResource(hInstance, hRsrc);
if (hRes == NULL... | Does the .rc file have an #include "resource.h" statement?
If not, then the IDR_EXE1 macro won't be defined when the .rc is compiled, and thus the resource's ID will be the literal string "IDR_EXE1" and not the numeric 105 (use a resource viewer tool to verify that). In which case, you would have to use _T("IDR_EXE1") ... |
70,430,566 | 70,444,118 | c++ filesystem, get files in directory alphabetically, rename inputs | I have the following code:
/*
This function conditions folders into a standard format with the following specifications
The first file in the folder to render has an index starting at 0
with the name of outPutName[Index].fileExtension dataType is preserved
*/
void vCanvas::conditionFolder(vizModule target){
vector<... | I wrote and ran unit tests on this function, which does what I want, which, in specific, is to first sort alphabetically, but then, if the program is comparing 2 digits, to take the smaller size string. This works for my purposes, which is simply to handle consistent but arbitrarily named series of .pngs and turn them... |
70,430,857 | 70,430,991 | Strange behavior found in Sublime and Vim at EOF | Ι have a file called position.txt which has been formatted in a particular fashion. This is the content of position.txt:
START POLYMER 1
1 0 0
2 0 0
3 0 0
4 0 0
4 1 0
5 1 0
5 0 0
6 0 0
END POLYMER 1
However, when I look at position.txt using vi, I see this:
When I look at positions.txt in sublime, I see:
Clearly,... | There is only one newline (\n) after the last line with text so the fact that you read one empty line is due to a bug in your program.
This:
while (myfile.good()) {
std::getline(myfile, myString);
should be this:
while (std::getline(myfile, myString)) {
See Why is iostream::eof() inside a loop conditi... |
70,431,146 | 70,431,271 | Sorting by struct data inside unordered_map | I have an std::unordered_map<id, town_data> data, where town_data is a struct of different information - name (string), taxes collected (int) and distance from capital town (int). I'm supposed to build a std::vector<id>, which is sorted by beforementioned distance, lowest to high. I'm quite struggling to figure out how... | You could create a std::vector of iterators into the map and then sort the iterators according to your sorting criteria. After sorting, you could transform the result into a std::vector<id>.
Create a std::vector of iterators:
std::vector<decltype(data)::iterator> its;
its.reserve(data.size());
for(auto it =... |
70,431,452 | 70,431,525 | Why "ios::sync_with_studio(0) and cin.tie(0);" doesn't work with strings in C++ | I was solving one problem using C++ where I have to take a string as an input. So instead of using the standard input/output method, I tried to use fast input/output method.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
ios::sync_with_studio(0);
cin.tie(0);
string str;
... | That's the way it is. You need to make sure that you're writing the names correctly. You can always take a look at https://en.cppreference.com/w/.
But in this case, check this: std::ios_base::sync_with_stdio
Also keep in mind that if set to false, the C++ standard stream objects such as cout, clog, cerr, wcout, etc. wi... |
70,432,293 | 70,432,381 | Dealing with unsigned integers | I know that unsigned integers are infamous and generally avoided by C++ devs. I have a class with two int member variables that should not contain negative values:
.
.
.
private:
int m_Y_AxisLen;
int m_X_AxisLen;
.
.
.
I have designed the logic of the member functions in a way that prevents any input of negati... | A lot of those "you shouldn't use unsigned integers" are just basically scared that you will mix up signed integers and unsigned ones, causing a wrap-around, or to avoid complex integer promotion rules.
But in your code, I see no reason not to use uint32_t and std::size_t, because m_X_AxisLen and m_Y_AxisLen should not... |
70,432,554 | 70,433,055 | gtkmm hello world error: glibmm/ustring.h: No such file or directory | I am new to GTK and gtkmm. I have been trying to compile an example hello world code for gtkmm which resulted in a gtkmm/button.h: No such file or directory I fixed this by providing the header path, but now I am getting this new error which I am unable to fix.
In file included from /home/kshitij/Tutorials/HMI/libhello... | Your CMake file does not actually use glibmm, it just searches for it.
Here is a modernized version of your libhelloworld/CMakeLists.txt:
# Set the name and the supported language of the project
project(hello-world C CXX)
# Set the minimum version of cmake required to build this project
cmake_minimum_required(VERSION 3... |
70,432,629 | 70,437,243 | How to use C++ module :private fragment with templates? | I'm experimenting with C++20 to better understand how they work in practice. I learned about the module :private fragment that can be used to separate the interface from the implementation, while keeping both in the same file. That seems to work for standard functions, but not for template functions.
I have the followi... | Modules do not change the nature of C++, merely how you access different components.
It is part of the nature of C++ that, in order for a translation unit to use a template, that translation unit must have access to the definition of that template. Modules doesn't change that.
The private module fragment specifically c... |
70,432,649 | 70,433,994 | Why do I see strange UDP fragmentation on my C++ server? | I have build an UDP server with C++ and I have a couple questions about this.
Goal:
I have incomming TCP trafic and I need to sent this further as UDP trafic. My own UDP server then processes this UDP data.
The size of the TCP packets can vary.
Details:
In my example I have a TCP packet that consists of a total of 2000... | OK, circumstances are more complicated as they appear from question, extracted from your comments there's the following information available:
Some client sends data to a server – both not modifiable – via TCP.
In between both resides a firewall, though, only allowing uni-directional communication to server via UDP.
Y... |
70,432,999 | 70,434,636 | What is mbstate_t and why to reset it? | Could you please explain to me what exactly is mbstate_t? I have read the cppreference description, but I still don't understand its purpose. What I do understand is that mbstate_t is some static struct visible for a limited set of functions like mbtowc(), wctomb() etc., but I am still confused about how to use it. I c... | The interface to mbtowc is kind of crazy. A historical mistake, I guess.
You are not required to pass it a complete string, but can pass a buffer (perhaps a network package) that ends in an incomplete multi-byte character. And then pass the rest of the character in the next call.
So mbtowc will have to store its curren... |
70,433,152 | 70,434,490 | Missed optimization with string_view::find_first_of | Update: relevant GCC bug report: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=103798
I tested the following code:
#include <string_view>
size_t findFirstE_slow(std::string_view sv) {
return sv.find_first_of("eE");
}
size_t findFirstE_fast(std::string_view sv) {
auto it{sv.begin()};
for (; it != sv.end() && *it ... | libstdc++'s std::string_view::find_first_of looks something like:
size_type find_first_of(std::string_view v, std::size_t pos = 0) {
if (v.empty()) return npos;
for (; pos < size(); ++pos) {
const char_type* p = traits_type::find(v.data(), v.size(), this->data()[pos]);
if (p) return pos;
}
... |
70,433,778 | 70,434,114 | C++ dynamically linked library and void pointer | I'm in the following situation: I'm writing a C++ program which has to dynamically load a C++ library (i.e. via dlopen and friends in Linux and LoadLibrary and friends in Windows). This can be done creating a C interface.
Now, both in the program and in the library I manage some object which has some specified template... | Hoisting my comment into an answer: you definitely don’t need to change the signature of your function to make it work with dynamic linking, if you’re happy to require C++. That is, the following works:
extern "C" void some_function(MyObject& o) {
o.do_something();
}
And then you could have a main.cpp as follows (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.