question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
65,246,548 | 65,248,634 | Are there some circumstances that boost::function could not be replaced by std::function? | Are there some circumstances that boost::function could not be replaced by std::function?
It would be better if you could give some simple examples.
| From theboostcpplibraries.com:
If you work in a development environment supporting C++11, you have access to the class std::function from the header file <functional>. In this case you can ignore Boost.Function because boost::function and std::function are equivalent.
But it might depends of version of boost, see his... |
65,246,970 | 65,247,124 | Alternative to `#define` macro for function alias in C++ | fmtlib has a function like:
template <typename S, typename... Args, typename Char = char_t<S>>
inline std::basic_string<Char> format(const S& format_str, Args&&... args) {
return internal::vformat(
to_string_view(format_str),
{internal::make_args_checked<Args...>(format_str, args...)});
}
I've defined a ... | You can define the same function with a shorter name (in your own code). This function is named FMT() and it passes its parameters to fmt::format(), which is the original function you want to call:
template <typename S, typename... Args, typename Char = fmt::char_t<S>>
inline std::basic_string<Char> FMT(const S& format... |
65,247,633 | 65,247,771 | How to fix template parameter as one enum class based on another template parameter? | I have the following code where as of now, we have clothes, and footwear. But in future there can be many more item Object types. The class Foo is templated with Object and its member functions here are the same for both eClothes and eFootwear, but things are templated further in actual code.
Is there a way to deduplic... | Define traits that maps Object to its value type. Like:
template <Object value> struct ObjectTraits;
template <> struct ObjectTraits<Object::clothes>
{
using type = eClothes;
};
template <> struct ObjectTraits<Object::footwear>
{
using type = eFootwear;
};
template <Object type>
class Foo{
public:
using Ki... |
65,248,891 | 65,248,929 | C++ - algorithm checking the value of (x * y + x + y) / (x-y), when x = 1.4 and y = 5.8 | This is the code. When I run it, nothing appears, just darkness. Blank.
I'm a beginner, and I don't really know too much about coding. Any help would be appreciated.
#include <iostream>
using namespace std;
int main()
float x;
float y;
float Wynik;
x = 1.4;
y = 5.8;
Wynik = (x * y + x + y) / (x-y);
return 0;
}
| Because you aren't printing out anything in your console. To print your results, use std::cout << Wynik;. And also, you have an error in your main function, it's supposed to be like this:
int main() {
// Your code goes here
}
Also, using namespace std; is considered bad practice since it can lead to conflicts with... |
65,249,125 | 65,249,659 | Passing a bool variable as a parameter to a function expecting a BOOL parameter in Visual Studio 2019 | Take this sample code:
void CChristianLifeMinistryDiscussionsDlg::SetControlStates()
{
if (m_pEntry == nullptr)
return;
bool bClass1 = false, bClass2 = false;
m_pEntry->GetAuxiliaryClasses(bClass1, bClass2);
m_cbBrothersC1.EnableWindow(bClass1 ? TRUE : FALSE);
m_cbBrothersC2.EnableWindow(b... | A BOOL is a type alias for an int. A value of type bool can be implicitly converted to a value of type int. This is called integral promotion, and well defined: The value false becomes 0 and the value true becomes 1.
Passing a value of type bool to a function that expects an argument of type BOOL (i.e. int) is safe and... |
65,249,367 | 65,249,698 | Virtual function input Argument type | I am trying to understand inheritance and polymorphism. When I run this :
#include<iostream>
using namespace std;
class Base
{
int x;
public:
virtual Base* fun() = 0;
int getX() { return x; }
};
// This class inherits from Base and implements fun()
class Derived: public Base
{
public:... | If I needed this in my own code. I'd write the new derived class like this:
// This class inherits from Base and implements fun()
class Derived: public Base
{
public:
int y;
Derived* fun(Base *t) {
Derived *d = new Derived;
Derived* input = dynamic_cast<Derived *>(t);
ASSERT(in... |
65,249,622 | 65,249,827 | What should I do if I have to declare a variable when I don't know the type for it? | I have code like this
if (...) {
const auto & h = std::make_shared<ClassB>();
... // here may be the function that uniquely belongs to ClassB
...
}
else (...) {
const auto & h = std::make_shared<ClassC>();
... // here may be the function that uniquely belongs to ClassC
...
}
h->someFunction();
... |
I can't [use a ternary operator]. The compiler will complain "error: conditional expression is ambiguous;".
You can, you just have to disambiguate the type of the result by casting one of the two expressions to a base class pointer:
auto const h = …
? init_class_b()
: static_cast<std:unique_ptr<BaseClass>>(in... |
65,249,809 | 65,249,912 | Why some examples are using "endl" instead of "\n"? | Why some examples are using "endl" instead of "\n"?
I heard that processing time of "endl" is longer than "\n" because "endl" has some flushing process.
But, there are so many examples using "endl" on the internet.
I wanna know why they're using "endl" which thought to be inefficient.
Sorry for the awkward English........ | Oftentimes, direct usage of std::cout is something not meant for production code, where it's usually preferred to use some kind of logging facility (for writing to a file instead of standard stream etc.). Within such logging library, you would want to take care you only flush when desired, but for some ad hoc, debuggin... |
65,250,075 | 65,250,501 | How to detect combined key input in C++? | Let's say you play a game on the computer, you move your character with arrow keys or WASD, if, let's say, you press and hold the up arrow key/W and left arrow key/A together, if the game allows it, your character will move somewhere in between, even if you press and hold one of the 2 first and the other later, while c... | Even if conio.h function are rather low level, they are not low enough for what you want: you do not want to extract characters from a console buffer (what getch does) but know the state (pressed/released) of some keys.
So you should directly use the WINAPI function GetKeyState. Your program will no longer be MS/DOS co... |
65,250,358 | 65,250,380 | Destructor with copy constructor | I want to use destructor in CPP, but, compiler is giving warning "undefined reference".
class trial{
private:
int number;
public:
trial(){};
trial(int num) {
number=num;
};
~trial();
};
Trial class constructor gets value from main function. Help me by telling me whats incorrect in construct... | It seems you declared the destuctor ~trial();, but you did not define that.
To define the destructor inside the class declaration, use {} instead of ; like ~trial(){}.
To define the destructor outside the class declaration (inside a source file), write like this:
trial::~trial() {
// do what you want
}
|
65,250,875 | 65,251,315 | Convert timestamp string to format "%d-%m-%Y" | I have a unix timestamp as std::string and I want to convert it to a beatiful, date string.
The already asked questions show only converstions with getting the current time (and use "auto", at all places so I am not sure what class is appropriate) but this
is an already existing std::string.
std::string beauty_date; //... | Following should work for you:
#include<iostream>
#include<iomanip>
#include<string>
#include<ctime>
int main() {
std::string ts_str{ "1567555200" };
std::int64_t result = std::stoi(ts_str);
std::time_t tmp = result;
std::tm* t = std::gmtime(&tmp);
std::cout << std::put_time(t, "%d-%m-%Y") << std::... |
65,250,882 | 65,250,983 | Issue with conversion QByteArray to char* | I faced an issue, which I can not explain when converting QByteArray to const char* not inline. Here is an example:
QString string1("ABCDEFGHI");
const char* stringData1 = string1.toUtf8().constData();
qDebug() << "String:" << string1 << "\nbytearray:" << string1.toUtf8()
<< "\ndata immediate:" << string1.toUt... | toUtf8 returns an object whose lifetime ends at the end of the expression.
constData returns a pointer into this temporary object.
Thus, you're using dangling pointers and the behaviour is undefined.
You need to extend the lifetime of the converted string:
QString string1("ABCDEFGHI");
QByteArray utfString = string1.to... |
65,251,098 | 65,263,205 | sed match lines not containing expression with parenthesis | (I have legacy C+ code that compiles with warnings with gcc and fails with errors with clang. The method signatures are either function(int,(char*),(char*)) or function(int,string,string). This method is used a lot throughout the code.)
So in trying to normalize the calls i'm giving it a go with sed.
Assuming this inpu... | Using address range, you could apply substitution on lines not matching two consecutive (char *\*):
sed '/\(char *\*\).*\(char *\*\)/!s/\("[^"]*");\)/(char*)&/' inputfile.cpp
Edit:
To make sure substitutions apply only on function definitions, just change the substitution pattern:
sed '/\(char *\*\).*\(char *\*\)/!s/\... |
65,251,278 | 65,251,587 | Issue while testing a C++ program that measure levels above the sea | I have a uni project the task is We flew from Europe to North America, and we measured the height above the sea level at equal sequences. The first and last measurements were either above a continent or the sea. We measured positive height, where we were above some land, and 0, where we were above the sea
I tried to ma... | To print single 0 instead of 0 0, you should add if statement to check if there were no islands and change what to print according to that.
Also, the initial value of max_valley_count should be -1 instead of 0 so that the (first) island with 0 valleys can appear in the output.
I don't think the issue can be fixed by ch... |
65,251,326 | 65,295,998 | Expressing a Python class as a type in std::variant in C++ using pybind11 | The working example below returns, a vector of type variant consisting of float and int64_t, to Python. The intent (illustrated by the commented lines of code **) is to add further functionality to this by enabling a Decimal (python class), constructed in C++, to be passed back to Python in the same structure.
#include... | you cannot just add the pi variable as is to your std::variant vector because the type of it is py::object. You could add it to your ListTypes so just changing the line
typedef std::variant<float, int64_t, py::object> Listtypes;
but then your list on the Python side would be [987654321, 1.0099999904632568, Decimal(3.14... |
65,251,463 | 65,251,582 | Compiler fails to find right function overload | I have a small base class that defines 3 overloads for a function. Overload A calls overload B which is pure virtual, and its implementation in the derived class calls overload C.
My complete code is as follows:
struct Base {
int func(int a) {return func(a, a+1);}
int func(int a, int b, int c) {return a... | If you declare a function in a derived class with the same name as in the base class, the declaration in the derived class will shadow the functions in the base class.
So in Derived, the only visible func is the (int, int) one.
One easy way to solve this is to pull the base class functions into the overload set with us... |
65,251,744 | 65,251,766 | Failing ternary operator | I have this ternary operator which always returns true:
int waitingTime = 0;
int awayPeriodThreshold = 5;
bool myOperator= 0? (waitingTime < awayPeriodThreshold) : 1;
I am using it in GoogleTest EXPECT_EQ, to compare two booleans.
I have a program which is measuring time, the output is 0 when time does not reach give... | bool myOperator= 0? (waitingTime < awayPeriodThreshold) : 1;
means
bool myOperator= 1;
because 0 is always treated as false.
Ternary operator in C++ means condition ? value when true : value when false.
Therefore, you should write like this:
int myOperator= (waitingTime < awayPeriodThreshold) ? 0 : 1;
Note that you ... |
65,251,840 | 65,261,148 | Can not debug C++ code in Visual Studio 2019 ("Source Not Available"/"Unable to start program: *.exe" issues) | I am using Windows 7 Professional.
I am trying to debug a simple C code in a C++ project in Visual Studio 2019. Here is the code:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
printf("#########################################\n");
// n: day that the query stops
int n = 5;
printf("Day to stop ... | I think my antivirus is deleting the *.exe file. I don't have privileges to stop or uninstall the antivirus so I will not be able to fix the issue in this PC.
|
65,251,900 | 65,252,016 | Relation between automatic deletion of copy constructors and assignements | In our code base we were using this in past:
Foo(const Foo&) = delete;
Foo(Foo&&) = delete;
Foo& operator=(const Foo&) = delete;
Foo& operator=(Foo&&) = delete;
But as we were discussing it later we came to conclusion it is redundant and just:
Foo(const Foo&) = delete;
Foo(Foo&&) = delete;
Should be enoug... | Yes and no.
Copy assignment operator is still generated with user declared copy constructor (or destructor), but this behaviour is deprecated and may be removed in future C++ standard versions.
Any sane compiler should issue a warning if such deprecated behaviour is relied on.
Move assignment operator will not be impli... |
65,251,997 | 65,252,782 | How can binary files and libraries built with different C++ compilers be compatible? | Compilers have a lot of freedom in the code they generate. They have complete freedom in the implementation of the VTable, RTTI, exceptions and much more. Even very basic things like the size of a pointer, the way functions are invoked and name mangling can be chosen arbitrarily, independently from operating system and... | Often times they are incompatible. Here are some of the incompatibilities that may be found:
Different data type sizes
For example, GCC uses 16 bytes for a long double, while VS aliases it to double (8 bytes). For more information, check this.
This can be easily fixed if both sizes are known, since converting between s... |
65,252,141 | 65,252,215 | How come INT_MAX and INT_MIN resolve in C++ without <climits> | How come the following code works even though I am not including <climits> library?
#include <iostream>
using namespace std;
int main()
{
int min = INT_MIN;
int max = INT_MAX;
cout << min << endl;
cout << max << endl;
return 0;
}
Output:
git:(master): g++ main.cpp ... | Implementations of standard library headers may, in turn, include other standard library headers as needed to perform their goals.
However, this is an internal detail that can (and will!) differ between toolchains, and should not be relied upon.
|
65,252,208 | 65,252,249 | Can I declare a placeholder variable in parent class, and declare it in different types in child classes? | Can I somehow declare masiv in the parent class, so the destructor can work properly, or do I need to basically copy-paste the code for each child-class?
class Parent{
public:
int X;
int Y;
// I want to declare a placeholder "masiv" here.
~Parent()
{
for(int i = 0; i < Y; i++)
d... | This can be easily achieved by template
template<typename T>
class Parent{
public:
int X;
int Y;
// I want to declare a placeholder "masiv" here.
T** masiv;
virtual ~Parent() // not an option the virtual destructor
{
for(int i = 0; i < Y; i++)
delete [] masiv[i];
}
delete [] masiv;
}... |
65,252,288 | 65,252,380 | Define field type from template class's field type, instead of adding extra class on the template | I have a generic caching class (the example is simplified from what I have in my code base). The items are stored in a map, and the template type T should have a field id so that I can store it in a map.
struct Car
{
int id;
std::string name;
};
struct Aeroplane
{
std::string id;
int top_speed;
std::string b... | You can provide a default for S like this:
template<class T, class S = decltype(std::declval<T>().id)>
class Cache
{
public:
void Add(T item)
{
cache.emplace(item.id, item);
}
bool Contains(T item)
{
return cache.find(item.id) != cache.end();
}
private:
map<S, T> cache;
};
int main()
{
Ca... |
65,252,573 | 65,285,290 | What is the proper mechanism for separating build and test stages in azure-pipelines? | I have a toy C++ cmake project with the following azure-pipelines.yml (see HelloAzure for sources).
# Starter pipeline
# Start with a minimal pipeline that you can customize to build and deploy your code.
# Add steps that build, run tests, deploy, and more:
# https://aka.ms/yaml
trigger:
- master
variables:
SOU... | For your scenario, you may try the following approach:
1 .In Build stage, adding a task to publish the build output. For example:
steps:
- publish: string # path to a file or folder
artifact: string # artifact name
displayName: string # friendly name to display in the UI
2 .In BuildTests stage, adding a task to d... |
65,253,103 | 65,257,164 | Does MPI_File_write_at() initialize the file with zeros? | Consider the following simple program which writes the rank of all processes whos rank is bigger than zero into a file:
#include <mpi.h>
int main() {
MPI_Init(NULL, NULL);
int world_rank, world_size;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
MPI_Offse... | MPI_File_write_at will write the data into the file as binary data. Then when you run the command hexdump -C myfile that command will display the data, accordingly, with the first 4 bytes being the offset. Those, first bytes are not part of the binary data per si, but rather added by hexdump -C myfile for readability p... |
65,253,124 | 65,253,789 | Lamba depending on template depending value as default value of constructor of that template fails on MSVC | I just upgraded my msvc and got into a trouble.
Here is Minimal Complete Verifiable Example which reproduce issue in my old code:
#include <functional>
#define VERSION 1
template<typename T>
class Foo
{
public:
static constexpr int bar = 512;
#if VERSION == 1
Foo(std::function<int()> f = []() { return Foo<T>... | static function does the job:
static std::function<int()> defaultF() {return []() { return bar;};}
Foo(std::function<int()> f = defaultF())
: m_f{std::move(f)}
{}
Demo
|
65,253,472 | 65,253,643 | Using ifstream to read .txt file with comma | Based on ifstream I am using the following function to read filename.txt file
//reading from text file
static std::vector<double> vec;
double a[18]; //values got read from txt file
int i = 0;
void readDATA()
{
double value;
std::ifstream myFile;
myFile.open("filename.txt", std::ios::app);
if (myFile.is_... | You want to read number followed optionally by colon?
Define class that will handle this "task":
struct Number
{
double value;
operator double() const { return value; }
};
std::istream& operator >>(std::istream& is, Number& number)
{
is >> number.value;
// fail istream on anything other than ',' or wh... |
65,253,579 | 65,255,399 | Makefile trigger rebuild for C/C++ preprocessor directives | Suppose I have a C++ source file which looks like:
int main() {
...
#ifdef flag
// do something
#endif
...
#ifndef flag
// do something different
#endif
...
}
I know that for gcc I can use -D'flag' as a directive to the pre-processor to define flag and thus determine which part of the code above actually gets ... | First of all make must know that the flag has changed. That means you must store the flag "somewhere" which is typically some file. The next you have to tell make which file depends on your flag. It is not necessary to compile all and everything but the dependent files. This means, you have to specify which source depe... |
65,253,592 | 65,255,739 | IDispatch Invoke() returns Type mismatch | I'm unable to successfully invoke create_session member. It's return Type mismatch
// COM class -> member
virtual HRESULT __stdcall create_session(
/*[in]*/ BSTR pbszName,
/*[in]*/ long i32Value ) = 0;
Trying to invoke create_session method as follow:
// test.cpp
HRESULT create_session( IDispatch *disp... | The IDispatch::Invoke() method must be called with parameters in reverse order, as stated in the official documentation:
Implementing IDispatch / Passing Parameters:
The arguments are passed in the array rgvarg[ ], with the number of
arguments passed in cArgs. The arguments in the array should be placed
from last to f... |
65,253,689 | 65,255,507 | How do you add a timestamp to an SD card without using a RTC? | I'm using an SD card with an Arduino Mega. Each time I write to the card, which is about once every 2 or 3 seconds, I want there to be a time stamp next to the text, the same way it works on the Serial Monitor.
I was wondering if there's any way to do this programmatically instead of getting an RTC.
| There are software RTC libraries out there, like swRTC, and Arduino-RTC has a software-only mode.
These libraries rely on the accuracy of the Arduino's clock, so they won't be all that accurate and will need adjustment every so often. Also, you will need to set them every time you reset your Arduino.
Setting and adjust... |
65,254,040 | 65,254,318 | DirectX9 CreateDevice fails in C, but succeds in C++ | I making a d3d9 app in C, but when trying to create a device object it fails in C, but its counterpart in C++ just works and returns S_OK.
C:
isOk = pD3D->lpVtbl->CreateDevice(pD3D, D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, d3dpParams.hDeviceWindow, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpParams, &lpDevice);
C++:
isOk = p... | The ={} initialization for a plain C struct only zeroes the memory.
Microsoft's own example at https://learn.microsoft.com/en-us/windows/win32/direct3d9/creating-a-device recommends ZeroMemory for this:
D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory( &d3dpp, sizeof(d3dpp) );
|
65,254,571 | 65,254,600 | Segmentation Fault in C++ while using string vectors | My code is for an online coding practice site, I have been doing many of the challenges but I cannot seem to get around the segmentation fault error on this one.
The aim of the code is to find the longest length strings in a string vector (up to 10 strings long) and then to return a string vector containing just those ... | longestStrings.clear();
longestArrayCounter = 0;
longestStrings[longestArrayCounter++] = inputArray[i];
is bad because you are doing assignment to non-existent element.
Instead of the two
longestStrings[longestArrayCounter++] = inputArray[i];
you should do
longestStrings.push_back(inputArray[i]);... |
65,254,622 | 65,254,679 | In-place new + reinterpret_cast | The code below compiles, but I am not 100% sure that it conforms to the standard:
#include <memory>
class A
{
public:
int x;
};
int main()
{
uint8_t m_storage[sizeof(A)];
new (m_storage) A();
auto deleter = [](A * p) { p->~A(); };
std::unique_ptr<A, decltype(deleter)> p(reinterpret_... | Yes it is correct reinterpret cast.
Albeit not correctly aligned storage. And potentially wrong placement new (should cast parameter to void*).
|
65,254,752 | 65,254,931 | Why can't I assign value of pointer to const int to a pointer of int? | [Note: I saw another question asking about the same section in the same book, but for different reasons]Reading through the C++ primer book and was going through the section "top-level consts". Here it writes that:
The distinction between top-level and low-level matters when we copy an object.
When we copy an object,... | First consider this example:
void foo(const int* p) {
*x = 1; // Error ! x is pointer to const
}
int x = 42;
foo(&x);
x is not const. Nevertheless, inside foo you are not allowed to modify its value via the const int* p, because it is a pointer to a const int. Having a pointer to const int does not imply that t... |
65,254,888 | 65,255,143 | Why can a static library be linked despite undefined references (missing `extern "C"`)? | I don't have a problem that needs solving but was very puzzled by the following:
I'm using CMake (which uses gcc internally). Not sure if this is important.
Suppose I have a project consisting of a C++ static library LibCpp and a demo C++ executable DemoCpp, which links to and uses LibCpp. The library LibCpp is compile... |
I would have expected it to fail already at linking the static library.
The static "library" is not linked. Its constituent object files are archived - bundled together in an object archive for convenience's sake. That's what the static "library" is. You can think of it as a bunch of object files packed in a "zip" fi... |
65,255,047 | 65,255,162 | C++ - Passing 2D array to function | I am trying to pass a 2D array to a function but I am failing to do so. There is no problem with passing 1D array. How can I do this?
#include <iostream>
using namespace std;
void DisplayBoard(int matrix[],int n) // Prints out the given array.
{
for (int j = 0; j < n; j++)
... | i think you want to input index number (n) from user and then input array object from user too
i complete your code like this :
#include <iostream>
using namespace std;
void DisplayBoard(int matrix[],int n) // Prints out the given array.
{
cout<<endl ;
for (int j = 0; j < n; j++)
{
cout <<... |
65,255,174 | 65,255,284 | C++ operator new returns unexpected value | I am working with conversion operators and I an error just popped out of nowhere. C class is derived from B and has no relation with class A, however, debugger shows that when doing C* val1 = new C val1 is showed as C* {A<B>}. It also produces an error because that A in the C* pointer has a size of an unreasonable siz... | for (unsigned int i = 0; i < size; i++)
{
return_value[i] = dynamic_cast<return_type*>(this->value[i]);
}
You are invoking undefined behaviour by accessing return_value[i] on an empty vector.
|
65,255,182 | 65,255,314 | Sum of specific tuple elements | I am trying to compute the sum of specific elements of a tuple, but cannot get it to compile.
Here is what the function I want to write would look like:
template <int ...ids>
float sum(std::tuple<int, int, std::string, float> things)
{
return "<sum of elements of ids>";
}
And I would like to call it, like this:
st... |
I couldn't get it to work using folding. :/ Is this even possible? If yes, how so?
What about as follows ?
template <int ...ids>
float sum (std::tuple<int, int, std::string, float> things)
{
return ( 0.0f + ... + std::get<ids>(things) );
}
But I suggest (1) to be more generic and (2) to use std::size_t for index... |
65,255,249 | 65,255,329 | Failed to include GLUT C++ | I'm using the MinGW compiler, my OS is Windows, GLUT is in my Documents folder and the file (Graphics.cpp) is also in my Documents folder, here it is by the way:
#include <GL/glut.h>
void drawSquare(double x1, double y1, double sidelength)
{
double halfside = sidelength / 2;
glColor3d(0,0,0);
glBegin(GL_PO... | It appears that the compiler can not find the header. In gcc use the -I flag to include the absolute path to the directory GL/glut.h
https://www.rapidtables.com/code/linux/gcc/gcc-i.html
|
65,255,313 | 65,255,457 | How can I replace the input character with the "*" character? | How can I replace the input character with the "*" character? Everything should happen at the time of entering (like entering a password when registering on the site).
Thanks for the answer!!!
| An easiest way, i think like this:
#include <iostream>
#include <string>
#include <conio.h>
int main()
{
std::string str;
char ch;
std::cout << "enter the text: ";
while((ch = _getch()) != 13) //enter type
{
str+= ch;
std::cout << '*';
}
}
|
65,255,882 | 65,256,952 | Can not run libpq examples in Visual Studio 2019 | I am new to C++.
I downloaded https://ftp.postgresql.org/pub/source/v13.1/postgresql-13.1.tar.gz from https://www.postgresql.org/ftp/source/ and unpacked it.
I created a new project in VS Community 2019. Added the example postgresql-13.1\src\test\examples\testlibpq3.c to the project.
Added my postgresql-13.1\src\includ... | You need to configure, build and install PostgreSQL to have all the header files in the correct place.
It would be simpler to install the PostgreSQL binaries, they include all the header files necessary to build client code.
|
65,255,982 | 65,279,201 | Cocos2d-x Display resolution problem in in iPad Air(4th Gen) and iPadPro 11 inch | I used resource of 2048x1536 for all iPad device. Resolution is not perfect in iPad Air(4th Gen) and iPadPro 11 inch.
In all other iPad display correct.
Tested in Cocos2dx v4.0
Here is my code:
if (MyGameBridge::sharedGameBridge()->IsIpad())
{
auto designSize = Size(1024, 768);
... | You are unsing ResolutionPolicy::NO_BORDER with that policy cropping can occur.
NO_BORDER: The entire application fills the specified area, without distortion but possibly with some cropping, while maintaining the original aspect ratio of the application.
When you use SHOW_ALL: The entire application is visible in the ... |
65,256,228 | 65,256,526 | Can free() cause a memory leak? | Calling delete calls the destructor of a class, but calling free() does not.
Can that cause a memory leak? If not, why?
#include <iostream>
#include <cstdlib>
using namespace std;
class x{
public:
int a;
~x(){cout<<"destroying"<<endl;}
};
int main() {
x *y = (x*)malloc(sizeof(x));
free(y);
x *z = new x;
d... |
Can that cause a memory leak?
In your particular example, no. The x object is merely being allocated by malloc(). free() will correctly deallocate the memory that malloc() allocated. But the object will not be destructed, which is fine in this example because it was not constructed to begin with, so there is nothi... |
65,256,289 | 65,256,371 | Why isn't the move constructor being called? | I am new to C++ and am trying to understand rvalue references and move semantics.
I have written a simple class, Class, which includes a method, fun, which creates an instance of the class in its body and returns it. The class has a copy constructor, a move constructor, a (copy) assignment operator, and a (move) assign... |
Why doesn't Class obj2(obj1.fun()); call the move constructor
Because of Copy Elison. The compiler sees that fun() returns a temporary object, and that temporary will only be used to initialize obj2, so the compiler optimizes the creation of obj2 by eliminating the temporary object altogether and allowing obj2 to be... |
65,256,486 | 65,256,579 | C++ dynamic_cast a template class to another template | I am working with template class A<widget_type> and I want to know if it is possible to dynamic_cast<A<another_type>*>(A<widget_type>*).
Question: in the following code, A<B>* target2 = dynamic_cast<A<B>*>(&source); returns a null pointer. Is it possible to cast a template class into the same class but with another tem... | dynamic_cast will only succeed if there is some kind of inheritance relation between where you are coming from and where you are going to.
If you simply want to treat a pointer of one type as a pointer to a different type (which in general is true of different specializations of the same template) then dynamic_cast wil... |
65,256,789 | 65,256,876 | Why does code in constructor not run when called from another file? | main.cpp
#include <iostream>
#include "shreeman.h"
using namespace std;
int main(){
Shreeman object;
}
shreeman.h
#ifndef SHREEMAN_H
#define SHREEMAN_H
class Shreeman
{
public:
shreeman();
};
#endif // SHREEMAN_H
shreeman.cpp
#include <iostream>
#include "shreem... | In the Shreeman class, shreeman() (lowercase s) is not a valid constructor, it is just a member method. It needs to be renamed to Shreeman() (uppercase S) to be a construcor (the compiler should have warned you about that). C++ is case-sensitive, and a constructor name needs to match the class name exactly, case and ... |
65,256,814 | 65,257,093 | Selecting cross compiler for Raspberry Pi | Looking for cross compiler that could help me build application for Raspberry Pi on my Ubuntu 20.04 machine. I found official tools on Github and I suppose that folder arm-bcm2708 contains cross compilers:
arm-bcm2708hardfp-linux-gnueabi
arm-bcm2708-linux-gnueabi
arm-linux-gnueabihf -> arm-rpi-4.9.3-linux-gnueabihf
arm... | You can use one of the toolchains provided by ARM for your RPI3/4.
If you are running a 32 bit Linux on your RPI3/4, use one of the arm-none-linux-gnueabihf toolchains, if use are running a 64 bit Linux on your RPI3/4, use one of the aarch64-none-linux-gnu one.
Both 10.2 and 9.2 versions of the two toolchains are worki... |
65,256,997 | 65,257,335 | How to write an insertion operator function template? | I'm trying to write a single function template instead of a bunch of similar overloads for the insertion operator. The redundant overloaded versions work, but when I try to unite them in a single function template, the compiler complains of ambiguity. For example:
#include <iostream>
#include <list>
class fooBar
{
pu... | You've inadvertedly added a possible overload for const char* by making this:
template<typename T>
std::ostream& operator<<(std::ostream& osOut, T& tContainer)
If you narrow it down a bit with SFINAE, it should work.
This overload will only work for types with a getList() member function for example:
template<typename... |
65,257,926 | 65,258,269 | Problem with false case in conditional_t being compiled and evaluated | I'm having a hard time understanding how to stop code from being evaluated with std::conditional_t in the false branch.
#include <type_traits>
using namespace std;
namespace {
template <typename T>
using BaseDifferenceType = decltype (T{} - T{});
}
int main ()
{
using T = int;
static_assert(! is_enum... | A possible alternative pass through a creation of a custom type traits as follows
template <template <typename...> class Cont, typename ... Ts>
struct LazyType
{ using type = Cont<Ts...>; };
and rewrite your std::conditional as follows
using aaa = std::conditional_t<
std::is_enum_v<T>,
L... |
65,258,485 | 65,259,350 | Variadic template class implicitly converting | I have a class and need to validate that it's function calls are being called w/ the right parameters. The function signature is always the same (sans 1 argument type). So, naturally I went for a templated approach. So generally the validation policy would have a template parameter per data type it could handle:
usin... | It's complicated...
First of all: you have a recursive template class, BasicValidationPolicy, where you define two methods and you want that all methods, for all recursion steps of the class, are available.
Unfortunately, the definition of the methods in the derived classes hide the method in base classes.
To un-hide t... |
65,258,571 | 65,258,760 | can anyone tell me why the fibonacci function does not work? | I want to have it add every once a parameter it has not yet found to the map, but when I try numbers higher than 47 it gives me negative numbers, clearly impossible
#include <map>
using namespace std;
//memoization
map<unsigned int, unsigned int> memo;
map<unsigned int, unsigned int>::iterator it;
int fibonacci(int n... | First, let's take care of the negative numbers. Comments above explained that you have an overflow of the 32-bit int.
However, you could stretch your code a bit further would you not convert an unsigned int you calculate to a signed one you return from that function.
The solution is to use larger types, like unsigned l... |
65,258,668 | 65,258,911 | std::shared_ptr which is null but not empty | Compare with: std::shared_ptr which is empty but not null
The std::shared_ptr<T> aliasing constructor lets us play interesting games. The above SO post discusses when the first argument is std::shared_ptr<void>{nullptr}. I'm interested in the reverse. Is this guaranteed to keep the pointed-to object alive even though t... | Yes, the "null but not empty" shared_ptr will keep the object alive because it shares ownership with the shared_ptr it was constructed from. All shared_ptrs that share ownership with each other contribute to an atomic reference count stored in the control block, and only when this reference count hits zero is the owned... |
65,258,786 | 65,259,339 | std::make_tuple with the input of a manipulated std::tuple unsing concepts in c++20 | Kindly considere the following godbolted code written for c++20:
#include<iostream>
#include<tuple>
template <typename T, std::size_t ...I, typename F>
void tuple_foreach_impl(T&& tuple, std::index_sequence<I...>, F&& func)
{
using dummy_array = int[];
dummy_array{(void(func(std::get<I>(tuple))), 0)..., 0};
}
... | You have a constness issue: your tuple is const, so you pass const int& and const int is not a int. removing const solve your issue:
template <typename... Ts, std::size_t... Is>
auto ConvertTupleImp(std::tuple<Ts...>& t, std::index_sequence<Is...>)
{
return std::make_tuple(ToPtrIfInt(std::get<Is>(t))...);
}
Demo
A... |
65,259,030 | 65,259,093 | Why `std` prefix is not required to call the `lower_bound` function? | Just for curiosity, I found a rather strange exception, that you can use a lower_bound function without telling in which namespace it is located. The following code:
// main.cpp
#include <algorithm>
#include <cstdio>
#include <vector>
// The std prefix is required for the vector, but not for the lower_bound, why?
usin... | lower_bound() is indeed in the std namespace, as expected. The reason you can call it without specifying the std:: prefix is because of Argument-Dependent Lookup. You are passing std::vector iterators to lower_bound(), and those iterator types happen to reside in the std namespace in your compiler's implementation of... |
65,259,103 | 65,259,203 | Read from a file after have written to it with fstream - always empty | std::fstream file("filename", std::fstream::in | std::fstream::out | std::fstream::trunc);
if (file)
{
file << "Some text" << std::flush;
std::string buffer;
//file >> buffer;
std::getline(file, buffer);
std::cout << buffer;
}
I need to write to a file and read from ... | Use seekg(0) to set the position to start. When you wrote on the file it move the position to the end and for reading it you have to move to start.
std::fstream file("filename", std::fstream::in | std::fstream::out | std::fstream::trunc);
if (file)
{
file << "Some text" << std::flush;
std::string buffer;
//... |
65,259,338 | 65,323,336 | 'from' parameter not supported c++ libcurl mailgun api Error 400 | I'm trying to send a email with the mailgun api using c++ libcurl. The api is returning the error "message": "'from' parameter is not a valid address. please check documentation".
code
CURL* curl;
CURLcode res;
std::string readBuffer;
std::string user = "api:" + (std::string)"MY_API_KEY";
std::strin... | you do not need to have quotes around the from-address and you must encode the lt/gt symbols:
"from='Bob Marley <bob@host.com>'&to='MY_EMAIL@gmail.com'&subject='Hello'&text='hi'";
you should use
"from=Bob Marley %3Cbob@host.com%3E&to='MY_EMAIL@gmail.com'&subject='Hello'&text='hi'";
|
65,259,421 | 65,261,638 | Print all permutations of selected length characters with repetition and do not start over after closing the program in CPP | #include <iostream>
#include <string>
using namespace std;
void enumerate(const string& s, int n, string t = "")
{
if (n == 0)
cout << t << endl;
else
{
for (char c : s)
enumerate(s, n - 1, t + c);
}
}
int main()
{
enumerate("abc", 5);
}
Hi, guys, I wanna make all of ... | Handling string permutations
C++ has a handy standard library algorithm std::next_permutation which you can use to handle string permutations for you.
One solution
Below is a brute force approach in which every possible permutation of the larger "parent" string is iterated through, and the first n character substring t... |
65,259,525 | 65,259,526 | What is an istream_view and when do I use one? | Apparently, C++20 has a new std::istream-related construct: std::istream_view. The cppreference page on it is a stub right now†. So, what is a "view of an istream" and what can I use it for?
† - Ok, technically it redirects to a page about std::basic_istream_view and that one's a stub.
| An std::istream_view<T> is a range; and more specifically, a range formed as a view. This addition to the standard library is akin to what you might find under std::ranges::views - except that it's not a view of an arbitrary range, but of an std::istream.
So what "viewing" is applied to an std::istream? Recall an istre... |
65,260,005 | 65,260,420 | C/C++ declare 2D/3D array with ascii art | Long time ago (10+ years) I saw a syntax which let you declare array with "ascii art".
Something like this:
//Declares 5x3 2d array
int myArray[] = #####
# #
#####
It was even possible to draw a cuboid for 3d arrrays.
My primary language for a very long time is a C++, so I'm sure it w... | Sounds very much like Eelis' Multi-Dimensional Analog Literals (also linked here). Short example:
#include <cassert>
#include "analogliterals.hpp"
using namespace analog_literals::symbols;
int main()
{
auto l = I---------I;
auto r = o---------o
| !
! !
o... |
65,260,044 | 65,261,349 | Get class pointer name from within its method? | Disclaimer: I'm fairly new to programming and my terminology may be way off. When I say "class pointer name", I mean the "A" in "myClass A" and in "A.Fill(...)".
I'm not sure how to formulate my question to make it as clear as possible, but let me try:
class myClass{
public:
// stuff
Fill(string msg)
{
... | You don’t want variable names, and you don’t want to be passing them in each time you call a method of the object.
You want object names. You need to give the A object a name, and then this name can be used by all of its methods.
Then, if you want convenience, instead of instantiating it as ClassA A("A");, you can have... |
65,260,167 | 65,260,198 | Struct, is fundamental template,C++ | I want to check whether the template parameter of the struct is fundamental or not.
So I created a struct
template<typename T, typename = std::enable_if<std::is_fundamental_v<T>>>
struct Something {
};
And an empty struct
struct AStruct{
};
Using is_fundamental I expected that my struct will be "enabled" only and on... | It should be std::enable_if_t<std::is_fundamental_v<T>> (_t added) or typename std::enable_if<std::is_fundamental_v<T>>::type.
I would suggest static_assert instead:
avoid the hijack with Something<AStruct, void> (can also be fixed with preferred std::enable_if_t<cond, int> = 0)
Your class would not be SFINAE friendly... |
65,260,497 | 65,260,533 | variadic template, Range, C++ | Consider I have a struct.
template<typename T>
struct Range{
T min, max;
Range() = default;
Range(T min = std::numeric_limits<T>::min(),T max = std::numeric_limits::max()) :
min(min), max(max){
}
};
So this struct holds a range for any type T, and if not given i... | You can create trait is_range:
template <typename> struct is_range : std::false_type{};
template<typename T, T MIN, T MAX>
struct is_range<Range<T, MIN, MAX> : std::true_type{};
and then fold expression (C++17)
template <typename ...Ts>
struct Something{
static_assert((is_range<Ts>::value && ...));
static std... |
65,260,758 | 65,261,431 | Read/write Arduino ports in llvm |
Just to avoid ab-interpretation, my question in short:
I want to read and write to Arduino port D via llvm C++ api.
write
DDRD = 0xFF;
PORTD = 12;
read:
DDRD = 0x00;
int x = PORTD;
Read more:
I like to know how to read/write Arduino ports via llvm. I am not after a specific AVR micro-controller just need the genera... |
llvm C++ api
Nope. Those words don’t mean what you seem to imply. The “llvm C++ API” is not available from inside a program that you compile for, say, an Arduino. See below the line at the end of this answer for details. If you actually had LLVM C++ API in mind, you wouldn’t be asking this question since register acc... |
65,260,902 | 65,261,372 | When the object of std::function is destroyed? | When the object of std::function is destroyed?
Why the pointer to the object of std::function is still valid when the variable fn1 is out of the scope(you see the code snippet works well, http://cpp.sh/6nnd4)?
// function example
#include <iostream> // std::cout
#include <functional> // std::function, std::negate... |
Why the pointer to the object of std::function is still valid when the variable fn1 is out of the scope?
Let me present a simpler example, using ints. But if you are brave, you can try to read the assembler for the std::function version.
int main () {
int a = 0;
int *c = nullptr;
{
int b = 1;
... |
65,260,953 | 65,261,520 | Is `boost::function<int(const char*)> f` a pointer or an object? | As per the article(https://theboostcpplibraries.com/boost.function), which says that:
boost::function makes it possible to define a pointer to a function
with a specific signature. boost::function<int(const char*)> f defines a pointer f that can
point to functions that expect a parameter of type const char* and
return... |
@sehe Sorry, I forgot. The link is added to the post. theboostcpplibraries.com/boost.function – John 37 mins ago
Thanks for the added link.
Though I have his book in print and value his contributions to Boost introductory materials, I stand by my assessment that the wording here is unnecessarily confusing, and even m... |
65,261,393 | 65,261,414 | C++ When to delete object initialized with new if needed for return? | I'm confused as to when I should be deallocating the following object from memory:
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode* addTwoNums(ListNode* l1, ListNode* l2){
ListNode *head = new ListNode(0);
...
return head->next;
}
Since I'm retu... | Every function accepting or returning a pointer needs to have a contract regarding who is responsible for owning the resource pointed to by the pointer. When you use raw pointers, such as you did, this contract is implicit, which means you'll need to figure out who frees the object (it seems obvious that the caller mu... |
65,261,599 | 65,262,540 | Google protocol buffers. 'make install' does not generate so files when protobuf building to cross-arm | When I build a protobuff for arm and then install it, I don't see *.so files in the lib/ directory, only *.a and *.la. If I build it for x86, then everything is fine.
The sequence of commands is as follows:
sudo ./configure --host=amd64 --build=arm-linux-gnueabihf --target=arm-linux-gnueabihf --enable-shared --prefix=/... | You are mixing up --host, --build, and --target. The --host option designates the machine type on which the artifacts you are building will run. The --build option designates the machine type on which you are performing the build, and you do not ordinarily need to specify it, because the build system can guess. In fa... |
65,261,797 | 65,262,014 | Varadic template to tuple is reversed | I have the following code which reads values/parameters from a pointer and calls a function:
#include <iostream>
#include <functional>
#include <string>
#include <tuple>
template<typename T>
T Read(void*& ptr)
{
T result = *static_cast<T*>(ptr);
ptr = static_cast<T*>(ptr) + 1;
return result;
}
template<ty... | The arguments in a function call expression are indeterminately sequenced ([expr.call]/8). That is, in the call to std::make_tuple(Read<int>(arguments), Read<int>(arguments), Read<int>(arguments)) in your code, the Read<int>(arguments) calls happen in whatever order the implementation wants to do them, not in the order... |
65,261,874 | 65,262,231 | Do one time (once) execution in forever loop or void loop? | I want make one time or once execution syntax inside forever loop (void loop) for any program languages.
What i found the solution is with make new variable boolean "executed" and set to true after executed.
It's okay, but what if i want do once execution to other syntax? Should i make new variable boolean again? It wi... | Several ways to approach this
Following is a very common way of how such an operation is usual made.
As you already suggested, with an global boolean:
bool once = true; // global variable
void loop() {
if (once) { // being called only once
lcd.print("OK");
once = false;
}
}
Do something only once after a s... |
65,261,928 | 65,261,950 | C++ syntax question - Why can't I use comma to separate variable definition of different types | int main() {
std::cout << 1, std::cout << 2;
return 0;
}
The above snippet is syntactically correct, as commas can be used to separate statements. However,
int main() {
int a, std::string b;
return 0;
}
This returns with an error
Expected initializer before 'b'
Why is this? Is there some circumstances I can... | Commas never separate statements. Your first example is a single statement, consisting of an expression containing the comma operator. It happens to do the same thing as if you had written two statements std::cout << 1; std::cout << 2; but they're not syntactically equivalent.
Likewise, your second example is (trying... |
65,262,466 | 65,262,534 | Question about operator += overloading in c++ | After I overloading operator +=:
Object1& operator+=(Object2* r)
{
ObjVector.push_back(r);
return *this;
};
and call it in another class's member function, it gives error like this:
error:invalid operands of type 'object*' and 'object*' to binary 'operator+'
Obj1 += Obj2;
error:in evaluation of 'opera... | Because your parameter for the + operator is a pointer, this will probably make the compiler happy:
Obj1 += &Obj2;
Or if they are pointers, then this;
*Obj1 += Obj2;
I generally discourage operator overloading on math operators unless there's actual math involved (e.g. a Complex number class). In your case, you are ... |
65,262,647 | 65,262,691 | Unrecognised database format with ACCESS and ADO | ALL,
I have a MS Access accdb file, to which I try to connect:
std::wstring dbFile = pimpl->m_connectString.substr( pimpl->m_connectString.find( L"DBQ=") + 4 );
dbFile = dbFile.substr( 0, dbFile.find( L";" ) );
if( FAILED( CoInitialize( NULL ) ) )
{
errorMsg.push_back( L"Failed to initialize DAO... | You are probably using the wrong provider. For accdb files use the following:
Provider=Microsoft.ACE.OLEDB.12.0;Data
Sourcee=C:\myFolder\myAccessFile.accdb;Persist
Security Info=False;
You may have to install the required ACE drivers freely available from the M$ site.
|
65,262,899 | 65,263,609 | What is the purpose of pointer rebind? | I trying to implement std::list (MSVC). And one thing I cannot understand:
template <class _Value_type, class _Voidptr> // voidptr? For what?
struct _List_node { // list node
using value_type = _Value_type;
using _Nodeptr = _Rebind_pointer_t<_Voidptr, _List_node>; // what is the purpose of such rebind?
..... | The answer to this question comes from allocators, too. Let's take a look at how _Rebind_pointer_t is defined:
template <class _Ptr, class _Ty>
using _Rebind_pointer_t = typename pointer_traits<_Ptr>::template rebind<_Ty>;
That is, we have
template <class _Value_type, class _Voidptr>
struct _List_node {
using _Nod... |
65,262,913 | 65,263,271 | How to define and initialize a variable only once in a recursive function? | I am trying to solve the 0/1 Knapsack problem on GeeksforGeeks and it requires me to complete the funtion
int knapSack(int W, int wt[], int val[], int n)
Now I want to do this with recursion + memoization. But to that I need to define and initialise a DP matrix for every test case. It looks like this.
int dp[1001][10... | Avoid global variable.
Split your method:
int knapSackRec(int (&dp)[1001][1001], int W, int wt[], int val[], int n)
{
// ...
}
int knapSack(int W, int wt[], int val[], int n)
{
int dp[1001][1001];
memset(dp, -1, sizeof (dp));
return knapSackRec(dp, W, wt, val, n);
}
|
65,263,005 | 65,263,272 | Sorting and keeping track of indexes in struct | Let's say we have n number of houses. This is a house:
struct Casa {
int id;
int membri;
};
I am reading the size of the struct and each struct's membri from a txt file. The first value is the size of the struct (n).
5
2
8
6
10
4
I increment the ID when reading from file:
void citire(Casa house[], int n, std... | There are one of a number of sorts you can choose from. The simple sorts like bubble-sort being the worst efficient, and then various selection sorts, until you get to the longer partitioning sort where efficiency finally improves.
Here a simple selection-sort example sorting your example struct ascending will do. The ... |
65,263,083 | 65,263,137 | call to function is ambiguous, but why? | #include <iostream>
using namespace std;
void x(int a,int b){
cout<<"int int"<<endl;
}
void x(char a,char b){
cout<<"char char"<<endl;
}
int main() {
int a =2;char c ='a';
x(a,c);
return 0;
}
call to 'x' is ambiguous in apple clang compiler, why?
for x(int,int), first argument is a direct match and second... | Looking at how cppreference describes the overload resolution process:
Best viable function
For each pair of viable function F1 and F2, the implicit conversion sequences from the i-th argument to i-th parameter are ranked to determine which one is better (except the first argument, the implicit object argument for sta... |
65,263,300 | 65,263,590 | What is the parent class of SoftwareSerial and Serial | I wanted to create a function to pass a serial port by reference for reading content. and I use SoftwareSerial and Serial in combination, meaning I want to pass both Objects to the function I want to create. What class do they both inherit from? what class should I declare my source object?
void getResponse(Serial &sou... | the common base classes for Arduino Serial and SoftwareSerial are Stream and Print
|
65,263,354 | 65,263,448 | Not being able to store a variant in a pointer in c++ | My groupmate and I are doing a school assignment and we are having some trouble trying to save a value.
I am 100% aware that some of the things done in the code is not the normal way of doing, and that there are better ways, but part of the assignment is to use the concepts taught in class.
Problem:
I have a Train clas... | You might use std::monostate to signal empty:
class Platform
{
public:
using Trains = std::variant<std::monostate,
TrainWrapper<Train<Arriva>>,
TrainWrapper<Train<IC3>>,
TrainWrapper<Train<IC4>>>;
template<typename ... |
65,263,700 | 65,263,751 | cmake does not generate makelists | //CmakeLists.txt
cmake_minimum_required (VERSION 2.6)
project (HelloWorld)
add_executable (HelloWorld HelloWorld.cpp)
//HelloWorld.cpp
#include <iostream>
using namespace std;
int main(){
cout<<"hw"<<endl;
return 0;
}
I execute cmake. No makefile is generated.
The file shown in the figure below is... | CMake has different generators, you can generate builds in different ways such as through 'make' or 'ninja' or through Visual Studio. You have most likely generated through Visual Studio and hence you have the Visual studio project HelloWorld.sln
See https://cmake.org/cmake/help/latest/manual/cmake-generators.7.html
|
65,263,717 | 65,263,879 | "expression must have class type" error in C++ | I got "expression must have class type" error while defining a method in a C++ struct. I do not know why.
The code:
struct qqueue {
int ar[20000];
int rear = 0;
void add_end(int c) {
ar[rear++] = c;
}
void add_front( int c) {
if (rear < ar.sz - 1) { // expre... | ar.sz
does not work. ar is of type int[], which doesn't have any members. since you know the size at compile time, you may want to write 20000.
Since you are using cpp, I'd suggest using std::vector or std::array
|
65,264,092 | 65,349,062 | How to fix "swig/python detected a memory leak of type 'HWND *', no destructor found"? | Consider this mcve:
mcve.h
#pragma once
#include <windows.h>
class Windows {
public:
static HWND GetActiveWindow();
static HWND GetForegroundWindow();
};
mcve.cpp
#include "mcve.h"
HWND Windows::GetActiveWindow() {
return ::GetActiveWindow();
}
HWND Windows::GetForegroundWindow() {
return ::GetFor... | SWIG wasn't provided a definition of HWND and treats it as an opaque class. Note that %include "mcve.h" does NOT recurse into #include <windows.h> and only processes code directly in mcve.h, so SWIG has no definition at all.
There are a couple of solutions:
Give SWIG a definition that it understands. SWIG has a defa... |
65,264,532 | 65,266,840 | Invoke a method of templated derived class method from non-template base class pointer | I'm trying to implement a Property system in my project similar to Property system in Qt. We just started with some ideas and are in prototyping stage.
Basically, what I understood from Qt is, client should be able to pass the get function, set function and property type through some macro in the .h file. So I tried to... | Your AbstractFunc isn't abstract at all: its Invoke isn't virtual. So even though GetterFunction also has a method named Invoke, that method doesn't actually override AbstractFunc::Invoke; it just hides it. When you try to call Invoke through the AbstractFunc*, it calls AbstractFunc::Invoke, which goes into infinite re... |
65,265,057 | 65,266,803 | node addon with cluster get process id returns same id for all forked process's | Edit
GetCurrentProcessId() and getpid() return different values... but boost does not.
Original question
I am writing a node addon to add a local native cache to be used with an express server when running as a cluster, to have a common cache. I am using boost's message_queue for IPC between the process's, and need t... | Like I said, that's an undocumented implementation detail.
However, if this is really your code:
std::cout << bip::ipcdetail::get_current_process_id << std::endl;
Then the obvious fix is to call the function instead of printing its address:
std::cout << bip::ipcdetail::get_current_process_id() << std::endl;
Note the ... |
65,265,146 | 65,265,174 | C++ Creating 2D array with nonconstant size, | I have been using Codeblocks and my code was fine. When I switched to Visual Studio I got an error that says : "expression must have constant value"
int board[n][m];
| In contrast to in C there is no variable length array (VLA) in C++ standard, i.e. it is implementation/evnvironemt depending whether you can use them with a compiler or not.
You got lucky in CodeBlocks and unlucky in Visual Studio.
Both will allow you to use containers in C++ (e.g. std::vector), which is the recommende... |
65,265,451 | 65,265,706 | Can multimaps be implemented with structures as key? If yes then how? | For example two structures like point and square as given below if it is possible to do so how may i insert new elements into it?
typedef struct _point{
int x;
int y;
}Point;
typedef struct _square{
float belowLeftX;
float belowLeftY;
}Square;
multimap <Square, Point > dictionary;
| Yes, a structure as key is not different compared to a class as key. You have two options to get your code working.
Option 1:
Supply ordering to the Square type.
typedef struct _square {
float belowLeftX;
float belowLeftY;
bool operator<(struct _square const& rhs) const
{
if (belowLeftX < rhs.be... |
65,265,522 | 65,265,791 | Makefile ignores specific lines | I'm making a simple C++ project that uses two different programs (One sends information and the other receives it, if you're curious). I made a makefile to compile both programs and generate two executable files in one go, but when I execute my make instruction I get the following error:
makefile:51: atención: se anula... | There is no rule for NetcpReceive.o, only NetcpSend.o and others.
Since all your object build recipes look alike you could/should declare a pattern rule:
$(OBJECTS_DIR)/%.o: $(SRC_DIR)/%.cc
$(CC) -c -o $@ $< $(CFLAGS)
Your recipe for the executables can be improved too. Declare the recipe and set prerequisites sep... |
65,265,850 | 65,265,924 | "Variable cannot be used as a constant" c++ array | I am struggling with C++. I learned Java before and i think it is much easier, tbh. Currently, I am trying to code a counting sort algorithm with c++. I want to get the maximum of my array to declare my helping array with the size = maximum +1; I tried several ways but nothing works. It always shows "variable cannot be... | You can not use variables for compile time array size simply because compiler has no way of knowing what the value returned by your getMax function will be ...
You need to use dynamic arrays in cases like this...
void countingSort(int *arr, int size)
{
int max = getMax(arr, size);
int *hilfsArr=new int[max ... |
65,266,165 | 65,266,357 | Edit data structure code to take in two vectors | I have this algorithm that I want to edit so it takes in two vectors. The two vectors are created from data in a csv file and I want to compare the data in the two vectors. The algorithm below only takes in one vector containing both values that are to be compared but I want to change it so that it can take in two sepa... | The algorithm does work with a structure that has both x and y. The most simple would be to copy your seperate vectors in such structure:
std::vector<Data> transform(const std::vector<double>& x, const std::vector<double>& y) {
std::vector<Data> result(x.size());
for (int i=0; i < x.size(); ++i) {
r... |
65,266,186 | 65,266,239 | Why doesn't this friend function allow brace-init-list but the static one does? | Basically this code won't compile
struct M
{
static void staticF(M m) {}
friend void friendF(M m) {}
};
int main()
{
M::staticF({}); //< okay
M m;
friendF(m); //< okay
friendF({}); //< error: doesn't the compiler allow this?
}
The compiler says that friendF "is not declared in the scope".
Try ... | The problem is not the {}, but as the compiler says: The function is not declared in the scope where you try to call it. Add a declaration:
struct M
{
static void staticF(M m) {}
friend void friendF(M m) {}
};
void friendF(M m);
int main()
{
M::staticF({}); //< okay
M m;
friendF(m); //< okay
f... |
65,267,014 | 65,267,408 | List iterator as an unordered-map key | #include <bits/stdc++.h>
int main ()
{
std::unordered_map<std::list<int>::iterator, int> map;
return 0;
}
This code doesn't compile. Error:
error: no match for call to ‘(const std::hash<std::_List_iterator<int> >) (const std::_List_iterator<int>&)’
noexcept(declval<const _Hash&>()(declval<const _Key&>()))>... | You need to define how the hash is generated for std::List<int>::iterator. You can do this by specialising the std::hash template struct for this type. Here is a naive implementation:
namespace std
{
template<> struct hash<std::list<int>::iterator>
{
std::size_t operator()(std::list<int>::iterator const... |
65,267,072 | 65,267,172 | Why does const_casting a heap.top() of priority_queue have undefined behavior? | I've made a simple Huffman encoding program to output individual encodings for characters and save the encoded file. This was for an assignment, and I was told that using const_cast on heap.top() is considered undefined behavior if we heap.pop() afterwards, but I'm not sure I understand why.
I've read cppreference rega... | tl;dr: Maybe; maybe not.
Language-level safety
Like a set, a priority_queue is in charge of ordering its elements. Any modification to an element would potentially "break" the ordering, so the only safe way to do that is via the container's own mutating methods. (In fact, neither one actually provides such a thing.) D... |
65,267,146 | 65,267,356 | How to navigate up in c++ files using relative paths | I'm using files for making operations on a txt file shared between 2 projects.
A grand folder contains both projects files and I want to use something like thissystem("..\ theOtherProject/launchEXEFromOtherProject.exe") to launch an "exe" from the other project.
The problem is I can't navigate up to the grand folder to... | You can navigate up, e.g. this works fine on my Windows 10 PC:
#include <cstdlib>
int main()
{
system(R"(..\..\..\..\..\Windows\notepad.exe)");
}
Here a raw string is used. Then you can also use the Windows path separators, if you like.
Instead of the raw string you can also escape the slashes, like:
system("..\\.... |
65,267,181 | 65,268,164 | Does not name a type C++ error in code blocks | #include <vector.h>
#include "UpdaterOptions.h"
struct VioManagerOptions {
std::vector<int> matrix_wh = {752,480};
matrix_wh.at(0) /= (params.downsample_cameras) ? 2.0 : 1.0;
matrix_wh.at(1) /= (params.downsample_cameras) ? 2.0 : 1.0;
std::pair<int,int> wh(matrix_wh.at(0),matrix_wh.at(... | It is a bit guessing what your intentions are, but maybe the code below looks like your intended program.
Within a struct one can declare data and functions. You did neither; your struct contains a function body. I've added a function name (member_function) to fix that. The error messages you got assumed that they were... |
65,267,880 | 65,267,935 | Is it possible to calculate the shortest path using Floyd Warshall's algorithm with a weight limit (C++)? | The point of the weight limit is that the algorithm should not use paths that exceed that limit even if it is the shortest path.
So if the weight limit was 50, in the graph below the algorithm should choose the path from 0 to 2.
https://i.stack.imgur.com/I9SCL.png
This is some code to find the shortest path using Floyd... | I’m pretty sure you didn’t write that code. But in any case, if certain edges should be disallowed because of a “ weight limit”, just ignore them when setting the initial edge costs.
|
65,268,135 | 65,268,195 | Arduino pick a random word from given array | I have this code that prints a word on an LCD:
void setup(){
lcd.print("Hello World");
}
I want it to pick a random word from this array:
const char *words[] = {"Happy","Sad","Angry","Worried","Shy","Excited","Suprised","Silly","Jealous","Hurt","Cold","Hot","Energized","Bored","Sick","Love","Upset"};
So basically usi... | First find the length of the array, then use random to get a number up to that bound:
const int len = sizeof(words) / sizeof(words[0]);
lcd.print(words[random(len)]);
|
65,268,728 | 65,268,991 | How does change in Passing parameters changes the output of the Code? | When I pass only Sum as Parameter in My coin Exchange Problem to find no of ways to find the amount Sum..
Example
if the coins are {2,3,5} and the desired sum is 9 i get correct output as 8.
This code :
#include <bits/stdc++.h>
using namespace std;
int n, sum, a[105];
int fun(int sum) {
int S = 0;
if(sum ... | You don't have the same result between your 2 solutions because in the first, at each "function call", you will iterate from 1 to N and in your second solution, you will iterate from Index to N. So the number of loop will be different.
|
65,268,808 | 65,619,519 | UE4-Changing movement speed depending on the direction of movement | I have a third person character. I use controller desired rotation for rotating character with the mouse as in PUBG etc. How can I change max walk speed when I go forward? For example, when I walk forward my speed must be 500 but when I walk right or backward my speed must be 250. How to detect this? I certainly can ad... | I can provide a solution for Blueprints, although I can't be certain it's appropriate in your case.
The key is to add movement input to the forward vector of your player character. See the screenshot below.
The AxisValue output from the MoveForward input event is +1 when you press forward and -1 when you press back.
I... |
65,268,995 | 65,269,205 | How do upper_bound and lower_bound work with comparator in c++? | I was just curious to know how lower_bound and upper_bound functions in C++ standard library work using comparators. I could not understand how they actually work using the documentation given at cppreference.com.
For ex.
vector<int> arr = {1, 1, 2, 2, 3, 3, 4, 4, 5, 5};
auto it1 = lower_bound(arr.begin(), arr.end(), ... | std::lower_bound requires that the input range be partitioned with respect to the comparator - that is, all elements for which comp(element, value) returns true must precede elements for which it returns false. In your example, only calls using less and less_equal satisfy this requirement; the other calls exhibit undef... |
65,269,298 | 65,269,335 | Giving the size to an array with a variable | I've been trying to give an array its size through a variable, but it's not working because "must have a constant value".
int processes[] = { 1, 2, 3 };
int n = sizeof processes / sizeof processes[0];
...
findavgTime(processes, n);
-------------------------------------------------
void findavgTime(int processes[], in... | As you've seen, you can declare an array with a non-constant size like this. You could, however allocate it dynamically using new:
int* wt = new int[n];
int* tat = new int[n];
Just don't forget that you need to delete[] these arrays when you're done.
|
65,269,549 | 65,269,676 | Acceptable font for QString degree symbol | I created a C++ class for generating a QML object. My class has a setter method that accepts a QString. I am attempting to pass a degree symbol to this method, however, the degree symbol appears as either a ? or a box depending on the font that I use. I have concluded that the font that I am using does not contain a de... | If you are using a const char* string literal, you need to have it encoded as UTF-8.
Degree symbol is \00b0 in UTF-16, but is 0xc2b0 in UTF-8.
Easy fix is probably this:
ptrHorizontalBarGraph->setUnits("\xc2\xb0 F");
Or you can explicitly be UTF-16:
QString s(QChar(0x00b0));
s += " F";
ptrHorizontalBarGraph->setUnits(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.