question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
66,205,773 | 66,205,875 | Const_iterator member variable not pointing to the begin of a vector member variable after initialization | I am trying to implement a Bayesian estimator for the card game Avalon. The game has five rounds and each round contains at most five proposals made by five different players. If a proposal is accepted, players go on a quest and the game proceeds to the next round. Before the previous round is completed, it is not know... | Your Round cannot be copied without problems:
class Round
{
private:
std::vector<const Player*> proposers;
std::vector<const Player*>::const_iterator proposer;
public:
Round(std::vector<const Player*> proposers) : proposers(proposers), proposer(Round::proposers.begin()) {};
void next_proposal() { (*Rou... |
66,205,961 | 66,685,050 | How to build c++ code into a .dmg file rather than a .exe file on visual studio 2019 from a windows computer? | How would I build my c++ code into a dmg file other than a exe file which is what it always builds into. I am trying to make my programs useable by mac users but I cant find answers for this
| First off, .dmg on Mac isn't an executable. It's really a packaging tool that includes your executable. If you have a GUI, then what you really need to produce is a .app. If it's just a command line tool, then a binary, just like on Unix. Remember, OSX is very UNIX-like.
I did a Google for "cross compile on windows for... |
66,205,969 | 66,206,123 | C++ for loop to find "sum of digits of a given number" | I'm a very beginner. I'm trying to solve some problems and being stuck right at the first one. The while loop runs but then I try using for loop and it never runs
#include <iostream>
using namespace std;
int main(){
int n=910;
int digits_sum=0;
for(int i=n;i=0;i/=10)
digits_sum+=(i%10);
cout<<digits_sum;
return 0;}
I ... | To quoute from your question:
condition to be out of loop: i=0
You have two misunderstandings here:
i = 0 is an assignment, you want a comparison i == 0
It looks you interpreted this as "exit if this is condition is fullfilled", but in fact the opposite happens: The loop will continue as long as this condition is tr... |
66,205,992 | 66,206,455 | Boost unable to verify IPv6 with square brackets | I'm using Boost's boost::asio::ip::address::from_string to validate IPs and it turns out it can't validate IPv6 if it's enclosed in square brackets. Not sure if this is intentional, but I wonder if there is a way to make it works? Perhaps some other method within boost?
boost::system::error_code invalid;
boost::asio::i... | I came up with a solution.
Basically, We check if the string has [ or ] then erase it else keep it as it's.
int main()
{
std::string str("[2607:f8b0:4008:80d::2004]");
if(str.front() == '[' && str.back() == ']') {
str.pop_back();
str.erase(str.begin());
}
boost::system::error_code invalid;... |
66,206,350 | 66,208,320 | how to convert C++ while statmernt code with decrement into c# code | what I'm trying is to convert C++ piece of code
while (n--) if (c & 0x80000000) c = (c << 1) ^ p2; else c <<= 1;
into c#
the whole code in c++ is:
#include "stdafx.h"
int main()
{
unsigned long c, c2, p2, pol = 0xEDB88320;
long n, k;
{
printf("CRC32 Adjuster (c) 2001 by RElf @ HHT/2\n");
... | In C++, non-nul integers convert to true.
So you have to be explicit here:
if (c & 0x80000000)
becomes
if ((c & 0x80000000) != 0)
Demo
|
66,206,476 | 66,206,637 | How to remove the a vector element from unordered_map | How can i remove a vector element from a unordered_map
std::unordered_map<std::string stdstrID, std::vector<std::string>> controlTags;
i will have multiple vales for a give keyname and would want to remove given value for the keyname from the vector list.
void Sum_TagControl::Remove_Tag(std::string stdstrControlID , s... | Based on the example, it seems that you don't want to remove an element from the map, but instead you want to remove elements from a vector that happens to be within a map. That is done the same way as removing an element from any vector regardless of where it is. The typical way is remove-erase idiom.
I assume that yo... |
66,206,593 | 66,254,998 | Suggestions for static library to avoid name collision | We have two libraries - lib1 and lib2. Both the libs use a third lib say lib3. If our customer uses lib1 and lib2 in the same application using static linking, the customer faces linking issues due to symbol collision as functions from lib3 are common in lib1 and lib2.
We have access to lib1, lib2, lib3 source codes. W... | We finally fixed our problem using dynamic namespacing
First, define a macro for the namespace
#ifndef LIB_NAMESPACE
#define LIB_NAMESPACE SomeNameSpace
#endif
then add namespace around every class.
On compilation override the macro from the compiler command line e.g.
g++ -DMY_LIB_NAMESPACE=Lib1Namespace ...
g++ -DMY_... |
66,206,737 | 66,207,170 | Exception thrown: read access violation **this** | I am trying to sort through two separate arrays containing objects passed to functions in order to find the highest salary. I thought I had it figured out, but then I get the error given below:
"Exception thrown: read access violation. this was 0x12963854."
I feel like this could be a simple fix and I am just overlooki... | There are 3 main bugs in your code, in order of appearance:
highest and otherHighest are not initialized
As pointed out by Kim Nyholm the salaries are used as indexes
Then highest and otherHighest are used as salaries instead of indexes
// Initialized as index of the first element
int highest = 0;
int otherHighest = ... |
66,206,751 | 66,207,117 | I got the correct solution in my local machine but Topcoder didn't accept this, can anyone help me | Problem Statement
|-O-| |-O-| |-O-| |-O-| |-O-|
Above you see a tiny fraction of our glorious imperial fleet, the Twin Ion Engine starfighters (known as "TIE fighters" for short).
Each TIE fighter consists of two solar array wings ('|'), two wing braces ('-') and one central cabin ('O').
Even though o... | Your method is correct, your code however can be modified to work without errors:
#include <string>
class TIEFighterAssembly
{
public:
static int assemble(std::string salvagedParts)
{
int a=0,b=0,c=0;
for(size_t i=0;i<salvagedParts.length();i++)
{
char character = salvag... |
66,206,865 | 66,206,996 | Socket Programming, Casting sockaddr_in to sockaddr. Why? | Here is a sample socket programming snippet from the client side. My question revolves around the type-casting that casted sockaddr_in into sockaddr. My question is that why is that casting necessary there, what is going on there exactly?
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stri... |
What is the purpose of this casting here which casted sockaddr_in to sockaddr.
sockaddr_in is not casted to sockaddr. sockaddr_in* is casted to sockaddr*.
That cast is done because the function connect which is being called doesn't accept a sockaddr_in* parameter, but a sockaddr*.
P.S. I recommend to not manually cr... |
66,207,909 | 66,208,164 | Assigning consecutive integers to a list of variables | How to rewrite the following in a more compact form?
constexpr unsigned int dog=1;
constexpr unsigned int cat=2;
constexpr unsigned int elephant=3;
...
constexpr unsigned int zebra=1000;
Ideally, I'd like something like
dog,cat, elephant, ..., zebra = range(1,1000)
|
Assigning consecutive integers to a list of variables
They're not really variables if they can't vary.
You can just replace
constexpr unsigned int dog=1;
constexpr unsigned int cat=2;
constexpr unsigned int elephant=3;
...
constexpr unsigned int zebra=1000;
with
enum Animal: unsigned {
dog=1,
cat,
elephant,
... |
66,208,248 | 66,208,568 | How do I implement adding and removing elements of an array? | How to implement output of all elements of an array?
A task:
N guys are arranged in a circle. Starting the countdown from the 1st, each k is removed, closing the circle after each removal. Who is left? Display the order of removal from the circle.
#include <iostream>
#include <conio.h>
int counter(int n, int k) {
i... |
How do I implement adding and removing elements of an array?
There is no way to add or remove elements from an array. An array has a constant number of elements that doesn't change through the life of the array.
If you need to represent a dynamic sequence of objects that can grow or shrink, you need a more complex da... |
66,208,767 | 66,284,103 | Xcode Swift MacOS App, C++ threads and progress bar | first of all I'm new in Stackoverflow and I'd like to thanks all of you for all the great info!
I have some experience on C/C++ under Linux and Win and recently I'm trying to develop/port an app for MacOS since I've just bought the new MacBook Air M1.
I've create a new MacOS App in Xcode and I'm using some C++ Classes ... | As you saw, using an int * is rather inefficient. That's because the assignments done to that value can't trigger any other code to run (there's no equivalent to a didSet observer in C). So you're forced to make a separate thread whose purpose is to poll the int value periodically, which is super wasteful.
To fix this,... |
66,208,804 | 66,208,897 | How to redefine (override) C++ __DATE__ and __TIME__ predefined macros in Visual Studio? | Is there any possibility to redefine __DATE__ and __TIME__ predefined C++ macros (give them other than default values) in Microsoft Visual Studio?
I tried compiler option /D "__DATE__=\"Feb 10 2021\"" but I'm getting:
pch.cpp : warning C4117: macro name '__DATE__' is reserved, '#define' ignored
and no effect. Any idea... | No you can't. But you don't need to either. Don't use __DATE__ but e.g. BUILD_DATE and add this:
#ifndef BUILD_DATE
#define BUILD_DATE __DATE__
#endif
And compile with:
/D "BUILD_DATE=\"Feb 10 2021\""
Then you get the exact behaviour you want.
But if you really can't replace __DATE__ with something of your own as su... |
66,208,945 | 66,210,707 | How to compile tesseract baseapi.h with MinGW on window? | So I want to use tesseract api on my project.
And the problem is I don't know how to compile this baseapi.h with MinGW on window.
I'm using this
g++ -I/[...]/project/tesseract-master/include/ -I/[...]/project/leptonica/src/ t.cpp -o t
and got
In file included from t.cpp:2:
/[...]/project/tesseract-master/include/tess... | It seems that you did not install tesseract - otherwise version.h (actually generated during tesseract build/compilation) would be present.
|
66,209,402 | 66,209,644 | Can a C++ interface inherit from a class with full implementation? | I have a specific class structure in mind, though I feel like it could become a little messy when the project gets bigger. The general idea is the following:
There is a class for all possible vehicles with basic implementations that do not change for any vehicle, regardless of its specific type. Then, for all the cars,... |
Can a C++ interface inherit from a class with full implementation?
The C++ language doesn't distinguish between interfaces and other classes. The distinction is purely conventional. Thus from one perspective it would be correct to say that C++ interface cannot [whatever] because there is no such thing as C++ interfac... |
66,209,542 | 66,209,856 | How to pass a class method? | I am trying to use this library for some work. In the example, which is given on their website, they use an operator for defining gradient calculation. I want to use a method,i.e., getGradient, instead of an operator. I have tried several ways, including std::bind(), &Rosenbrock::getGradient. None of them works fine. ... | What about:
struct Bind
{
Rosenbrock & impl;
template <typename X, typename Y> // Template here because I'm lazy writing the full type
double operator () (X x, Y y) { return impl.getGradient(x, y); }
Bind(Rosenbrock & impl) : impl(impl) {}
};
// Then use Bind with your solver:
Bind b(fun);
int niter = sol... |
66,209,587 | 66,215,893 | Can I describe a shared variable in multiple C++ functions that can be called in Octave? | Is it possible to keep a state variable that is shared by multiple C++ functions called by Octave? I tried to explain what I am doing below:
#include <iostream>
#include <octave/oct.h>
#include "stdlib.h"
int x = 0;
DEFUN_DLD(foo, args, , "foo"){
x++;
std::cout << "foo=" << x << "\n";
octave_value_list re... | Based on the information in the comments, you compiled like so:
mkoctfile -c sandbox.cpp
mkoctfile -o foo sandbox.o
mkoctfile -o bar sandbox.o
Instead you should be doing this:
mkoctfile sandbox.cpp -o sandbox
ln -s sandbox.oct foo.oct
ln -s sandbox.oct bar.oct
See the relevant page in the manual for more details: ht... |
66,209,849 | 66,211,363 | C++ scope to define a variable? | Say I have a Class called Tensor and in order to fully construct an instance of the class I need to do a bunch of calculations and define auxiliary variables. In that context, I have seen code from somebody else that used a scope as such:
Tensor t;
{
// lots of calculations to define a, b, c, ..
... |
Is this good practice?
When should I use it? Should I avoid it?
Reduce scope of variable is generally good, but it is generally better to initialize variable instead of set them later (so you can have const for example).
Creating a function or invoking a lamdba would be even better than the scope:
/* const */ Tensor ... |
66,209,879 | 66,215,692 | wxWidgets with MinGW, "wx/wx.h: No such file or directory" | I am new to C++ and wxWidgets. During the last couple of days, I have followed a tutorial with Visual Studio into how to build wxWidgets desktop applications (https://www.youtube.com/watch?v=FOIbK4bJKS8&t=800s).
Now, because I am not familiar with Visual Studio, I wanted to move to edit the code with Atom and compile w... | You can't compile the library with one compiler and then compile the application using it with another, this is just not going to work. You should decide which compiler you want to use (or maybe try using both of them, but not both at the same time!) and follow the official build instructions in the file docs/msw/insta... |
66,209,918 | 66,209,985 | Why can I bind rvalues to non const reference with a for loop in C++? | The logic of the following is confusing me. It compiles ok but the result of foo is an rvalue. It is a temporary. Why am I then allowed to get non constant references to items in the container?
https://godbolt.org/z/vEafrE
#include <array>
std::array<int,3> foo(){
return std::array<int,3>{0,1,2};
}
int main(){
... | The range based for loop has the syntax
attr(optional) for ( init-statement(optional)range_declaration : range_expression ) loop_statement
and it expands into
{
init-statement
auto && __range = range_expression ;
auto __begin = begin_expr ;
auto __end = end_expr ;
for ( ; __begin != __end; ++__begi... |
66,210,094 | 66,210,643 | Smart pointers to an object explicitly created object | I have read a lot of issues created in regard to this but was not able to answer my question.
I have created a class as follows -
class exampleClass{
public:
exampleClass(int n){
cout<<"Created Class"<<endl;
this->number = n;
}
~exampleClass(){
cout<<endl<<"This class is destroyed ... | When you create a shared_ptr from a raw pointer, it takes ownership of the raw pointer, and when the smart pointer goes out of scope, it will call delete on the owned resource. Giving the same raw pointer to 2 different shared_ptrs causes a double free, as both of them will try to free the resource.
If you need 2 share... |
66,210,306 | 66,210,462 | Conversion from 'wchar_t' to 'const _Elem', possible loss of data | TCHAR buf[MAX_PATH];
int aFolder = CSIDL_APPDATA;
if (SHGetFolderPath(NULL, aFolder, NULL, SHGFP_TYPE_CURRENT, buf) != S_OK)
*buf = '\0';
// buf wchar_t
std::wstring str(&buf[0]); //convert to wstring
std::string str2(str.begin(), str.end()); //and convert to string.
std::string str3 = "\\settings.ini";
auto ... | std::wstring is usually either UTF-16 or UTF-32. std::string is usually UTF-8. What you are doing is not a proper way of converting between those encodings. See UTF8 to/from wide char conversion in STL
|
66,210,312 | 66,252,391 | Efficient way of finding minimum path in graph traversal | I have a huge set of binary strings, all of the same length. I know the 1 step neighborhood of every binary string (meaning, all the other binary strings that differ by only 1 bit). This relationships essentially creates a graph. Now, starting from any node in the graph, I would like to know what is the minimum number ... | Found out my first loops where adding the same node multiple times since from the set of nodes to visit it is very likely that some of them have a few neighbors in common. Easily fixed by erasing duplicates in the set of nodes to visit next. I also implemented the suggestions made in the other answer. Here is the resul... |
66,210,411 | 66,210,651 | calling a base function on a derived object | class base{
public:
virtual void foo(){
std::cout << "base::foo was called" << std::endl;;
}
void bar(){
foo();
std::cout << "base::bar was called" << std::endl;;
}
};
class derived : public base {
public:
void foo() {
std::cout << "derived::foo was called" << std::endl;
}
};
... | When a member function in a derived class overrides a virtual member function in a base class like this, that means it entirely replaces the function definition for most purposes. So calling the function foo on the object der created in main will usually use the Derived::foo definition. This behavior is consistent whet... |
66,210,653 | 66,212,171 | DSO missing from command line when compiling | I have seen here several posts with similar questions and tried many suggestions but still, I haven't found a way around my problem.
I use for my work some cpp codes that I have to slightly change according to my needs. They have their own makefile with the same structure. Those files use the same list of libraries and... | The INCDIROPTS field is incorrect. In Makefiles, library locations are specified with -L and the actual library names are linked with -l.
Specify the mysql library with -L/usr/lib64/mysql in INCDIROPTS, and then link it with -lmysqlclient in LNKLIB.
|
66,210,914 | 66,211,431 | How to combine "Values" and "Combine"? | I want to add some special set of values to cartesian product. Something like this:
INSTANTIATE_TEST_SUITE_P(Test, Test,
testing::Values(
testing::Combine(
testing::Values(1, 2, 3),
testing::Values("one", "two", "three")),
testing::Values(std::make_tuple(12345, "big value")... | You can do two instantiations:
INSTANTIATE_TEST_SUITE_P(TestSanity, Test,
testing::Combine(
testing::Values(1, 2, 3),
testing::Values("one", "two", "three")));
INSTANTIATE_TEST_SUITE_P(TestSpecial, Test,
testing::Values(std::make_tuple(12345, "big value")));
Only Combine() accepts other gen... |
66,210,944 | 66,510,807 | qt qml Object already has a QQmlContext | I want get json file from local and send it to QML using this:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QGuiApplication ap... | Maybe a bit late, but did you try importing in your Main.qml without version number?
import QtQuick
import QtQuick.Controls
|
66,211,485 | 66,211,943 | Recognize string formatting Debug Assertion |
I have a runtime problem with code below.
The purpose is to "recognize" the formats (%s %d etc) within the input string.
To do this, it returns an integer that matches the data type.
Then the extracted types are manipulated/handled in other functions.
I want to clarify that my purpose isn't to write formatted types in... | Let's take a look at this else clause:
char bufFormat[1024 + 1];
memcpy(bufFormat, buf + pos, stringSize);
bufFormat[stringSize] = '\0';
The variable stringSize was initialized with the size of the original format string. Let's say it's 30 in this case.
Let's say you found the %d code at offset 20. You're going to cop... |
66,211,795 | 66,211,832 | vector list initializer and assignment | For the two snippet of code, i don't understand the second one
1st: it prints 0 1 2 as expected
vector<int> ivec;
ivec={0,1,2};
for(auto i: ivec){
cout<<ivec[i]<<endl;
}
2nd: it prints 0 0 0 5. How is this random value generated?
vector<int> ivec;
ivec={0,1,2};
ivec={4,5,9,1};
for(auto i: ivec){
... | This is undefined behavior because ivec has size 4 yet you are indexing elements such as 4, 5, and 9 which are out of bounds.
for(auto i : ivec){
cout << ivec[i] << endl;
}
Instead you should be printing the elements themselves
for(auto i : ivec){
cout << i << endl;
}
To be clear, in your range-based for loop i i... |
66,211,808 | 66,212,119 | Visual studio not finding spdlog.lib | I've been trying to create a simple project to understand the build process on Windows.
Recently, I downloaded and installed spdlog library, the folder of installation is located at
C:\Program Files (x86)\spdlog
with the following directories:
bin: with the spdlog.dll inside;
include: all headers regarding spdlog;
lib... | Your build fails because you installed spdlog in a path that contains spaces. Try escaping the spaces:
link_directories("C:/Program\ Files\ (x86)/spdlog/lib")
As far as linking goes, on Windows, dll files are dynamic libraries, while lib files are static libraries.
There are two ways of using (linking) dynamic librari... |
66,211,868 | 66,212,037 | How do I apply cv::Rect on a pointer to image? | I am trying to display half of an image (from a pointer to an image):
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
void main() {
// Load image
std::string path = "Resources/test.png";
cv::Mat img = cv::imread(path);
// Pointer ... | You don't need to use new/delete or pointers for what you're trying to do.
void main() {
// Load image
std::string path = "Resources/test.png";
cv::Mat img = cv::imread(path);
cv::Mat subImg = img(cv::Rect(0, 0, img.cols / 2, img.rows));
// Display left half of image
cv::imshow("left imag... |
66,212,103 | 66,212,546 | Using a range as a parameter pack | I have a function
#include <iostream>
#include <iterator>
#include <vector>
template <typename T, typename P...> Function (T&& Sth, P&&... SthElse) {
//Perform operations on all arguments. For example:
std::cout << Sth << " ";
(std::cout << ... << SthElse);
std::cout <<"\n";
}
If I also have a vector... | You cannot use runtime value for compile time one.
vector size is a runtime value, size of pack is compile time.
But, if you know size at compile time, you might do something like:
template <typename C, std::size_t ... Is>
auto to_tuple_impl(C&& c, std::index_sequence<Is...>)
{
return std::tie(c[Is]...);
}
templat... |
66,212,113 | 66,223,905 | Fill allocated memory with data from another process | Okay, this question is not regular, and maybe stupid, cause im not familiar with pointers and links in c++:
So i have some data in memory of another process (http://prntscr.com/zmfb4p), it's about 1200-1600 bytes.
I have a driver, which can do kernel read-write to needed process.
I have a user-mode application, which o... | So basic function readVirtualMemory doin this(i guess i presented too short explanation above, but nvm now):
template <typename type>
type ReadVirtualMemory(ULONG64 ProcessId, ULONG64 ReadAddress, SIZE_T Size)
{
type Buffer;
KERNEL_READ_REQUEST ReadRequest;
ReadRequest.ProcessId = ProcessId;
ReadReque... |
66,212,222 | 66,212,285 | Template specialization of clearing std::queue with other std containers | I created a function Clear that receives a varied number of parameters, and clears those containers
inline void Clear() {}
template <class First, class ...Rest>
void Clear(First&& first, Rest&&... rest)
{
std::forward<First>(first).clear();
Clear(std::forward<Rest>(rest)...);
}
So I can use it to clear most st... | You might split iteration and job for one element, something like:
template <typename T>
void Clear(std::queue<T>& q) {
std::queue<T> empty;
std::swap(q, empty);
}
template <typename C>
void Clear(C& c) {
c.clear();
}
template <typename ... Ts>
void Clear(Ts&... ts) {
(Clear(ts), ...);
}
|
66,212,273 | 66,212,457 | what does this template do? | In the llvm source code llvm/IR/PassManager.h has this template (comments have been deleted for brevity):
struct alignas(8) AnalysisKey {};
struct alignas(8) AnalysisSetKey {};
template <typename IRUnitT> class AllAnalysesOn {
public:
static AnalysisSetKey *ID() { return &SetKey; }
private:
static AnalysisSetKey S... | Suppose it was not a template and we don't care about alignment, then it would look like this:
struct AnalysisKey {};
struct AnalysisSetKey {};
class AllAnalysesOn {
public:
static AnalysisSetKey *ID() { return &SetKey; }
private:
static AnalysisSetKey SetKey;
};
AnalysisSetKey AllAnalysesOn::SetKey;
The las... |
66,212,399 | 66,212,475 | Forwarding reference for struct as a parameter in a function template with SFINAE | I wonder why this code does not compile:
struct S{ int m; };
template<class T, class = std::enable_if_t<std::is_same_v<T, S>>>
T& operator+=(T&& arg0, int arg1)
{
arg0.m += arg1;
return arg0;
}
int main()
{
S val0{ 0 }; int val1{ 1 };
val0 += val1;
return 0;
}
But it does compile either when ... | The issue here is that for forwarding references, since val0 is an lvalue, T gets deduced as a S&, not a S. That causes std::is_same_v<T, S> to fail as a S is not the same as a S&. To fix this you can use std::decay_t to remove the reference like
template<class T, std::enable_if_t<std::is_same_v<std::decay_t<T>, S>, ... |
66,212,419 | 66,212,826 | Does a range convert to bool via emtpy() member function when used as a if condition? | The following code compiles, runs, and gives the result as if range is being converted to bool via range.empty(). Is it actually what happens? I'm really not comfortable enough in navigating Range-v3 headers, so I'm asking this question here.
#include <iostream>
#include <range/v3/view/take.hpp>
#include <range/v3/view... | The only operations required for a type to fit the std::ranges::range concept (or its Range-v3 equivalent) is being able to perform std::ranges::begin/end on it (or its Range-v3 equivalent). But this does not mean that a range type only has those operations.
A type that fits a concept can implement anything it wants on... |
66,212,481 | 66,212,682 | c++ define empty multidimensional array and pushback array the array | First, how do I define an empty multidimensional array?
Second, how do I then pushback an array into the array?
Where an end result could be something like this: { {string1, int1}, {string2, int2}, {string3, int3}, {string4, int4} }
| Based on the small example you've provided, you want to store a vector of pairs. You can't represent such data in a multidimensional array, because the "inner" array members would need to have different types (string and int), which is not possible. C++ does not support collections with different types, unlike Python f... |
66,212,718 | 66,215,588 | C++ regular expressions fails, while online checker works | I have this code:
class Clazz {
private:
constexpr char _csVersionPattern[] = "^[^\\(\\[\\)\\],]+$";
//constexpr char _csVersionPattern[] = "(^([\\(\\[])[!-'\\*+\\.-Z\\\\^-z\\|~-]*,[!-'\\*+\\.-Z\\\\^-z\\|~-]*([\\)\\]])$)|(^[^\\(\\[\\)\\],]+$)";
constexpr char _csIdPattern[] = "^[!-~]+$";
public:
void func(std::... | The regular expressions you wrote are ECMAScript compatible, but you selected the std::regex::extended flavor, which is POSIX ERE.
In a POSIX ERE pattern, you cannot use regex escape sequences. For example, you cannot put \] inside a bracket expression and expect it will match a literal ]. In fact, it will close the br... |
66,213,416 | 66,235,004 | Why can i not use a function that is linked? | I am developing some library using Gtkmm4. This libraries purpose is to replace the removed API of Gtkmm3 (such as Gtk::Window::move). Especially for this particular function, i need to use gdk_x11_surface_move. The linker says undefined reference to gdk_x11_surface_move. My library libgdp.so links to following Gtk lib... |
I just do not understand why I cannot use that function in my library, even though it is defined / available in the Gtk library.
$ nm /home/user/.local/built/lib/libgtk-4.so.1 --defined-only | grep x11_surface_move
0000000000461cc0 t gdk_x11_surface_move
You are correct that the function is defined in libgtk-4.so.... |
66,213,478 | 66,213,717 | Why is "==" not acceptable here? | I'm writing a unit test and comparing two objects to ensure they're the same but am getting the error no operator "==" matches these operands -- operand types are: Item == Item
This is my code with the line in question commented:
SCENARIO("A container can be created, and items added and removed from it.", "[container]"... | == cannot be used to simply compare two different objects unless specifically defined for the class to compare attributes.
|
66,213,517 | 66,214,793 | Remapping one range of values to another, encountering integer overflow | I need to remap several different ranges of values in my application, for example [0 1.0] to [-1000 1000]. So I created a template class (below) with the previous max/min and type (int/double) and the new max/min and type. The code works for small ranges, but when I try to convert ranges that exceed the integer range I... | One thing that could mitigate this problem would be take out prev_range_ and new_range_ entirely and replace them with a scale factor, which is inherently a floating point number.
#include <stdexcept> // std::out_of_range
template<class P, class N>
class Remap {
public:
/**
* @brief Construct a new Remap obj... |
66,213,706 | 66,215,451 | Tinkercad: Function return user-defined class "does not name type" in Arduino | I had been writing a simple game on Arduino Uno using Tinkercad's simulator. I created a class named Bullet and a class named MainCharacter, I put it directly into the code editor of Tinkercad since it cannot be imported multiple .h and .cpp files like a normal Arduino compiler.
class Bullet{
private:
int ... | I've never used tinker cad before, but I managed to get your project to compile.
Here's my change to the declaration of spawnBullet(), this more or less comes from C, even though some c++17 features like auto do work in tinker cad.
class Bullet spawnBullet(int flySpeed, int locationY)
{
//...
}
The main .ino file ... |
66,213,712 | 66,220,869 | parallel eclipse does not recognize true number of processors when using MPI | I have the following code that when executed with eclipse 2020.12, the output is this: "Hello from rank 0 out of 1"
#include <iostream>
#include <mpi.h>
using namespace std;
int main(int argc, char* argv[])
{
MPI_Init(&argc, &argv);
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int size;
MPI_C... | Create a new run configuration from the Parallel Application template. On the Resources tab, set Target System Configuration to Generic OpenMPI Interactive or Generic MPICH2 Interactive based on whether your MPI implementation derives from Open MPI or MPICH. Set Connection Type to Local. Then set the number of processe... |
66,213,879 | 66,215,499 | Finding Twos complement, | Here is the code to compute: anyone, with help to convert a signed integer to its binary equivalent (8 bits) (in 2's complement) and vice versa. The program should be able t0 first read in either a signed integer or a binary number (always in 2's complement) provided by the user
For example, when I input 00110101 to co... | I am assuming you want this for didactic purpose, other wise you just do (signed char) n.
The two complements is -2<<(n-1) + sum(2<<k for 0 <= k < n-1) so for 8-bit you have the usual binary representation for the numbers 0 <= N < 128 the difference is that the most significant bit is not adding 128, but subtracting 12... |
66,213,905 | 66,214,117 | c++: is there a way to ensure the compiler that calling twice the same const method gives the same result? | I am puzzled with the following 2 simple snippets:
#include <vector>
struct A{
int foo(int i) const {return v[i];}
std::vector<int> v;
};
int f(const A &a, int i) {
int j;
j=a.foo(i);
j=a.foo(i);
return j;
}
which gives the assembly code:
movsxd rax, esi
mov rcx, qword ptr [rdi]
mov ... | The fact that the member function is const-qualified does not mean that the function does not have any side effects. Without seeing function definition, the compiler cannot be sure that the function doesn't output something into a file, doesn't send something over the network, etc. Thus, in general, calling the same me... |
66,213,922 | 66,213,972 | How do I declare, send classes with unknown template argument into function? | Let's say I have a class DogClass that takes in something like this
DogClass<Poodle::Medium>
Where it could be be anything in the template. I need to do many different operations on them so I want to make a function like this.
void DogAnaylzer(DogClass<T>) {
size = DogClass<T>.size();
weight = DogClass<T>.weig... | Your function could itself be a template
template <typename T>
void DogAnaylzer(DogClass<T> const& dog) {
auto const size = dog.size();
auto const weight = dog.weight();
auto const density = weight / size;
...
}
Note that you'd call methods off the instance (e.g. dog.size()) not the class itself (e.g. ... |
66,214,034 | 66,214,112 | 2D array inside a vector for multiple checkers boards | I've got a 2D array which contains the current values of squares for a checkers game. The values change after every move. I want to save the state of the board after every move. So i decided to use a vector with a 2D array inside of it. (If this is possible)
std::array<std::array<int, 8>, 8> boardArr; //this is my boar... | To much unnecessary code. You access vector elements, but do not fill the vector.
void saveBoard()
{
savedBoard.push_back(boardArr);
}
|
66,214,411 | 66,214,773 | Default struct initialisation in any case? | I realized that in C++ you can initialize any structure with default values. I don't think that was possible under C. Is that correct?
Are there situations in which it still makes sense not to use such a default initialization? Or is it better in any case since it is safer?
I also saw that there are different ways to d... |
I realized that in C++ you can initialize any structure with default values. I don't think that was possible under C. Is that correct?
Yes.
Are there situations in which it still makes sense not to use such a default initialization?
If you target Older standard than C++11 - or cross-compatibility with C. Default m... |
66,215,180 | 66,215,276 | Which of the two structs is best to use in general? | I agree that the struct with the static function is much easier to use, however I always receive advice that static functions and/or variables shouldn't really be used.
struct Factorial_Local
{
size_t factorial(size_t n)
{
size_t fact = 1;
for (size_t i = 1; i <= n; i++)
fact *= i;
... | This is opinion based, so someone will probably close it, but...
Your trivial example is pretty. Using a namespace is better for this. Use non-static methods when they really work on an instance of your object. Use static methods when they're truly related to the class of object.
And use namespaces when you're just try... |
66,215,491 | 66,227,939 | gcc cannot find winedef.h for wow64 build of wine 6.2 | I compiled the wine 6.2 with wow64 build instructions: https://wiki.winehq.org/Building_Wine#Shared_WoW64
Everything seemed to work fine except when I tried to install wineasio and playonlinux, gcc could not import windef.h (fatal error: windef.h: No such file or directory).
The file exists in /usr/local/include/wine/w... | I moved /usr/local/include/wine/ to /usr/include/. It's fixed now.
|
66,215,557 | 66,217,733 | How to add/initialize members in an SML state or state machine? | I designed this state machine using boost::sml
struct LooperStateMachine {
auto operator()() const {
using namespace sml;
return make_transition_table(
*"beggining"_s + event<heel> / onRecordFirstLoop.value() = "recording_first_loop"_s,
"recording_first_loop"... | To your literal question you might just provide a default constructor/NSMI. However I get that you want to be able to "dynamically" switch out these action "hooks".
About injecting the function hooks, the docs say:
SML states cannot have data as data is injected directly into guards/actions instead
This gave me the i... |
66,216,007 | 66,216,476 | Do I need to declare a constructor and destructor in a new class? | I am noticing a lot in my data structures class that they are declaring constructors and destructors. This is for C++ by the way.
| Do these objects allocate and retain memory? Do they allocate resources that must be released?
If so, yes, a destructor is required. If not, no.
This is all part of understanding C++ RIAA which is the defining methodology here.
Constructors aren't necessary for struct, those are often treated as "dumb data" with no bui... |
66,216,075 | 66,216,115 | Printing tree by levels? | Reading the first suggested algorithm on: https://www.geeksforgeeks.org/level-order-tree-traversal :
/*Function to print level order traversal of tree*/
printLevelorder(tree)
for d = 1 to height(tree)
printGivenLevel(tree, d);
/*Function to print all nodes at a given level*/
printGivenLevel(tree, level)
if tree is ... | You scan each node h(branch)-h(node) + 1 times.
See this example:
A
\
B
\
C
\
D
At printGivenLevel(tree, 1), you scan only A, and finish.
At printGivenLevel(tree, 2), you scan A and B, and finish
At printGivenLevel(tree, 3), you scan A, B and C, and finish
At printGivenLevel(... |
66,216,272 | 66,216,324 | How to write a C++ constructor with same signature as copy constructor? | I am writing a class that can optionally have a reference to its parent. In other words the class looks something like this:
class X {
const X* parent;
public:
// (1) Default constructor with no parent
X() : parent(nullptr) {}
// (2) Constructor that accepts a parent
X(const X& parent) : parent(&pa... | You can use tag dispatching to handle this by creating a tag type that you using to signal you want the construct with pointer to parent behavior instead of copy construction. That would look like
struct parent_reference {};
class X {
const X* parent;
public:
// (1) Default constructor with no parent
X()... |
66,216,328 | 66,216,351 | How to avoid circular dependency in this project? | My project at the moment is set up something like this
game.cpp
#include "game.h"
#include "enemy.h"
class Game {
public:
...
...
std::vector<Enemy> enemies;
...
};
enemy.cpp
#include "game.h"
class Enemy {
public:
...
...
void turn(Game* game);
...
};
I obviously under... | If those are the only dependent functions, you could declare and initialize in the following order:
class Game;
class Enemy {
public:
void turn(Game* game);
};
class Game {
public:
std::vector<Enemy> enemies;
};
Live example: https://ideone.com/g6Vmwi
|
66,216,913 | 66,217,006 | How do I initialize a constant global variable from a runtime arguments? | So, I've seen questions here on how to set global constant variables at runtime by prompting the user for input then using cin. However, I need to be able to set a constant global variable based on one of the arguments passed to main (ie from argc/argv). All of the solutions I found involved having a constructor functi... | Objects in global scope gets constructed before main() gets invoked, so it's logically impossible to use main's argc and argv to construct them. This is a fairly fundamental chicken-and-egg problem, and there is no portable way around it.
It might be possible to cheat and use function static scope to simulate it, somet... |
66,217,443 | 66,218,035 | Are the Performances of these two programs the same? | Say for example you have a linked list 1->2->3->4->5->6->NULL and you want to calculate the total of the even indices of that linked list (assuming that the 1st index starts with 1 and the size of the linked list is even)
First Approach
int total = 0;
int count = 0;
Node *ptr = head;
while(ptr != NULL)
{
if(count %... | I read your question again and will answer that probably the second method is slightly faster.
Now, the comments section immediately highlighted that it's also more dangerous. You have actually specified that the assumption is the number of nodes in the list is even. If that is a guaranteed and enforceable preconditi... |
66,217,479 | 66,392,670 | Can you use constraints on derived classes in CRTP methods? | Is something like this valid C++20 code?
#include <iostream>
template <typename T>
concept impls_decrement = requires(T it) { it.decrement(); };
template <class Derived>
struct iterator_facade {
Derived& operator--()
requires impls_decrement<Derived>
{
auto& self = static_cast<Derived&>(*this);
self.d... | As Barry mentioned, the code is valid and this is Clang bug 44833.
In the meantime, I was able to work around the issue by writing the code like this (demo):
#include <iostream>
template <typename T>
concept impls_decrement = requires(T it) { it.decrement(); };
template <class Derived>
struct iterator_facade {
tem... |
66,217,662 | 66,217,688 | Using const in getters in C++ | I am having a hard time understanding this purpose of const at the end of the getter declaration. What purpose it has here?
// Define getter
std::string Car::brand() const
{
return _brand;
}
Thanks in advance. :)
| The const specifier serves the purpose of clarifying what this method is allowed to do. If a member function is declared const, you can be sure that it is not going to modify any members of that instance.
|
66,217,741 | 66,218,284 | Is it guaranteed that std::char_traits<char>::to_int_type(c) == static_cast<int>(c)? | The question How to use correctly the return value from std::cin.get() and std::cin.peek()? made me wonder if it is guaranteed that
std::char_traits<char>::to_int_type(c) == static_cast<int>(c)
for all valid char values c.
This comes up in a lot of places. For example, istream::peek calls streambuf::sgetc, which use... |
Does that mean this implementation is conforming, and therefore std::cin.peek() == '\n' does not do what it is supposed to do?
I agree with your analysis. This isn't guaranteed.
It appears that you would have to use eq_int_type(std::cin.peek(), to_int_type('\n')) to guarantee correct result.
P.S. Your to_char... |
66,218,002 | 66,218,023 | Why am I getting this error: class CSE has no member named EnterRN and EnterName? | #include <iostream>
using namespace std;
class CSE
{
private:
char Name;
double Roll;
public:
void getN(char N, double RN)
{
Name = N;
Roll = RN;
}
};
char EnterName()
{
cout << "Enter the name of the student" << ;
}
char EnterRN()
{
cout << "enter the rn" << ;
};
int main... | You are defining (free) functions instead declaring and defining a method:
class CSE {
...
public:
char EnterRN();
};
char CSE::EnterRN() {
...
}
If you want to do it inline then the closing } of the class needs to be after those functions.
|
66,218,214 | 66,218,302 | why (var) is considered as lvalue? | I was trying to understand decltype in C++ through one of the stack overflow questions What is decltype and how is it used?
Part of accepted answer is as below.
int foo();
int n = 10;
decltype(n) a = 20; // a is an "int" [id-expression]
decltype((n)) b = a; // b is an "int &" [(n) is an lvalue]... | The expression n is an lvalue ; and putting parentheses around an expression does not change the value category.
As covered in the question already linked:
decltype( (n) ) is the syntax decltype( expression )
decltype( n ) is the syntax decltype( id ) .
The latter is not decltype expression with an expression of (n... |
66,218,262 | 66,218,714 | can i just mmap a file and revise it without writting back? | I want to open a file in memory, and revise some elememts.
here is the code:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include<sys/mman.h>
#include<sys/types.h>
#include<string.h>
#include<unistd.h>
#include <iostream>
using namespace std;
int main(int argc,char *argv[]) {
in... | You want MAP_PRIVATE flag to mmap. It is defined as following:
MAP_PRIVATE:
Create a private copy-on-write mapping. Updates to the mapping are not visible to other processes mapping the same file, and are not carried through to the underlying file. It is unspecified whether changes made to the file after the mmap() ... |
66,218,476 | 66,218,611 | My selection sort replaces some numbers in the array with 0 | This is the complete code that I wrote:
( [numsin the function] and [arrin main] is the array that needs to be sorted, sizeis the amount of numbers in the array, minis the smallest number in the unsorted part)
#include <iostream>
#include <vector>
using namespace std;
void sort(vector <int> &nums, int size){
int m... | Your swapping logic doesn't handle the case where the smallest remaining element is the first unsorted element (i.e., i == min). Consider what each line does in this case:
nums[i] = nums[min] + nums[i]; //nums[i] will be doubled
nums[min] = nums[i] - nums[min]; // nums[min] is subtracted from i... |
66,218,888 | 66,223,732 | How to change read/write method of source/sink device in C++ boost::iostreams? | I'm trying to get familiar with boost::iostream, so in a example program I'm writing, I want to read a text from a file and write it to file.
I would use my inherited class from file_source/file_sink as device to read/write. In the read method, my class needs to add each character with one and write method needs to sub... | I solved the problem...
template <typename charType>
class MyFileSource : public boost::iostreams::file_source
{
public:
MyFileSource(const std::string& path) : boost::iostreams::file_source(path)
{
if (!is_open())
open(path);
}
std::streamsize read(charType* s, std::streamsize n)
... |
66,218,922 | 66,219,082 | How does gcc search framework headers on Mac OSX(10.15)? | By gcc -v I know that gcc searches in these paths:
/usr/local/include
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/11.0.3/include
/usr/include
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include
/System/Library/Frameworks (framew... | Two lines in the gcc -v output is a hint about special directories that are handled not like include directories.
/System/Library/Frameworks (framework directory)
/Library/Frameworks (framework directory)
Apple's gcc for Darwing architecture has special extensions for finding include files from framworks. You can re... |
66,219,511 | 66,220,107 | How to automatically determine IDs for gameObject's? | I'm trying to make ECS (Entity-Component-System) in C++ right now.
Here is my GameObject class :
class GameObject
{
private:
int ID
/*gameobject name, tranform */
public:
int GetID();
template<class component>
void AddComponent()
{
component::ComponentAdded(this->ID);
}
tem... | In order to have a unique value for each instance of GameObject you can:
introduce a static counter (of instantiations, not of existing instances) to the class GameObject
uincrement it in the constructor of the class GameObject
use its current value, at the time of instaatiating a new object which inherits `GameObject... |
66,219,755 | 66,220,788 | Why the superfluous calls to filter functions when `std::views::reverse` is used? | I am trying to understand the sequence of calls to filter functions when passed through pipe operators (views/adapters). The result I see is not intuitive at all. While there might be reasons for it, I'd appreciate if someone can walk this through. As well if one can point to right documentation on cppreference.com.
#i... | The range-based for loop in question can be rewritten to
auto&& range = vec
| std::views::reverse
| std::views::filter(filter)
| std::views::take(2)
| std::views::reverse;
auto begin = range.begin();
auto end = range.end();
for (; begin != end; ++begin) {
auto v = *begin;
std::cout << std::end... |
66,220,046 | 66,258,213 | I am trying to encrypt a text file using vigenere cipher and xor in c++ but my it will not encrypt the file | Here is the updated code with encryption algorithm:
#include<iostream>
#include<string>
#include<fstream>
int main()
{
char ch;
char cch[128];
char pch[128];
std::string str;
std::string key = "01100011 01100001 01110100";
std::fstream pFile;
std::fstream cFile;
pFile.open("plaintext.t... | So the problem is the structure of your code. You have some file read/writing code which is fine, and you have some encryption code which is more or less fine. But the problem is that you haven't combined these two pieces of code correctly. In fact the way you have written it the two parts of the code are entirely sepa... |
66,220,069 | 66,220,211 | This may be due to a corruption of the heap error when i run program in MFC 0f c++ | When i run program start it will show an Error as in the picture.
enter image description here
and When i clikced continue it will show an Error as in the picture
enter image description here
This is the code structure I wrote.
int nSites = 0;
int nTasks = 0;
int nThreads = 0;
CCriticalSection cs;
BOOL bUpdateList=fals... | Look at this
char *buffer = new char[10240];
...
delete [] buffer;
if (buffer != NULL) {
HeapFree(GetProcessHeap(), 0, buffer);
}
You don't need to use delete[] and HeapFree. Because you used new[] to allocate buffer you should use delete[] to free it. Remove the cal... |
66,220,765 | 66,220,923 | Why does my while loop allow the wrong amout of tries | Im just learning c++ and have this program I'm wondering why when I run the program through terminal it allows 5 trys when I set tries <= 3 and if I change it to tries <= 1 it allows the correct amount of tries
#include <iostream>
using namespace std;
int main() {
int pin = 0;
int tries = 0;
cout << "BANK ... | You start loop counter from zero. So it has 4 iterations:
0 <= 3 = true
1 <= 3 = true
2 <= 3 = true
3 <= 3 = true
Loop will break on 5-th iteration because condition would fail (4 <= 3 = false). So you have to change condition from <= to < and it'll work correct or start counting tries from 1.
Also you left pins' inp... |
66,221,525 | 66,264,874 | Why did STL made a(nother) distinction between a std::array and a std::initializer_list | Why is there not only 1 type with the best performance, to define a list at compile time?
The benchmark is clear, the constexpr std::initializer_list is faster, uses even less memory and the IO-reads are astonishingly less over constexpr std::array:
https://build-bench.com/b/1EDAcFjJ6NACk4Pg4tG2nbsEx0A
So why didn't th... | The question betrays some misunderstandings about what is going on here.
std::array is an array object. It is an object whose storage size is the storage for its array elements. std::initializer_list is a pointer to an array (one created by the compiler). You can heap-allocate std::array for example; you cannot heap-al... |
66,221,531 | 66,221,756 | How to overload [] for a templated function | I'm tasked with improving C arrays by implementing an array class with various functionality. I'm trying to overload '[]' but I've ran into an issue.
template<typename T>
class SA{
private:
T* pT;
//other vars...
public:
//other initialization functions...
int& operator [](int offset);
};
template<typename T>
int&... | The return type of the function should be T&, not int&:
T& operator [](int offset);
Also note that, while it is nice that you check to make sure the index is in range, you don't actually do anything about it. One solution is to throw an exception:
#include <stdexcept>
template <typename T>
T& SA<T>::operator[](int of... |
66,221,946 | 66,222,024 | print a list of numbers using template metaprogramming | I am unable to figure out why does following code not compile. Could you guys please help me?
#include <iostream>
template <typename T, typename ...Args>
void foo(T i, Args ... args){
std::cout << i << std::endl;
foo(args...);
}
template <typename T>
void foo(T i){
std::cout << i << std::endl;
std::cout << "e... | Functions must be declared before they can be called. Change the order of functions.
Your special case is not a specialization of the base case, so the base case cannot see it. Because the template argument list is different, it is simply an overloaded function.
template <typename T>
void foo(T i){
std::cout << i << ... |
66,222,089 | 66,226,537 | C++20 P0784R7 Non-transient allocation too brittle vs. P1004R2 constexpr std::vector | I would like to create an extensive constexpr data repository in C++20. Tens of thousands of hopefully native C++ objects loaded as "text segment" i.e. demand paged into the process and shared between instances (the code is generated).
The objects are referencing each other and need indexing by various properties, cros... | You have a misunderstanding of transient allocations. Transient allocations are allocations that exist entirely within constant evaluation. For example:
constexpr std::size_t summation(std::vector<unsigned int> const &vi)
{
std::size_t ret = 0;
for(auto i : vi)
ret += i;
return ret;
}
constexpr auto sum = su... |
66,222,196 | 66,234,809 | Using native cpp testframework in visual studio to test c code LNK2019 | I try to set up a test project in Visual Studio 2019.
The module that I want to test is written in c.
I'm using the native VS cpp Testframework.
I can compile and run my program but not my unittest. Once I try to run that one I get the following error:
Fehler LNK2019 Verweis auf nicht aufgelöstes externes Symbol "_is_p... | After I tested the code, I found that it has nothing to do with the C file.
First of all, you need to check if you have added ..\calc\Debug\*.obj in Properties->Linker->Input->Additional Dependencies.
Then, you could add the reference to the calc in References.
|
66,222,235 | 66,222,723 | Visual Studio "item + item" issue | So I'm having some issues with Visual Studio
Here's my current issue
const char* Char1 = "Foo ";
const char* Char2 = "Bar ";
const char* Char3 = Char1 + Char2;
/* ^
This is where the error is coming
Here the error I'm getting
expression must have integral or unscoped enum type
*/
This is for s... | You can't add two pointers in C++. I suggest you use std::string.
In C++20:
#include <string_view>
#include <format>
void newStyle(std::string_view const name) { // note string view
auto path = std::format("./Assets/Styles/{}.style", name);
// ...
}
Most compilers don't support std::format yet. In the meantime, y... |
66,222,594 | 66,223,086 | How to use multi-inheritence with std::shared_ptr? | So, I have code like this:
class IUpdatable {
virtual void onUpdate() = 0;
};
class IDrawable {
virtual void onDraw() = 0;
};
class IEventable {
virtual void onEvent() = 0;
};
class IObject {};
class Button : public IObject, public IUpdatable, public IDrawable, public IEventable {/*override of virtual meto... | Something like this could work:
#include <vector>
#include <memory>
class IUpdatable {
public:
virtual void onUpdate() = 0;
};
class IDrawable {
public:
virtual void onDraw() = 0;
};
class IEventable {
public:
virtual void onEvent() = 0;
};
class IObject {
public:
virtual ~IObject() = default;
};
cla... |
66,222,696 | 66,222,715 | print a list using variadic templates | I need your help to find out why does following code not compile.
#include <iostream>
template <int I>
void foo(){
std::cout << I << std::endl;
std::cout << "end of list" << std::endl;
}
template <int I, int ... Ints>
void foo(){
std::cout << I << std::endl;
foo<Ints...>();
}
int main(){
foo<1, 2>();
re... | foo<2> matches both templates equally well (since int... matches zero ints too) which is why the compiler complains about ambiguity.
Isn't a more specialized function is supposed to be chosen?
Yes, but a these are equally special. Deducing which is the more specialized matching function is done by looking at the argu... |
66,223,241 | 66,227,796 | How to install Clang 11 on Debian | I am trying to compile a C++ project on a PC with "Debian GNU/Linux 10". The project requires clang, so I installed it with:
sudo apt-get install clang
But I run into the following error:
Clang version must be at least 11, the version used is 7.0.1
How can I install clang 11?
Note: I do not want to install the entire... | I found the solution after some searching. Here is what I did to make it work:
Add the following lines to your /etc/apt/sources.list:
deb http://apt.llvm.org/buster/ llvm-toolchain-buster main
deb-src http://apt.llvm.org/buster/ llvm-toolchain-buster main
deb http://apt.llvm.org/buster/ llvm-toolchain-buster-10 mai... |
66,223,446 | 66,223,558 | Write a function that will return string after fetching message using FormatMessage | I wanted to write a function that will take error_code as argument and fetch the error message and the return the message. But for FormatMessage the memory allocated is cleared by using LocalFree(err_msg). Not sure how can this be dont along with returning.
static char* return_message(int error_code) {
LPTSTR err_ms... | Seeing as you're using C++ you can copy the resulting message into an std::string instance, free the C-string and return the copy. std::string's destructor will take care of deallocation when its no longer used.
#include <string>
#include <windows.h>
static std::string return_message(int error_code) {
char* tmp_msg... |
66,223,606 | 66,223,696 | Copying a string into an empty string without using a lib function | I'm trying to copy a string p into an empty string stack using a function push. I don't wanna use any other function like strcpy or concat.
#include<bits/stdc++.h>
using namespace std;
int tos=0;
void push(char *stack, char c)
{
stack[tos++]=c;
}
int main()
{
int i;
char p[]="([]}";
char stack[]="";
... | You're found out why C++ is so much easier, with std::string. Doing this manually, the old-fashioned way is fraught with dangers. The new way is just stack = p; Literally, it's that simple.
stack is not an "empty string" in your code. It's a char[1]. You cannot copy any characters into it, because that one char is need... |
66,224,510 | 66,224,676 | Simplest way to pass a lambda as a method parameter in C++17 | Google is showing me lots of SO posts on passing lambdas as arguments, but they all seem to be C++0x/C++11 based (e.g. Use a lambda as a parameter for a C++ function) and I understand this is an area that has improved in more recent C++ versions?
I want to pass what is effectively a very simple delegate return MyGlobal... | A function that just wants to invoke a passed lambda or other functor during its own execution can be a function template, deducing the type of the functor:
template <typename F>
void use_it(F&& func) {
do_something_with(func());
}
Here you want to store the functor to be invoked later, so we'll need a common type... |
66,224,970 | 66,225,361 | Multiple classes need access to a static variable | We have classes A, B and C, all of which need access to a static variable staticVariable in class D.
Moreover, class A needs to have an instance of classes B and C like this:
class A{
public:
B instanceB;
C instanceC;
};
Class D hold the static variable of object type T:
class D{
public:
... |
I'm not sure if I need an instance of D in main.
You don't. static variables are global, they are shared by all the instances of the same class and you don't need to instantiate a class to be able to use such variables so they must be initialized regardless of class instantiation. That being the case they need to be ... |
66,225,638 | 66,225,774 | At which point of destructor call the object ceases to exist? | When a destructor of an object is called, at which point does the object cease to exist?
Does it happen in the moment when its called? or after it finishes deleting the memory of the object's members inside the function?
I'm mainly asking it in order to understand if it's legal to call an object's function inside its d... |
At which point of destructor call the object ceases to exist?
The lifetime of the object is ended by the call to its destructor. Within the destructor body, the sub-objects are still alive and member functions may be called. After the destructor body, the sub objects are destroyed.
if it's legal to call an object's ... |
66,226,280 | 66,226,333 | How to pass data member as default argument to class method? | I am creating a recursive function to reverse a linked list.
class LinkedList {
node *head;
public:
node *reverse(/* Here, I want to pass the head as a default argument */);
}
I have tried to do node *reverse(node *nd = this->head) but it raises the following error:
'this' may only be used inside a nonsta... | The problem is, the default argument is supposed to be provided from the caller context, where this doesn't exist.
You can provide an overload.
class LinkedList {
node *head;
public:
node *reverse(...);
node *reverse() { return reverse(this->head); }
};
|
66,226,306 | 66,226,307 | How to transliterate ASCII control characters to their UTF-8 symbolic equivalent? | I want to transliterate any character in the control character range (0x00 NUL to 0x1F) to the Unicode symbol for that character encoded as UTF-8. Do you have a simple/elegant solution in C++?
Example:
Rather than print '\n' in the string, replace it with the 'N-L' control symbol, and do this for all unprintable charac... | std::string ReplaceASCIIControlCharacters(std::string input)
{
std::vector<uint8_t> output;
output.reserve(input.length());
for (char c : input) {
if (c >= 0x00 && c <= 0x1F) {
output.push_back(0xe2);
output.push_back(0x90);
output.push_back(0x80 + c);
} e... |
66,226,370 | 66,226,512 | How to read JSON file which has values with parameters in C++ | I'm trying to read in a JSON file using C++. In the file i have key value pairs. And in the value, I am passing number of values with different parameters.
Is this approach is correct? Please suggest if there is any modifications required?
approach1:
"test_details" : {
"testd" : "1",
"testvalue":["one",... | Yes it is possible to parse that json into an object. I highly prefer the second approach. Say you go with the second approach, you can create a TestCase class that looks look like:
class TestCase {
public:
std::string id;
std::string value;
// std::vector<std::string> values; // this will hold multiple valu... |
66,226,425 | 66,226,426 | Boost awaitable: how to await on async operation inside post | I was writing some asio code and tried to refactor it to use C++20 coroutines. However I got stuck transforming this code:
asio::post(
my_strand,
[self = shared_from_this()]() {
// functions that write in this container can only be called
// on a single thread at a time, thus the strand
... | Simply send asio::use_awaitable instead of a callback to post. This will make your function awaitable. You will then be able to put your async calls directly in your function:
co_await asio::post(my_strand, asio::use_awaitable);
// ...
// code that runs on the strands context
// ...
co_await socket.async_write_some(buf... |
66,226,727 | 66,227,010 | c++ Container that preserve insertion order | I have a std::map which store a key with a vector of std::any.
The purpose is to store all values and print them (with the different types) for each key.
No other operations are performed on the container, only "insertion" and "clean".
I want to clarify that the container is filled (and emptied) very frequently, so i n... | There is no standard library container that both provides fast access by key (which is presumably why you're using std::map to begin with) and "preserves insertion order". If you really need access by key, then iteration order is something you give up control over.
If you need to recover the order of insertion, then yo... |
66,226,874 | 66,226,940 | C++ dynamic memory allocation weird output | I'm learning about dynamic memory allocation in C++. On running the code below, different output is printed every time.
char *const dynamic_array = new char[50];
dynamic_array[0] = '\0';
dynamic_array[0] = 'a';
cout << dynamic_array << endl;
delete[] dynamic_array;
Example output(s) of 5 runs:
aδ
aδ
aⁿ
aΓ
aε
why is ... | This is unrelated to dynamic memory allocation but only to the legacy C string. A C string is a null terminated char array. As you failed to properly write a null character ('\0') after the 'a', using it as a C string is undefined behaviour.
|
66,227,096 | 66,227,221 | Get a list of results from by conditions | I will want to get a list of resaults by this condition of reg expression:
QRegExp rx(
"(https://)"
"(.*)"
"(\\.jpg)"
);
QStringList list;
int pos = 0;
while ((pos = rx.indexIn("jpegData_https://sfasdfsf_sadlfkjnsdlfjhn.jpgasodjfhasdfoho;usdoauhfsvc.asdfkpjhttps:/... | By default, matching is greedy. Your desired behavior should simply be a case of calling setMinimal(true) on your QRegExp.
e.g.
QRegExp rx("(https://)(.*)(\\.jpg)");
rx.setMinimal(true);
|
66,227,180 | 66,227,549 | Boost Process 1.71 does not look in environment path anymore | I have been using boost 1.65, did not change the code, updated boost to version 1.71 and now suddenly boost::process::child("command-in-path") does not inherit the environment of the executing process. How can I recover the behavior, is it possible without parsing the command every time to find the executable in path?
| I haven't checked whether the behaviour actually changed, but I know there's a way to explicitly allow Boost to search the path:
Keep in mind that searching the path can easily be a security issue because it can be compromised, or attackers can leverage knowledge of the path setting to intercept executables. This is w... |
66,227,246 | 70,320,798 | Catch2 undefined reference to Catch::StringMaker | I am using Catch2 from the actual devel branch and I have a linker error when trying to compare two vector<string_view>
The issue can be reproduced as following:
#include <vector>
#include <string_view>
#include <catch2/catch_test_macros.hpp>
TEST_CASE("Can split string", "[split]") {
vector<string_view> splittedStr... | Solution
You need to build Catch with C++17 support to be able to use string_view inside REQUIRE() and other macros. By default, Catch is built with C++14 for some reason.
To do so you can run this in directory with your Catch sources:
mkdir build && cd build
cmake -DCMAKE_CXX_STANDARD=17 ..
sudo make install
Notes
Y... |
66,227,261 | 66,228,113 | wstring data to const uint32_t* | I have an object of type std::wstring and a library function which takes const uint32_t* as an argument. My code is running on platforms where sizeof(wchar_t) == 4. There is no API in the library (harfbuzz) which takes const wchar_t*, so I must convert my std::wstring. I know that reinterpret_cast is not safe (it viola... | Only possible way in standard C++ to avoid both type aliasing violations, and avoid copying is to reuse the storage of the std::wstring buffer and "create" the array of std::uint32_t in its place:
template<class Dst, class Src>
Dst*
reinterpret(std::span<Src> src) noexcept
{
static_assert(sizeof(Src) == sizeof(Dst)... |
66,227,292 | 66,227,866 | C++ Pointers and C-style array initialization | Long time java programmer here, new to C++. I have been working with C-style "traditional" arrays (similar to arrays in java). I understand in C++ we can create a simple array as follows:
Person people[3];
The contents of this array is essentially uninitialized junk values. When I print out the contents of each element... | I believe the problem stems from this misconception :
From my research, C++ does NOT fill arrays with objects of the specified type automagically.
C++ objects have value semantics. Defining a local variable of type T concretely creates a unique instance of that type, it is not a handle to a potential T. The expressio... |
66,227,387 | 66,227,586 | please help me with max_element function in c++ stl | Below is my code, I am new to C++ please help why this is giving error, I want to find max among element without using any extra space.
Code:
#include <bits/stdc++.h>
using namespace std;
int main() {
cout<<*max_element({4,6,2,5});
}
Error:
error : prog.cpp: In function ‘int main()’:
prog.cpp:5:30: er... | you can use max instead of *max_element. Refer below:
cout<<max({4,6,2,5});
It will give your desired output.
|
66,227,469 | 66,227,760 | Reading an address containing 11111111 as an unsigned int shows 4294967295 | So, I was trying some stuff and I noticed that if you read one address that contains 11111111 as an unsigned int it shows that is value is 4294967295 and not 255, why is that?
Example of the code:
unsigned int a = 255;
unsigned int* p = &a;
char *p0 = (char*)p;
cout << (void*)p0 << " " <<(unsigned int)*... |
char *p0 = (char*)p; Here p0 points at the lowest byte of p. What value that happens to be stored there depends on endianess. Could be 0x00 (Big Endian) or 0xFF (Little Endian).
What is CPU endianness?
*p0 here you access the contents of the supposed char. Since char has implementation-defined signedness, it could ei... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.