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 |
|---|---|---|---|---|
64,772,004 | 64,772,667 | C++ : Problem when doing command line make : undefined reference for Singleton::theInstance | I am trying to create a Singleton class in C++.
Here is the error:
CMakeFiles/minisig.dir/src/main.cpp.o : Dans la fonction « main » :
main.cpp:(.text+0x9) : référence indéfinie vers « Singleton::theInstance() »
main.cpp:(.text+0x12) : référence indéfinie vers « Singleton::theInstance() »
collect2: error: ld returned 1... | Ok so the answer was that I didn't change my CMakeLists.txt file before compiling
For next time :
modify your file
then command line : mkdir build, cd build, cmake .., make
|
64,772,031 | 64,772,509 | C++ Lambda to Function Pointer | I have three classes:
class ShapeEditor {}
class PointEditor: ShapeEditor{}
class RectEditor: ShapeEditor{}
I want to define a function pointer in Manager class and pass it in constructor as lambda function. It looks like this:
class Manager {
public:
ShapeEditor (*factory)();
Manager(ShapeEditor (*_factory)());
}... | @NathanOliver gave the correct answer in comments above:
Yes, but you didn't specify a return type for the lambda, so it gets it from the returned object, and that object doesn't have the same type as the return type your function pointer needs
So here is my solution:
Manager m = Manager([] -> ShapeEditor* { return n... |
64,772,179 | 64,772,242 | Why does an input of char in place of int always display value zero? | The following is my code:
#include <iostream>
using namespace std;
int main() {
int num;
cout<<"Enter a number: ";
cin>>num;
cout<<"The number is: "<<num;
return 0;
}
If I enter a character or a string instead of an integer on the prompt for cin>>num, the value of num is returned as 0 everytime. Is it beca... | This is a feature introduced in C++11. From cppreference;
before:
If extraction fails (e.g. if a letter was entered where a digit is expected), value is left unmodified and failbit is set.
(until C++11)
now:
If extraction fails, zero is written to value and failbit is set. If extraction results in the value too larg... |
64,772,377 | 64,772,848 | How to get keyboard accelerators for a command ID? | The MFC feature pack seem to magically print the resources keyboard accelerator shortcuts to the tooltip of a menu item.
How would I find the key combination for any given command ID (if all I have is the HACCEL handle?).
| You can use the CopyAcceleratorTable() function to retrieve the list of accelerators for a given HACCEL handle.
First, call that function with nullptr and 0 as the second and third arguments to get the size of the list (i.e. the number of accelerators) and then allocate a buffer of ACCEL structures of appropriate size.... |
64,772,595 | 64,772,678 | What error in my code I have which cause exceptions ignored? | I am Implementing some program error exception catching and it's not getting to work properly thus I have seen any error in my code and compiler is also not showing any warnings and error.
The programs build successfully but ignored the exceptions.
#include <iostream>
#include <string>
using namespace std;
void wrongU... | correct the following
void programErrorExceptions()
{
void wrongUsage();
}
to
void programErrorExceptions()
{
wrongUsage();
}
|
64,772,727 | 64,776,026 | Mysterious C++ threading crash | The following code strangely crashes when entering the run function. None of the printfs trigger, and single-stepping into the function will cause a crash. Is it undefined behaviour, or a compiler bug? I'm on MacOS compiling with Apple clang 12.0.0. It crashes with EXC_BAD_ACCESS (code = 2).
#include <iostream>
#includ... | So, when you change your function to pre-reserve a stack frame with space for a half-megabyte object ... it crashes right at the start of the function when setting up that stack frame?
That's probably because you made sizeof Chunk equal to the entire default OSX thread stack size of 512Kb. If you single-step into the f... |
64,772,741 | 64,773,094 | Interpreting / Reading text files written for Assembly application | I am just starting out in C++.
I am writing a console application, to "read in" an .evt file (custom, not to be confused with Event viewer files in Windows) and its contents but now I need to write a method to.
a) Store each block of 'EVENT X' including but also ending at 'END'.
b) Make the contents of each block searc... | I would do something like this:
struct Subevent {
std::string selector;
std::string name;
std::vector<int> params;
};
struct Event {
int id;
std::vector<Subevent> subevents;
};
std::vector<Event> load_events(std::istream& input_stream) {
std::vector<Event> out;
Event current_event {}; // c... |
64,772,928 | 64,773,004 | How to initialize std::map by an array? | I have a task to fill empty std::map<char, std::set<std::string>> myMap, by an array
const char* s[] = { "car", "sun", "surprise", "asteriks", "alpha", "apple" };
and print it using range based for and bindings. Result, should be like S: sun, surprise
The last one(printing) I have already implement in this way
for (co... | How about this?
const char* s[] = { "car", "sun", "surprise", "asteriks", "alpha", "apple" };
std::map<char, std::set<std::string>> myMap;
for (auto str : s)
myMap[str[0]].insert(str);
// Result: {
// 'a' -> {"alpha", "apple", "asteriks"},
// 'c' -> {"car"},
// 's' -> {"sun", "surprise"}
// }
|
64,772,951 | 64,773,393 | how do i configure `stdin` to read from a c++ string? | consider a cpp function solve(). A string a of numbers (sample test string) is passed to the function solve() as arguments.
I wanted stdin to read the numbers in the string a.
It is actually a stress-test. So in this stress test, this function solve() is provided with a string to return a result which will be tested ag... | Pass a std::istream to your function and then construct a istream from a string. As a general rule, do not to use global variables (like std::cin) in code that is meant to be unit-tested.
#include <sstream>
#include <iostream>
int solve(std::istream& input, std::string s) {
std::string variable;
input >> vari... |
64,772,953 | 64,773,060 | Overwriting a vector | I have a 2d vector that contains these elements:
1 3
4 6
I use a function to overwrite the vector by adding 1 to each element:
overwrite(){
for(int i = 0; i<rows;i++){
for(int j = 0;j<columns; j++){
2d_vector[i][j] + 1;
}
}
My task requires me to use another function to print the matrix onto console wh... | The line
_matrix[i][j] + 1;
takes each element, adds one, then discards the result.
Instead, you should use one of the following (all equivalent, in this case):
_matrix[i][j] = _matrix[i][j] + 1;
_matrix[i][j] += 1;
_matrix[i][j]++;
++_matrix[i][j];
|
64,773,399 | 64,774,032 | std::partition implementation | I have already read about differences between std::partition and std::stable_partition.
Also I have watched the cppreference example
int main()
{
std::vector<int> v = {0,1,2,3,4,5,6,7,8,9};
std::cout << "Original vector:\n ";
for(int elem : v) std::cout << elem << ' ';
auto it = std::partition(v.be... | If we look at the possible implementation from cppreference we can see its very deterministic (if the UnaryPredicate is deterministic).
template<class ForwardIt, class UnaryPredicate>
ForwardIt partition(ForwardIt first, ForwardIt last, UnaryPredicate p)
{
first = std::find_if_not(first, last, p);
if (first == ... |
64,773,494 | 64,791,914 | Propagate exception from C++ constructor with cython | I want to raise an exception in C++ class constructor if some parameters are invalid, e.g., do PyErr_SetString(PyExc_ValueError, "Error occurred"). Unfortunately, it does not propagate correctly, and I get SystemError: <class 'testlib.foo.Foo'> returned a result with an error set instead. Is it even possible to make it... | First, be aware that this has the potential to go a quite wrong. Python scoping rules are different from C++ scoping rules, and Cython largely follows Python scoping rules. Consider
# distutils: language=c++
cdef extern from "something.hpp":
cdef cppclass C:
C()
def f(x):
cdef C c
if x>0:
... |
64,773,552 | 64,783,929 | UWP Hardware Video Decoding - DirectX12 vs Media Foundation | I would like to use DirectX 12 to load each frame of an H264 file into a texture and render it. There is however little to no information on doing this, and the Microsoft website has limited superficial documentation.
Media Foundation has plenty of examples and offers Hardware Enabled decoding. Is the Media Foundation ... | Hardware video decoding comes from DXVA (DXVA2) API. It's DirectX 11 evolution is D3D11 Video Device part of D3D11 API. Microsoft provides wrappers over hardware accelerated decoders in the format of Media Foundation API primitives, such as H.264 Video Decoder. This decoder is offering use of hardware decoding capabili... |
64,773,921 | 64,774,553 | Pass dynamic array of objects safely and without forcing copies | I want to define a function Foo that takes as argument a few objects Widget, whose number is only known at run time. The simplest signature would be:
void Foo(const std::vector<Widget>& widgets);
The function can be made more general by turning into a template and using iterators. However, if the Widgets are not store... |
The function can be made more general by turning into a template and using iterators.
This is often a good design. Or alternatively, accept a generic range.
However, if the Widgets are not stored in some contiguous form, any signature based on array-of-values would force the caller to make a copy of each.
Which is ... |
64,774,029 | 64,775,424 | How to build a system for C++20 on Sublime Text? | I'm trying to run c++20 using the command + B key combination, not yet succeeded. Also tried to add -std=gnu++20, it did not work. How do I do that?
Currently, my system works with c++17 and here is the config build-system:
{
"cmd": ["g++", "-std=c++17", "-o", "${file_path}/${file_base_name}", "${file}"],
"fil... | You made a small typo. The executable is still g++, you just need to add either -std=c++20, -std=c++2a, or -std=gnu++20, depending on which features/extensions you want to take advantage of. So, change the relevant lines in your build system to this:
"name": "Run with C++20",
"cmd": ["bash", "-c", "g++ '${file}' -std=c... |
64,774,242 | 64,774,645 | Qt5 tr() macro does not translate text | I am trying to track down a bug in someone else's code where some text (but not all), is not getting translated by the tr() macro in the program. The strings in question that do not get translated are all translated in bulk in a function like so:
SafeStr extractStringFromContainer(UniContainer* p_uni_container, const S... | tr(text) macro is meant for literal text. It must not be used in any other context. Whereas QObject::tr is not a general-purpose translation function, in that it expects there to be an established context, and such context is provided by the enclosing class. Using QObject::tr outside of methods will lead exactly to the... |
64,774,356 | 64,775,166 | Why is the Right Side of my Image Being Wrapped Around? | essentially, I'm making a class that takes a BMP file for the constructor. From THIS POST I get all of the header data out of the way and then read RGB data into a vector. I then calculate the intensities as 0.25R + 0.5G + 0.25B. I put these numbers into a space-separated file, line by line. With the original above my ... | The problem you are seeing is caused by improper data alignment. Each scanline of .bmp file must have a byte-size divisible by 4. You are calculating the input data size correctly with this line:
auto dataSize = ((width * 3 + 3) & (~3)) * height;
However, while converting the img array you do not compensate/throw away... |
64,774,361 | 64,775,212 | How to convert std::string to wchar_t* | std::regex regexpy("y:(.+?)\"");
std::smatch my;
regex_search(value.text, my, regexpy);
y = my[1];
std::wstring wide_string = std::wstring(y.begin(), y.end());
const wchar_t* p_my_string = wide_string.c_str();
wchar_t* my_string = const_cast<wchar_t*>(p_my_string);
URLDownloadToFile(my_string, aDest);
I'm using Unic... | First off, you don't need the const_cast, as URLDownloadToFileW() takes a const wchar_t* as input, so passing it wide_string.c_str() will work as-is:
URLDownloadToFile(..., wide_string.c_str(), ...);
That being said, you are constructing a std::wstring with the individual char values of a std::string as-is. That will... |
64,774,448 | 64,778,235 | Compiling project with LLVM MAC OS X causes linker error | I installed LLVM with brew
brew install llvm
in a test c++ file:
#include <llvm/IR/Value.h>
#include <llvm/IR/IRBuilder.h>
int main()
{
llvm::LLVMContext context;
llvm::Module *module = new llvm::Module("module", context);
return 0;
}
Makefile:
BIN=main
SRC_FILES=main.cpp
FLAGS := $(shell llvm-config -... | I ended up needing --system-libs as a flag in the llvm-config command:
FLAGS := $(shell llvm-config --cxxflags --ldflags --libs --system-libs)
|
64,774,646 | 64,774,833 | g++ -shared argument seems to be causing a segmentation fault | I am just getting started learning cpp, coming from a background in python and java. A few days ago I decided to try and mess around with python embedding in cpp using boost. I got the library installed, and I tried for a long time to get it working. However, no matter what I did, I kept running into a segmentation ... | You don't need -shared to link with the boost libraries. You need to add the python libraries too to resolve the undefined reference to _Py_NoneStruct.
Note that the order of the libraries is important:
g++ boost.cpp -o boost -lboost_python38 -lpython3.8
Here I've added the boost_mpi_python libraries too in case you ... |
64,774,762 | 64,774,953 | Creating a custom vector class. Push_back function only working for the first value | In my Comp Sci class, we are learning how to make our own vector class. We will eventually store our custom made string class objects in a custom made vector class. I wanted to try and build a vector class of integers beforehand for simplicity.
So far, I have a default constructor that initializes my pointer to an empt... | In your code:
this->data[size] = val;
you are going outside of the allocated array.
Same in the previous loop (in its last iteration):
for(int i = 0; i != (size - 1); i++)
{
this->data[i] = temp[i];
}
|
64,775,221 | 64,775,423 | How can I add a 64 bit floating point number to an unsigned char array at specific indexes (C++) | I need to add a 64 bit floating point number into an unsigned char array at specific indexes (ex. index 1 through 8).
Example unsigned char array:
unsigned char msg[10] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
I want to add a floating point number like 0.084, for example, which is represented a... | Formatting the component bytes into a hex string and then reading those back in again is a terrible waste of time and effort. Just use std::memcpy() (in C++) or memcpy (in C):
std::memcpy(&msg[1], &dVal, sizeof(dVal));
This will take care of any required pointer alignment issues. However, it will not do any 'inter... |
64,775,345 | 64,776,099 | Generate tuple of pointers | I have a function similar to printf (variadic argument list) like:
void some_func(void* object, const char* format, ...)
{
va_list vl;
va_start(vl, format);
int** arg1 = va_arg(vl, int**);
char** arg2 = va_arg(vl, char**);
va_end(vl);
if (arg1 && *arg1)
{
*arg1 = 1024;
}
... | As I understand, you need to adapt the call to:
std::apply([](void* object, const char* format, auto&... args){
some_func(object, format, &args);}, args);
|
64,775,587 | 64,775,790 | Initialize child class before parent class without composition / decorator | Once again I need to do something like this -
I need to initialize first the vector, so I pass its data() address to the parent class.
#include <vector>
struct A{
A(int *a) : a(a){}
int *a;
};
struct B : A{
B() : A( v.data() ){}
std::vector<int> v { 1024 };
};
#include <cstdio>
int main(){... | Base classes are constructed first by design. No way around it. However, you can introduce a second base class and inherit from your base classes in desired order of initialization.
struct a
{
int x;
a(int x) : x(x) {};
};
struct b
{
int *px;
b(int* px) : px(px) {};
};
struct derived : a, b
{
public:
... |
64,775,804 | 64,776,761 | Use class in differents task on ESP8266 - CPP | I'm actually programming on esp8266.
I'm using multitasking and I would like to access a class from any task.
About the building I'm using PlatFormIO so I'm not manage the build.
Here is my main.cpp file :
#include "HackQuarium.h"
class LedShowTask : public Task {
public:
void loop() {
// some stuff
}
... | Seems to me that you declared static attributes, but you didn't define them. It should be:
File.h
class AllStaticData {
public:
t_API_current_weather currentWeather;
t_HackQuarium_data hackQuariumData;
};
File.cpp
t_API_current_weather AllStaticData::currentWeather;
t_HackQuarium_data AllSta... |
64,775,808 | 64,775,889 | How do I print the following array to show number 1 - 1000000 | I want to initialize an array and fill it from 1-1000000. How do I then print the array?
#include<iostream>
using namespace std;
const int holder = 1000000;
int main()
{
int i = 0;
int nums[holder] = {0};
for( int i = 0; i < holder; i++)
{
nums[i] = i+1;
}
return 0;
}
| How about something like this:
// First create a vector containing holder elements
std::vector<int> nums(holder);
// Then set each element to the number from 1 to holder, inclusive
std::iota(begin(nums), end(nums), 1);
Then to print it:
// Print each number in the vector, separated by newlines
for (auto num : nums)
{... |
64,775,894 | 64,775,981 | How to properly convert std::string to an integer vector | My high level goal is to convert any string (can include non-ascii characters) into a vector of integers by converting each character to integer.
I already have a python code snippet for this purpose:
bytes = list(text.encode())
Now I want to have a C++ equivalent. I tried something like
int main() {
char const* byt... |
However C++ code outputs [116, 101, 115, 116, -50, -108].
In C++, the char type is separate from both signed char and unsigned char, and it is unspecified whether or not it should be signed.
You thus explicitly want an unsigned char*, but the .c_str method gives you char *, so you need to cast. You will need reinterp... |
64,776,223 | 64,776,258 | Is use of empty std::optional<string> UB or not? | The following code:
std::optional<std::string> so;
std::cout << so->size() << std::endl;
std::cout << so.has_value();
outputs:
0
0
My question is whether its safe to call : so->size() on an empty optional. I used clang sanitizer, but it didnt report any UB in above code.
| Using operator-> on an empty std::optional is Undefined Behavior, regardless of what type T is in std::optional<T>.
According to cppreference on std::optional<T>::operator-> :
The behavior is undefined if *this does not contain a value.
|
64,776,718 | 64,776,804 | How to have reference vector as a class member? | I have a class that holds a vector. I want it so that if the original vector is modified, then the class member vector will also be modified. I.e. the class member vector is a reference to the original vector:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Entity {
public:
i... | You have two options here...
Use a vector reference
Have the class hold a vector<Entity> &, or a vector reference. This will require you to pass the vector you're referencing to the class at the time of creation. That could look like:
class Me {
public:
vector<Entity> &vec;
Me(vector<Entity> &v): vec(v) { }... |
64,776,764 | 64,777,635 | How to properly install c++ libraries when using mingw? | I am having trouble installing a c++ audio library called BASS(https://www.un4seen.com/). I have dumped the bass.h file into the mingw32 include directory. I have also put the bass.dll file in the lib section of the compiler. Whenever I try to use the any of the functions or methods that are included in the bass.h file... | If it's telling you there's no reference to that function, then you're probably not linking the library properly. You have to use the -l flag to link the DLL to you project. If there are more DLLs, as you think there are, you can still use this flag to link them. If you need to include a directory of libraries, use -L.... |
64,776,833 | 64,789,000 | Boost 1.70 io_service deprecation | I'm trying to migrate some old code from using io_service to io_context for the basic tcp acceptor, but am running into issues when switching get_io_service() to get_executor().context() results in the following error:
cannot convert ‘boost::asio::execution_context’ to ‘boost::asio::io_context&’
This is the listener:
... | You will want to focus on executors rather than contexts.
Passing around executors is cheap, they are copyable, as opposed to contexts.
Also, it abstracts away (polymorphism) the type of execution context that the executor is attached to, so you don't need to bother.
However, the static type of the executor is not fixe... |
64,776,906 | 64,777,022 | Make macro produce compile time error for non-existing function | I've got several functions in a namespace. The parameters are different, for every invocation they store an object containing a string member to a vector.
There are no overloaded functions in the namespace.
I'd like to create a macro that produces a lambda expression for matching objects created via a call of a certain... | You might just use it, assuming no overloads:
#define CALL_INFO_PREDICATE(functionName) [] (CallInfo* info) -> bool \
{ \
static_cast<void>(&mymath::functionName); \
return info->m_function == #functionName; \
}
cast to void to avoid warning for unused expression.
|
64,777,108 | 64,777,219 | error C3863: array type 'double [length]' is not assignable | In windows MSVC, I was trying to compile the below code.
void foo(std::vector<double> &bar){
const long int length = bar.size();
double a[length]; //error C3863: array type 'double [length]' is not assignable
for(int i=0; i < length; i++){
a[i]=0.0;
}
//do some other things
}
the code works... | double a[length]; is not portable C++ as variable length arrays are not implemented by the language.
std::vector<double> a(bar.size());
is the replacement. Note that the elements will be initialised to zero for you, so you can remove the initialisation loop.
|
64,777,306 | 64,777,383 | Unsure of how to proceed with functions related to istream and ostream | I have to write a program that uses the following functions, but I'm not sure how to proceed from this point forward. Essentially, I want getValue to use the inputstream and outputstream referenced in the main function (cin and cout, in this case) but I get numerous errors. If needed, I can provide my header file.
#inc... | istream inputStream and ostream outputStream won't work. Streams are not copyable. Make those references too.
double getValue(istream& inputStream, ostream& outputStream, string promptUser) {
double number;
outputStream << promptUser;
inputStream >> number;
return number;
}
As a sidenote: You don't nee... |
64,777,578 | 64,777,802 | Second lambda function in template causes compile error (intellisense does not detect problems) - error C2988 | I'm using the latest version of C++ (guess it is something between C++17 and C++20) available in visual studio enterprise 16.8 (but this error happening on previous versions too).
The following part of the code works correctly if exclude SquareMatrixInput<T> input_func = [](bool latest) { T temp; cin >> temp; return te... | I think it's a bug in the Visual Studio compiler (I can reproduce with Community Edition 2019). Clang-cl has no problem with your code.
The problem appears to be that the compiler is confused by the >> operator in cin >> temp; and can be fixed by enclosing that operation in parentheses, like so:
template<typename T = i... |
64,777,687 | 64,778,254 | Why does this Y Combinator using code fail to compile? | I've been reading about combinators for three days now and I finally started writing them in code (more like copying stuff from places and making sense of things).
Here's some code that I'm trying to run:
#include <iostream>
#include <utility>
template <typename Lambda>
class y_combinator {
private:
Lambda lambd... | Type deduction
The type of n == 1 ? (int64_t)1 : n * self(n - 1) depends on the the return type of self, therefore it can't be deduced. You would think that int64_t is an obvious candidate, but float and double are also just as good. You can't expect the compiler to consider every possible return type and choose the ... |
64,777,715 | 64,777,918 | C++ How to avoid repetitive code for variables of different third-party type? | I have class that is managing a number of similar member variables of different, but similar type.
class Manager {
Type1 a;
Type2 b;
Type3 c;
void process();
};
Although the types are different, they share some functions and attributes. At least this lets me use some templated functions to process the class me... | It seems like this is exactly the use case for the preprocessor---removing repeating code and stringifying identifiers. If you don't like it, and you don't mind the horrible syntax, you could make Manager a tuple:
class Manager {
std::tuple<Type1, Type2, Type3 /* more types can be added ... */> tup;
}
Then you can... |
64,777,804 | 64,778,124 | how to write clean try/catch block when find function returns a reference? | I have some code that looks like this:
const SomeType & elt = x.find();
try {
// ... do something with elt ...
} catch (...) {
// handle processing exception
}
And it works, but due to changing circumstances, it's now possible for that find() method to throw a "not found" exception, which I need to catch.
What... | If exceptions are different, you might use the same try block:
try {
const SomeType& elt = x.find();
// ... do something with elt ...
} catch (const NotFoundException&) {
// handle "not found" exception
} catch (...) {
// handle processing exception
}
else rebinding reference is not allowed, but might ... |
64,778,367 | 64,778,711 | How template explicit instantiation works? | I am struggling to understand Template Explicit Instantiation using extern specifier. Here is my example"
// power.h
template <typename T>
class Power
{
public:
T operator()(T const& x) {return x * x;}
};
// power.cpp
#include "power.h"
template
class Power<int>;
//mathlib.h
class Square
{
public:
Square(int... |
I want to know whether this is how Explicit instantiation works or not?
Yes.
Why I get in each *.ii a definition of the template class Power?
*.ii files are result of pre-processing phase. unrelated to template instantiation.
Does this mean the class template Power is only defined but not yet instantiated and the ... |
64,778,516 | 64,778,582 | Detecting repeating digits in a number | I am trying to build a method that would take an integer as input. Then split that integer into single digits and then store them inside a vector. I then use sort() to sort the vector so I can detect any repeating elements within the vector. Upon the first repeat, I want to return True, if no repeat, I want to return F... | Delete your else branch - it causes your cycle to break on first iteration, so it only checks if the first digit in temp is duplicated.
Moreover, instead of RepeatDigit(numerator) == false you could simply write !RepeatDigit(numerator)
|
64,778,584 | 64,778,775 | The better way to control player in 2d game ? (sdl2) | I'm doing this like this, in .hpp file:
class Player
{
public:
Player(){}
Player(){}
virtual ~Player(){}
void handler(SDL_Event event);
void update()
{
move(velocityForwardX, velocityForwardY);
move(-velocityBackwardX, -velocityBackwardY);
/* the player moves from it cu... | You could store only one variable per direction and add and subtract speed when pressing and releasing a button, e.g.
switch(event.key.keysym.sym)
{
case SDLK_d:
velocityX += speed;
break;
case SDLK_q:
velocityX -= speed;
break;
case SDLK_z:
velocityY -= speed... |
64,778,919 | 64,779,332 | object copy happens even with move constructor defined when RVO disabled | I happened to find a scenario where I am returning an object from a function by value.
With a conditional statement at the return statement, RVO is avoided.
Here is the code:
#include <iostream>
#include <cstring>
class myObject {
public:
myObject() {
std::cout <<"Default Constructor called" << std::en... |
It seems that in the line myObject c = GetObject_Complex(1,0), copy operation is happening.
Sort of but not quite. More accurately, the copy operation happens within GetObject_Complex when the
result of the ternary conditional operator is copied to the temporary return value.
Why move construction is not happening h... |
64,779,422 | 64,779,566 | Call to make pair with mutex as argument fails. Cannot insert mutex onto unordered map | Below is an error
std::mutex mtx;
auto t = std::make_pair(std::string("hello"), mtx);
But the following is not?
std::mutex mtx;
auto t = std::make_pair(std::string("hello"), 1);
My ultimate goal is to create a create an unordered map of type:
std::unordered_map<std::string, std::mutex>
Using:... | std::mutex is not copyable or moveable. When you do
std::mutex mtx;
auto t = std::make_pair(std::string("hello"), mtx);
and
mHeartBeatMutexes.insert(std::make_pair(std::string("hello"), mtx));
std::make_pair tries to make a copy of mtx since it is an lvalue and it can't because std::mutex is not copyable.
In
std::mu... |
64,779,452 | 64,868,073 | Set transform origin point for an already transformed QGraphicsItem | I have a robotic hand which contains of two connected moving arms. when arm1 is being rotated, arm2 is also rotating around the same origin point of arm1. when arm2 is being rotated arm1 should not move and arm2 should rotate around arm2 origin point.
QPixmap arm1(":/new/prefix2/pictures/arm1.png");
QPixmap arm... | The problem is already solved simply by using setOffset and mapFromItem the final code is :
QPointF c1 = arm1p->mapFromItem(bodyp,423,188);
arm1p->setOffset(-29,-375);
arm1p->setPos(c1.x()*scale,c1.y()*scale);
arm1p->setRotation(arm1angle);
QPointF c2 = arm2p->mapFromItem(arm1p,712-29,42-375);
... |
64,779,837 | 64,800,095 | Is there any way to get CGAL's polyline simplification to work for inner/shared boundaries? | I've been trying to carry out line simplification on polygons belonging to maps with the help of this CGAL guide, e.g. South Korea.
This is a screenshot of South Korea after line simplification with CGAL.
I carried out the line simplification by adding each polygon to CGAL::Constrained_triangulation_plus_2<CDT> ct and ... | As you write "shared boundaries" I guess they are there twice, once seen from each province. You have to split the province-polygons where three provinces meet, and
then only take one of the two shared boundaries.
|
64,779,971 | 64,780,005 | How do I fix Error: duplicate case value in C++? | I'm fairly new to c++ and programming in general. I want to be able to test for the origLetter char. However, it could be 'a' or 'A'. When I attempt to execute my program it throws back an error. "Error: duplicate case values". I want to include both of the case values. How do I get around this?
using namespace std;
i... | The correct syntax is:
switch (origLetter) {
case 'A':
case 'a':
cout << "Alpha" << endl;
break;
case 'b':
case 'B':
cout << "Beta" << endl;
break;
default:
cout << "Unknown" << endl;
break;
}
|
64,780,598 | 64,782,324 | Why isn't this class specialization using a concept accepted? | The following code attempts to partially specialize a class using a concept and add a method to the specialization, but it is rejected by clang 11.0.0:
#include <concepts>
template <typename T> // note: previous template declaration is here
struct S {};
template <std::integral T>
struct S<T>
{
void f();
};
templ... | This is definitely a CLANG bug. It is already filed - #48020.
|
64,780,699 | 64,796,487 | Is it more efficient in SYCL to use one buffer or multiple buffers? | Suppose I have an array of data, for example an array of 3D vectors of size N. Suppose that each iteration of my SYCL kernel is exclusively or primarily concerned with only one vector. Which of the following ways of breaking this into contiguous buffers is, as a general rule, more efficient--or does it matter?
I realiz... | For memory access patterns on GPUs, it is first important to understand the concept of coalescing. Basically it means that in certain conditions, the device will merge memory accesses of adjacent work items and instead emit one large memory access. This is very important for performance.
The detailed requirements when ... |
64,780,762 | 64,781,180 | Calculate Average of Numbers in between each other C++ | Im trying to retrieve values from the user and then use those values to print out the numbers in between them. The numbers have to fall into certain parameters. I need to find the average of the numbers in between the two user inputs but I have no idea how to get those. I can calculate the sum but I cannot figure out h... | As much I can understand, you want to find average instead of sum. It's easy, just create another variable to track number of times you have added to sum and then divide sum by that number
#include <iostream>
using namespace std;
int main()
{
//retrieves box dimensions
int boxHeight;
cout << "Enter a box height (be... |
64,780,829 | 64,780,881 | Explain the algorithm in detail | int Min[m];
for(int i=0; i<m;i++){
int Min_Element=INT_MAX;
for(int j=0;j<n;j++){
Min_Element = min ( Min_Element , Target[i][j]);
}
Min[i]=Min_Element;
}
Can someone tell me the whole explaination about the algorithm above to me please..
I still can't figure out the detail about how the Min_El... | This may help
int Min[m]; // store minimum value for each row
for(int i=0; i<m;i++){ // loop each row
int Min_Element=INT_MAX; // start at max value
for(int j=0;j<n;j++){ // for each number in row
Min_Element = min ( Min_Element , Target[i][j]); // set minimum value if less than current minimum
... |
64,781,091 | 64,781,115 | How to read a line using scanf in c++? | I'm trying to use "scanf" to read a string line: "is it not working", but I don't know if it's even possible to implement it in this particular example.
#include <iostream>
#include <iomanip>
#include <limits>
#include <string>
using namespace std;
int main() {
int i = 4;
doubl... | %s in printf/scanf family stands for char array, not std::string. If you want to get line, use std::getline. If you want to use std::string buffer for stdio functions, use std::string::data function, but I wouldn't suggest that as buffer-overflow is likely, especially for something like get-line.
|
64,781,202 | 64,781,273 | Copy assignment operator returning *this vs (*this) | Is there a difference between
class MyString {
...
MyString &operator=(MyString other) {
swap(s, other.s);
return (*this);
}
};
and
class MyString {
...
MyString &operator=(MyString other) {
swap(s, other.s);
return *this;
}
};
I read in some other posts that adding par... | The link you have cited discusses a different situation. In this case
*this == (*this)
It depends on your preference since both of them will do exactly the same thing. Personally, I'd prefer *this to avoid unnecessary parenthesis
Operator precedence can sometimes change the way you want to de-reference something. Imag... |
64,782,096 | 64,783,088 | How do I speed up this program to find fibonacci sequence | I am doing this coding question where they ask you to enter numbers N and M, and you are supposed to output the Nth fibonacci number mod M. My code runs rather slowly and I would like to learn how to speed it up.
#include<bits/stdc++.h>
using namespace std;
long long fib(long long N)
{
if (N <= 1)
ret... | While the program you wrote is pretty much the go-to example of recursion in education, it is really a pretty damn bad algorithm as you have found out. Try to write up the call tree for fib(7) and you will find that the number of calls you make balloons dramatically.
There are many ways of speeding it up and keeping it... |
64,782,121 | 64,782,620 | Deduce lambda return and arguments passed to constructor | I have the following class:
template<typename R, typename... Args>
class Callable final
{
public:
Callable(void* args, R(*fn)(Args...));
Callable(void* args, std::function<R(Args...)> &&fn);
/* parse args into a tuple<Args...> and invoke callable */
void* invoke();
private:
void* args;
... | If we're allowed to modify the template signature of Callable to remove the pack Args... in favour of a single parameter, we can write our own deduction guide for Callable:
template<typename Fn>
class Callable final {
public:
Callable(void* args, std::function<Fn>&&);
void* invoke();
private:
void* ar... |
64,782,573 | 64,784,054 | Not correct template specialization | Please tell me i have class Foo, where i overload operator<<.
I need the so that operator<< work with unsigned type differently.
For this I am trying to declare a template specialization, but wrongly.
#include <iostream>
class Foo {
public:
Foo(std::ostream& out)
: _out(out) {}
template <typename T>
... | As @super pointed out correctly an overload makes more sense in this case. Just for completeness this is the way template specialization would be done:
#include <iostream>
class Foo {
public:
Foo(std::ostream& out) : _out(out) {}
template <typename T>
Foo& operator<<(const T& s) {
_out << "[]: " << s;
... |
64,783,378 | 64,791,508 | Do I have to build clang-11 from source on Ubuntu 18.04 to have OpenMP GPU target offload? | I installed clang-11 from https://apt.llvm.org/ on Ubuntu 18.04 and I have OpenMP host device functionality working in my C++ test project, but omp_get_num_devices() returns 0, even though I have Nvidia GPU and working CUDA 11 toolkit. Do I have to build a special version of Clang from source in order to get OpenMP GPU... | The Debian/Ubuntue packages for LLVM do not come with OpenMP offload support for GPUs [0] (at least until LLVM 11) . Packaging this is a bit tricky but we are working on it. One of the tricky parts, for now, is that for reasonable performance it requires a two stage build and you need(ed) to specify what GPU architectu... |
64,783,841 | 64,784,012 | Are there real use cases for smart pointers? | I was reading about smart pointers in C++ and I am surprised that more than 99% of the given examples are in fact fairly bad examples because in those cases dynamic allocation could be avoided. I would agree to use smart pointers only in the context that STL containers wouldn't work. For instance in dynamic arrays (std... |
I am surprised that more than 99% of the given examples are in fact fairly bad examples because in those cases dynamic allocation could be avoided
This is probably because the examples are intended to be super-simple.
So what could be good examples or uses for Smart Pointers in C++?
Never mind "goodness", but consi... |
64,784,248 | 64,784,943 | IMFTransform::ProcessOutput Efficiency | I've noticed that as apparently documented IMFTransform::ProcessOutput() for a resampler can only output one sample per call! I guess its more orientated at large frame size video coding. Given all the code I have been looking at as reference for related audio playback allocates one IMFMediaBuffer per call of Process... | I wrote some code for you to prove that audio resamper is capable to process large audio blocks at once. It is good, efficient processing style:
winrt::com_ptr<IMFTransform> Transform;
winrt::check_hresult(CoCreateInstance(CLSID_CResamplerMediaObject, nullptr, CLSCTX_ALL, IID_PPV_ARGS(Transform.put())));
WAVEFORMATEX ... |
64,784,331 | 64,784,408 | Bubble Sort algorithm leaves array unchanged | I'm trying to write a simple bubble sort algorithm but it isn't working. The array is unchanged when it is printed at the end.
I have used the debugging tools on my IDE and it tell's me that the second for loop isn't incrementing but I can't tell why it isn't.
I'm still new to learning C++ and algorithms in general, so... | Your algorithm is wrong. You should check the flag after the second loop has finished
int flag = 0;
for (int j=0; j<n-i-1; j++) { //optimise checks, avoid checking sorted part of array
if (A[j] > A[j+1]) {
int temp = A[j];
A[j] = A[j+1];
A[j+1] = temp;
fla... |
64,784,519 | 64,791,982 | __asm nop for breakpoints with MinGW compiler? | I want to create stop points for debugger by __asm nop command (next step to create #define __asm nop stop) and simple use it. But it doesn't works well as it works in Visual Studio with MSVS, I cant change compiler in this project and I have to use MinGW.
I dont know right syntax for this problem in MinGW, what is the... | The solution is to use __asm__("nop"); or asm("nop"); (suggested solution by Nate Eldredge )
|
64,784,612 | 64,862,866 | Calling CPP function from C File doesn't work properly | I have a QT application which is written in c and c++. I tried to call a CPP function from C file. When I tried to call my callback function with a qpushbutton from UI, It works but when I tried to call my callback function in the main, It does not work correctly. What is the problem according to the below codes? Thx.... | I think the code didn't work because of the static method which I wrote for the callback function. When I changed the static function to class function, It worked! But I still don't know why static method did not work.
|
64,784,703 | 64,788,824 | Something wrong with odd sum | This code does not show the correct output.
I need help at the sum, odd. I am not sure if the vector is ok. What I need to do is "to calculate and display a vector that has as product elements the corresponding element on the first row and the first column."
Here is an image with the code when is running.
The input and... | You are defining a matrix 20x20 in resize regardless of the players input.
I would recommend a dynamically sized array using std::vector or something similar.
The extra size is usually fine, but in this program it has caused the program not to crash at the first for loop when it should have crashed.
Arrays in C++ have ... |
64,784,939 | 64,786,446 | template deduction failed for std::plus | The following code defines an operator+ between std::array of arbitrary type. The implementation consists in defining an auxiliary routine op2 that takes a generic callable operator and applies it to every element of the array, via template recursion.
#include <array>
#include <functional>
#include <iostream>
template... | The same problem occurs in the following simplified demo:
std::array<int, 3> a{1, 2, 3};
std::array<int, 3> b{2, 2, 1};
print_array(std::plus{}(a, b));
Internally, std::plus invokes operator+. But since it is invoked in the std::namespace, it may not find your custom operator+ defined outside of this namespace.
Gene... |
64,785,323 | 64,785,902 | Python Pandas does not recognize numbers when read from .txt file | I'm using Pandas to write to table from .txt file generated by other C++ program. Python or Pandas do not recognize them as numbers and I'm really clueless what to do. Here is Python code:
df = pd.read_csv(r'C:\Users\romea\Desktop\Inżynierka\ER_etap_5\Metropolis_average_path_6_p_0.010000_nodes_100.txt', sep='\t', engin... | import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(r'your_file_here.txt', sep='\t', header=0)
plt.scatter(df["iteracja"], df["variancja"])
plt.show()
|
64,785,336 | 64,879,352 | An issue about the member function qualified by volatile qualifier | #include <iostream>
struct A{
A() = default;
A(volatile const A&){}
void show()const volatile {
}
};
int main(){
volatile A a;
//A b = std::move(a); // ill-formed
std::move(a).show(); //OK
}
Consider the example, the results of the example are out of my understanding about some relevant rul... |
struct A {
A() = default;
A(volatile const A &) {}
void show() const volatile {}
};
int main() {
volatile A a;
std::move(a).show(); // OK
}
The implied object parameter for the member function show() is, as per [over.match.funcs]/4, const volatile A&, such that for the purpose of overload resolu... |
64,785,427 | 64,788,038 | C++ Windows API - How to retrieve font scaling percentage | I want to retrieve the "Make text bigger" percentage in C++ Windows API application. I know how to retrieve the scaling (DPI) factor, but I also want to include the font scaling percentage (see the attached image, the upper value, not the lower one).
Ultimately, I want to make application that preserves user font and D... | For the "Make everything bigger" section, you can use GetScaleFactorForMonitor
Gets the scale factor of a specific monitor.
For the "Make text bigger" section, you can use a WinRT static property: UISettings.TextScaleFactor
Gets the value of the system text size setting.
Otherwise the latter can also be read using ... |
64,785,650 | 64,786,034 | How to convert a while loop into a for loop? C++ | I've checked the solutions for problems that are similar to mine, but they did not work in my situation.
I want to make this program use a for loop instead of the while loop.
#include <stdio.h>
#define SENTINEL -99
int main(void) {
int sum = 0, number;
printf("Enter first number (or %d to quit)> ", SENTINEL);
... | #include <stdio.h>
#include <vector>
#define SENTINEL -99
int
main(void)
{
int sum = 0, number;
std::vector<int> v;
printf("Enter first number (or %d to quit)> ", SENTINEL);
scanf_s("%d", &number);
for(int i = 0; number != SENTINEL; i++) {
sum += number;
v.push_back(number);
printf("Enter next n... |
64,785,794 | 64,788,221 | Can't tell if Mutex Lock is kicking in or not? | I'm working on a college assignment and have been tasked with showing a basic mutex lock example. I've never worked with threads in any form, so I'm a total beginner working with POSIX threads in C++.
What I'm trying to get the program to do is create 1000 threads that increment a global integer by 1000.
#include ... | Sorted a way to show the mutex lock in action. So when I output the global var in the function, without mutex locks it has the potential to show the results out of order.
Running the number range with mutex locks, out looks like:
1000
2000
3000
... (etc)
10000
With mutex locks removed, the output can vary in the order... |
64,785,872 | 64,799,554 | fstream fails to open file | I have a very weird problem. The setup is the following:
Library A uses Library B
Both libraries are installed as shared library independently and A links to B using CMake packages.
When I create an executable that directly links to B, everything works fine.
When I create an executable that links to A however, which is... | Okay, apparently a reboot was all it takes. Today everything works flawlessly. No permissions, file or line of code was changed. I assume either something went terribly wrong, when my Laptop came back from hibernation. Or it was some pending ubuntu update? I really have no idea. I could swear it was shutdown at least o... |
64,787,060 | 64,787,113 | Confusing idiom name RAII | I think I understand what RAII means and I found numerous questions about this idiom on SO. My concern is more about the RAII name itself. I don't find a way to match the four words of this idiom to the concept it describes. Has someone has ever asked Bjarne about that?
In my understanding RAII means:
Encapsulate a Re... | In an RAII type, the constructor acquires the resource that needs to be managed. So, if you do
RAII_Type foo;
Then that resource acquisition happens at initialization, so resource acquisition is initialization.
|
64,787,374 | 64,787,745 | binding const reference to rvalue reference | I have this private member function below, (part of class template, Heap) :
template <typename Task, typename Priority>
const size_t& Heap<Task, Priority>::parent_of(const size_t& index) const
{
// ** warning C4172: returning address of local variable or temporary
return (this_index-1)/2;
}
And i am calling it... | If you want to preserve the lifetime semantics of a return value depending on the value category of the returned expression, you can't return a const&, or even a && since you will face issues with dangling references.
Instead, you can use decltype(auto) for the return type in order to deduce the appropriate value categ... |
64,787,851 | 64,792,714 | Can I forward declare a type defined elsewhere with typedef | I know that I can forward declare a class or struct that is defined in another header file (that I do not want to include). I'm trying to do the same thing with a plain old data type which is specified by a typedef.
class foo; // defined in foo.h
struct bar; // defined in bar.h
typedef baz; // defined in baz.h
void Cr... | You can’t do this, because there is nothing at all that can be done with a type without knowing what kind of type it is. In particular, baz might be a function type, in which case const baz and baz are the same type (affecting overload resolution), or it could be an lvalue reference type, in which case those, baz&, an... |
64,788,460 | 64,788,602 | Is there a less verbose idiom for unpacking an optional in C++? | In the project I am currently working on I find myself writing a lot of code that looks like the following, where, get_optional_foo is returning an std::optional:
//...
auto maybe_foo = get_optional_foo(quux, ...)
if (!maybe_foo.has_value())
return {};
auto foo = maybe_foo.value()
//...
// continue on, doing things... | You don't need an intermediate object. std::optional supports a pointer interface to access it so you can just use it like:
//...
auto foo = get_optional_foo(quux, ...)
if (!foo)
return {};
//...
foo->some_member;
(*foo).some_member;
|
64,788,795 | 64,788,833 | Why did I get an error about null pointer while customizing a comparator | I'm trying to solve this problem on Leetcode: https://leetcode.com/problems/merge-intervals
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into ... | In your comparator, this comparison:
return e1[1] <= e2[1];
does not satisfy a strict-weak-ordering on the elements being compared. e.g. if
e1: {1, 2}
e2: {1, 2}
then comparing e1, and e2 will return true, regardless of the comparison order.
Violating this requirement of std::sort invokes undefined behavior. In this ... |
64,788,932 | 64,789,597 | How to make a min heap of tuples sorted by the 2nd element? | So I can make a min heap by doing the following:
// Creates a min heap
priority_queue <int, vector<int>, greater<int> > pq;
pq.push(5);
pq.push(1);
pq.push(10);
pq.push(30);
pq.push(20);
// One by one extract items from min heap
while (pq.empty() == false)
{
cout << pq.top() << " ";
pq.pop();
}
return 0;
But... | You can do this in two ways:
Change the order of the tuple so the column you want to sort is the first in the tuple.
Create a custom comparator outside of your function definition.
Struct Comparator {
bool operator()(tuple<int, int>& t1, tuple<int, int>& t2) {
return std::get<1>(t1) > std::get<1>(t2);
... |
64,789,034 | 64,789,186 | glibmm.h: could not find such directory or file | I want to include gtk to my new cmake project. But wen I compile, I get this error: +
In file included from /home/chhu/CLionProjects/MasterMind/main.cpp:2:
/usr/include/gtkmm-3.0/gtkmm.h:87: fatal error: glibmm.h: could not find such directory or file
This is my cmake file:
cmake_minimum_required(VERSION 3.17)
project... | Gtkmm is not a part of Gtk. You should update your CMakeLists
PKG_CHECK_MODULES(GTKMM3 REQUIRED gtkmm-3.0)
INCLUDE_DIRECTORIES(${GTKMM3_INCLUDE_DIRS})
LINK_DIRECTORIES(${GTKMM3_LIBRARY_DIRS})
ADD_DEFINITIONS(${GTKMM3_CFLAGS_OTHER})
TARGET_LINK_LIBRARIES(MasterMind ${GTKMM3_LIBRARIES})
|
64,789,486 | 64,789,666 | Exception thrown: read access violation.during BST Deletion for many elements | so am having problems with the exception during deletion(Exception thrown: read access violation.
parent was 0x158398.)like that sometimes are different numbers etc and always its about parent object/pointer, my code is working without any errors,exceptions till 100k objects then sometimes works sometimes not, for 1 mi... | findParentForDelete does not always return a value.
It will not return a value if the node you're looking for has an age that is the same as a different node in the tree, so the value returned to the caller will be a garbage value.
If you increase the warning level when you compile, most compilers will issue a warning... |
64,789,609 | 64,789,776 | VS2017 developer command prompt only builds to x86 - need x64 | I'm trying to build some C++ libraries using cmake using the VS2017 developer command prompt. I need to build them for a Release x64 setup, however, the command prompt only seems to build them to x86.
First, I run this command (note the build type Release64):
cmake -G "NMake Makefiles" -DCMAKE_BUILD_TYPE=Release64 -Dpr... | If you do not require using NMake, you could use the Visual Studio's build system by first generating for 64 bit (note the Win64 part):
cmake -G "Visual Studio 15 2017 Win64" -DCMAKE_BUILD_TYPE=Release64 -Dprotobuf_BUILD_SHARED_LIBS=ON -DCMAKE_INSTALL_PREFIX=../../../../install ../..
And then building via cmake's bui... |
64,789,979 | 64,790,005 | What exactly should I declare in a header file in C++? | I have searched almost every website I could, but nobody has been able to answer my question. Basically what I ask, is what exactly should I place in a header file? I know of function declarations, but are variable declarations in a .h file also a thing? I need to know what the "tradition" or the "usual method" is of u... | Header files conventionally contain declarations of entities that you wish to share between translation units.
That usually means class definitions, type aliases, and function declarations.
A translation unit, very roughly speaking, is "a .cpp file".
So, if you use a function in a.cpp, and you also use it in b.cpp, a d... |
64,790,100 | 64,791,253 | Creating a linked list program from user's input | We are asked to make a program using list structure to list student information but I can't seem to find a way to output all of it. It only shows one and it is the last input. I'm new in doing linked list so I do not know how to manipulate them. Any help will be much appreciated! Thank you guys!
#include <iostream>
#in... | In for loop you should save new stud object for setting stud->next during next iteration.
In while loop you are checking only last created stud object. You must set stud for the first object from the list, you can use head object for that to save first list element.
I think that if (head == NULL) ... part is not necess... |
64,790,113 | 64,800,406 | avformat_write_header() doesn't work when writing data to memory instead of file | i want to resample a given input format from memory to memory everything is good so far.
but when trying to get the output header from ffmpeg it doesn't work.
here i allocate the context and pass the write_buffer function pointer so that it doesn't write to a file but instead it will call my function with the required ... | well, after a lot of debugging that led me to discover the way ffmpeg writes format headers.
long story short, some formats are associated with special functions for writing their headers.
the "s16le" format inside ffmpeg is not associated with one. but surprisingly as i stated in the question ffmpeg can write its data... |
64,790,125 | 64,790,201 | How can a unsigned char take a int value? | In class we have to make a code that give a color etc etc, I am very bad to explain things (I'm french).
So the problem is that in my code (under), I would like to prevent the user to input a number up to 255, but it actually don't work, how can I fix it ;p
Thanks all
#include <iostream>
using namespace std;
//Déclara... | Check if the input is valid before assigning into your char!
If you assign into your char immediately and then check to see if the char is under 256, it will always be!
You need to check the int before you assign (and ever better, check that it's in the range [0, 255] like you want):
cout << " Entrez la valeur du rouge... |
64,790,174 | 64,790,396 | std::unordered_map with custom allocator / local allocator does not compile | I have a pretty simple custom/local allocator. My goal is to use an array on the stack as the allocating portion of memory. It appears to work in std::vector but when I try to plug it in to std::unordered_map it fails to compile. gcc 7.4.0's error messages are pretty impenetrable. Something along the lines of:
hashtabl... | An allocator of type T must be rebindable to an allocator of type U -- this is why there is the rebind template.
To do this you must offer a way to conversion-construct from a type U to a type T e.g. a constructor that constructs from MonotonicIncreasingAllocator<U, ...>&, such as:
template <typename U>
MonotonicIncrea... |
64,790,492 | 64,790,571 | How to pass value to parameterized constructors if there objects are being created as data members of another class? | I am trying to make a Chess Game in C++ using OOPS concepts but face the following error:
src/Game.cpp:6:36: error: no matching function for call to ‘Player::Player()’
Game::Game(): player1(1), player2(0){
^
In file included from include/Game.h:4:0,
from src/Game.cp... | The source of the error is that Game is derived from Player.
Game::Game(): player1(1), player2(0){
}
is the same as
Game::Game(): Player(), player1(1), player2(0){
}
My suggestion is to not make Player a base class of Game.
// class Game : public Player
class Game
{
...
}
|
64,790,597 | 64,791,542 | Sprite array loop only shows 1 element | Trying to get 4 clouds to move across the screen left to right. When I execute I can see all 4 clouds are drawn at the positions given in the code. But after game starts only one cloud is moving across the screen; the other 3 never show.
const int NUM_CLOUDS = 4;
Sprite clouds[NUM_CLOUDS];
int position = 0;
In main:
... | In your code, you are srand-ing every time before you rand. You're probably seeding with the same number every time, because not enough time has passed between calls to srand to change the number. Calling rand() depends deterministically, usually, on the random seed. This means if you call rand() multiple times, each t... |
64,790,947 | 64,791,230 | Is there a difference between "throw MyException()" and "throw (MyException())"? | I want to know if writing exceptions inbox and out box is changing the behavior or not of a particular program, for example throw MyException(); and throw (MyException());
My Code:
#include <iostream>
#include <exception>
using namespace std;
class MyException: public exception {
public:
virtual const char* what... | The exception object is copy-initialised (except.throw/3), so it doesn't really matter which one you use; the result is the same.
Copy-initialising would ignore a reference qualifier even if you got one out of this.
We can prove this with some trace output:
#include <cstdio>
using std::printf;
struct T
{
T() { pri... |
64,791,475 | 64,791,564 | C++ behavior unexpected of Set of class objects | For example, take a std::set of std::pair<int,int>, if you insert 2 pairs, {1,1} and {1,2}, both of them will be inserted in the set, however when i implemented a pair class, this behaviour is not seen. Only one of them gets inserted in the set. Please explain why?
#include <bits/stdc++.h>
using namespace std;
class P... | A set can only hold unique values. It uses operator< to determine uniqueness.
For two items a and b, if (!(a<b) && !(b<a)) then they are considered equivalent.
Your operator< only considers the x member of your pair, so the y member is completely ignored for purposes of your set.
|
64,791,490 | 64,791,627 | 2D white grid not displaying above background | I'm trying to create a 2D hollow grid on top of a purple background; however, what's being displayed whenever I create the grid is a white window.
I created the 2D grid using GL_Lines, as I only wanted the borders to be colored white and not the inside of the grid, which is not what happens.
#include <stdio.h>
#include... | GL_LINE is not an OpenGL primitive type. But GL_LINES is a line primitive type (see Line primitives):
glBegin(GL_LINE);
glBegin(GL_LINES);
GL_LINE is a polygon rasterization mode (see glPolygonMode).
One cell in your grid is only 1 pixel in size. This results in the entire screen being filled in white. Use a differen... |
64,792,031 | 64,792,375 | What is top-level in C++? | In example 14 under [dcl.init.list], the standard uses the term "top-level" when describing the semantics of code using list-initialization, in the context of narrowing conversions. I don't know what this means.
This code executes without errors:
int f(int a) { return 1;}
int main() {
int a[] = {f(2), f(2.0)};
... | This is not a strictly defined term. But in [dcl.init.list]/note-7 that you linked, "at the top level" seems to mean "written directly in a braced list, rather than in a nested expression".
So, in int x[] = {1.0, f(2.0)};, 1.0 is at the top level, because it's written directly in the braced list, but 2.0 is not because... |
64,792,605 | 64,792,650 | Is it possible to make some function parameters private to the outside of an object but accessible to inside of it? | I don't know if you would have to use different functions for the same task, but is it possible to do something like this in c++, but in another way?
void foo(int n , private Bar *bar) {}
I'm planning to code a recursive function into an object, but don't want some parameters to be accessible outside the object.
| You can do this:
struct Moo {
static void foo(int n);
private:
static void foo(int n,Bar* bar);
};
I don't like classes with only static methods (for reasons beyond the scope of this question), but thats the most simple to get what you ask for. foo(int) is public, the other overload is private (and can only be... |
64,793,219 | 64,793,863 | Trying to pass an array of pointers to objects, to a function of another class in C++ (not allowed to use vectors) | I have a class named Student. I create many student objects in my main (each object representing one student.)What i'm really trying to do is pass each one of these students to function enter of School class, representing that a student enters the school and then print his/her name etc.Here's the code:
my study.h file ... | here's the solution to this problem
School class:
class School
{
private:
Student* pointer_array[5];
public:
School()//constructor
{
cout << "A New School has been created!" << endl;
};
~School(){//destructor
cout << "A School to be destroyed!" << endl;
};
void ... |
64,793,676 | 64,793,740 | big ints with boost : too large to be represented in any integer type | I think i don't get something.
Is the class cpp_int from boost::multiprecision supposed to hold integers as big as one want ?
Let's say i want to store the following ridiculously big integer. How am I supposed to do it ?
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
cpp_int n = 99... | As detailed in the documentation, you need to construct with a string:
cpp_int n{"999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999"};
See https://www.boost.org/doc/libs/1_74_0/libs/multiprecision/doc/html/boost_multiprecisi... |
64,793,874 | 64,793,892 | " not captured " Error in std::all_of() C++ | When I use value in all_of pred function it works but when I use variable it gives error. Whyy??
#include <iostream>
#include <algorithm>
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> a{1,2,3,4,5,6,7};
int x=10;
if(std::all_of(a.cbegin(),a.cend(),[](int i){return i< x; }))
... | You need to capture your variables inside your lambda:
if(std::all_of(a.cbegin(),a.cend(),[x](int i){return i< x; }))
// ^ here
This captures x by value.
|
64,794,213 | 64,797,044 | I get a "Debug assertion failed" error after entering the username in my TCP_Client program | I am currently a student at Automatics and Applied Informatics. I have a project from Computer Networking, in which I need to make a chat application with the help of threads. Since now I made the receiving part of the connection for the server and made the client, but I get a debug assertion failed error when I run th... | The reason for the debug assertion failed error is as John said, you did not set the size of vector <char*> username, so you cannot directly set the value in the vector through assignment.
But the reason why you output garbled characters is that the bytes you read exceed the number of bytes actually returned.
According... |
64,794,265 | 64,794,296 | How to declare a global-scope function a friend to a namespaced class? | The following code defines class Foo in namespace Namespace.
// main.cpp
#include <csignal>
namespace Namespace
{
class Foo
{
private:
void doSomething() {};
friend void func( union sigval );
};
}
static Namespace::Foo foo;
void func( union sigval sv ) {
(void)sv;
foo.doSomething();
}
I would like to make ... | You can reference the global scope with just ::. So your friend declaration can be:
friend void ::func( union sigval );
But don't forget to forward declare the function before you reference it in the class!
So in the global scope you'll need:
void func( union sigval );
Before the class declaration.
Compiled example: ... |
64,794,519 | 64,794,620 | How to put a word into a var | I would like to set a program that ask personnal information to a "customer", and this code need to store a name and a surname in a structure contening al the var.
But at the output it shows me a number.
#include <iostream>
using namespace std;
//DECLARATIONS
struct dates {
int emb_date;
int post_date;
};
struct in... | You have to change the data type of nom and prenom in the struct info. The type int represents numbers. Strings (or words) are represented by std::string in C++:
struct info {
std::string nom;
std::string prenom;
};
If I make that change to your code and I enter my name, I see it in the output.
|
64,794,608 | 64,794,802 | Typename and variable in templates | I want to do structure with some type and with ability to use another comparator somewhen.This way of do template is not work.How I can do it correct?
template<typename T, typename Comparator = std::less<T>>
struct list_heap{};
bool min(int &a, int &b){return a<b;};
int main(){list_heap<int>r;list_heap<int, min>rr;retu... | min is a name of a function, not a type. The type of min is bool(*)(int&, int&).
You can initialize your struct by giving the full type name:
list_heap<int, bool(*)(int&, int&)> rr;
//or something that bool(*)(int&, int&) will be convertible to:
list_heap<int, std::function<bool(int&, int&)>> rr;
Or by utilizing declt... |
64,794,625 | 64,794,730 | Variadic lambda vs variadic template function : stricly equivalent? | Consider this code snippet
#include <chrono>
auto wrapAndCallLambda =
[] (auto fn, auto &&... params)
{
const auto start = std::chrono::system_clock::now();
auto result = fn(std::forward<decltype(params)>(params)...);
const auto end = std::chrono::system_clock::now();
const auto elapsed = end - start... | wrapAndCallLambda is an actual object, whereas wrapAndCall is a template.
This means that you can pass wrapAndCallLambda directly to other functions, and you have to either explicitly pass &wrapAndCall<fn_type, arg1, arg2, ...>, or wrap it into another lambda which forwards its arguments.
This also means that you canno... |
64,794,649 | 64,795,244 | Is there a way to consistently sort type template parameters? | I have a class taking several template parameters :
template<typename... ELEMENTS>
class MyContainer;
By definition, MyContainer<A, B, C> is a different type than MyContainer<B, A, C>.
But in this case, I would like to avoid this: MyContainer<B, A, C> should be considered the same than MyContainer<A, B, C>.
So I thoug... | As mentioned in the comments, to sort the types, you need a constexpr predicate. This could be manually assigning each type a static constexpr value which you can then compare. If that's not good enough, and you are using GCC, Clang or MSVC, you can use this to get a constexpr comparable value for a type.
Using that as... |
64,794,705 | 64,795,752 | How to pass C++ function as callback to Python? | I am using the Python 3 C API to interface with some Python code.
I have instantiated a Python object from C++ using PyObject_Call and I have been able to modify some of its attributes using PyObject_SetAttrString. One the attributes I would like to modify is a callback function, how can I instantiate a Python object f... | What you need to do is to create a Python object which is callable, and when it is called, it ends up calling a function implemented in C (or C++).
I would implement a new class, as specified in Python Type Objects docs. It may implement any kind of constructor etc. you may need, but most importantly for this purpose, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.