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 |
|---|---|---|---|---|
67,469,811 | 67,470,196 | Seperate items by 3 in for loop | I want to display <row></row> for each of 3 items in loop, I am having issue with this.
Expected output:
I am getting this now for 3,6,9.. items
<?xml version="1.0"encoding=\"ISO-8859-1"\?>
<results>
<row>
<field>1</field>
<field>2</field>
<field>3</field>
</row>
<row>
<field>4</field>
<field... | Good trick with trailing delimiters I learn is to put them AT THE START OF THE LOOP. Pseudocode, that you will use many times in your life:
array<x> someValues;
endDelimiter = ",";
for(each value of values) {
if(NOT firstIteration)
print(endDelimiter);
print(value);
}
In your case, you also have a delimiter... |
67,470,217 | 67,470,742 | Let virtual method accept any Qt container type as input paramter | I have two graph classes: DirectedGraph and DirectedBreakableGraph. DirectedBreakableGraph inherits from DirectedGraph, and provides the ability to temporarily break edges, meaning that they should not be traversed, even though they are still part of the graph. This way cycles in the graph can temporarily be resolved.
... | With type erasure, you might do something like:
template <typename T>
struct IGenerator
{
virtual ~IGenerator() = default;
virtual void reset() = 0;
virtual const T* value_and_next() = 0;
};
template <typename Container>
struct Generator : IGenerator<typename Container::value_type>
{
Generator(const Co... |
67,470,470 | 67,476,533 | Concepts causing compiler bugs in msvc and clang? | I have the following code:
#include <variant>
template <typename T>
struct S{};
using Var = std::variant<S<int>, S<float>>;
template <typename T>
concept VariantMember = requires(Var var) { std::get<T>(var); };
void foo(VariantMember auto x) {}
void foo(auto x) {}
void bar()
{
foo(S<int>{});
foo(S<char>{})... | First, your S template is noise. Deleting it.
using Var = std::variant<int, float>;
template <typename T>
concept VariantMember = requires(Var var) { std::get<T>(var); };
template <int = 1>
void foo(VariantMember auto x) {}
template <int = 2>
void foo(auto x) {}
void bar()
{
foo(int{});
foo(char{});
}
we ... |
67,470,591 | 67,479,274 | C++: Find out type of custom class at runtime | I want to create a multimap that maps several bitmaps to their specific char. For latin chars there are more bitmaps (because of font size). Also I need to store chinese chars. There are different fonts (called meg5, meg7, _china01). meg-family fonts are used for latin letters and china01 is used for chinese letters. I... | I think you have a possible option if you don't mind adding some helper functions:
class Bitmap {
...
public:
virtual std::string name() const = 0;
};
...
class Meg7 : MegFamily {
...
public:
std::string name() const override { return "Meg7"; }
};
Then (like some of the other comments have suggested)... |
67,470,861 | 67,471,481 | How to get floating-point literals's locations in source code in C/C++? | I would like to write a function whose input is a piece of C/C++ code,
and whose output is the exact of locations of floating-point
literals. Preferred implementation languages are Java or Python, although
this question is language-agnostic.
Example input program:
#include<stdio.h>
#include<string.h>
int main() {
f... | You may be looking for something like Kythe, it is a tool Google build to index and search their source code.
As I understand it (I have only seen a presentation, not worked with the tool myself), it is build on top of LLVM(?) and uses the compiler to build and extract a graph of the code. This then enables somebody to... |
67,470,900 | 67,470,992 | Is it possible to have multiple operator& in a class? | I was trying to express a interface where two interfaces composite the same thing, and inherited (single inheritance) by the implementation. The idea is composition over inheritance from the interface class itself. It is something like this:
class A_interface;
class B_interface {
public:
B_interface(const B_interfa... | Literal overloading requires an argument to overload on, but this is the unary operator&. You seem to want to overload on the return type, not the argument.
For that, you need to return a proxy type which has implicit conversions to both A_interface* and B_interface*. These need to be members of the proxy, since you ob... |
67,471,352 | 67,471,879 | Line 1034: Char 9: runtime error: reference binding to null pointer of type 'int' (stl_vector.h) | I was solving the leetcode question Merge Sorted Array and I am getting runtime error while running the following code on leetcode
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume ... | This:
k = m + 1;
Makes it skip the slot at k[m] and also makes the for loop access nums1 out of bounds since k will reach 6 and nums1[6] is out of bounds.
Make it:
k = m;
Demo
Note: Errors of this kind are easy to find if you use a debugger or even by adding print outs in your code so you can see the values of the in... |
67,471,458 | 67,928,526 | Can't read export directory properly | I'm trying to read export directory of a loaded module. The following program works as a 32-bit binary, but crashes as a 64-bit file.
All pointer is 64bit and I'm not sure the differences here, does anyone know what's wrong?
#include <windows.h>
#include <iostream>
#include <dbghelp.h>
#pragma comment(lib, "dbghelp.lib... | A DWORD is 32 bit and not enough for 64 bit. Change it to DWORD_PTR if you need pointer size
PULONG Names = (PULONG)((DWORD_PTR)hModule + ExportDirectory->AddressOfNames);
|
67,471,510 | 67,471,726 | Class object deleting after post increment | I have a Weather class. So let's say I create an object of that class let's say Weather object; after that I have created pre and post increments to manipulate the temperature of that weather. So when I do ++object; the temperature increments by one perfectly, but when I do object++; the destructor is called, my point... | Try something like this and you can avoid all copy constructors and destructors.
class Temp {
double airTemperature;
};
class Weather {
public:
Weather(std::shared_ptr<Temp> tempPtr)
: ptr(tempPtr){}
std::shared_ptr<Temp> ptr;
Weather Weather::operator++(int) {
Weather temp = *this;
... |
67,471,519 | 67,510,619 | OpenCV destroyWindow() not working with multiple windows | I am using openCV library to open and display multiple images. I am doing this with multiple windows created in order to display each image. In order to achieve display of multiple windows at the same time, I am using waitKey() only after the last image.
cv::namedWindow("Window1");
cv::imshow("Window1", myImage1);
cv:... | I have reached a solution by adding startWindowThread() before adding each of the windows.
An important thing to note is also that I have built openCV using GTK option, so my solution is tested only on GTK not on others.
startWindowThread() is used only with GTK as noted here: https://github.com/opencv/opencv/issues/75... |
67,471,862 | 67,472,046 | Passing a function template as a function argument in C++ | Suppose I have a template function that takes an integer as the template argument as follows:
template <int i> void f(int x) {...}
Now I want to write another function that takes the function f as an argument. However I do not know how to achieve this. For example, consider the following wrong code (that can not be co... | You can emulate that with a callable class:
template <int i>
struct f {
void operator()(int x) {
// ...
}
};
template <template <int> typename T>
void g(int i, int x) {
if (i == 0)
T<0>{}(x);
else if (i == 1)
T<1>{}(x);
//...
}
int main() {
g<f>(10, 12);
}
Could also do the same with a name... |
67,472,328 | 67,472,403 | Not able to find run option in C++ - VS Code | I recently started programming in C++ in VS Code. I am not able to find the run option to run my code, neither in the menu that shows on right-click, not the Code Runner Run button on the top left.
But if I make a python file (.py) surprisingly I am able to locate both of these in their respective places.
No code runne... | I'd suggest you to try Ctrl + Shift + D, since this works for me for bringing up Run view.
Also, if that doesn't work, I would like to suggest refering onto this page
|
67,472,506 | 67,472,716 | How to create ranges from two iterators | Am new to using c++20 ranges. One question I have is if you have two iterators into a vector how do you create a ranges view from them ? Range would start at first iterator and end 1 before the second iterator.
| std::ranges::subrange allows combining together an iterator and a sentinel into a single view.
For example:
#include <iostream>
#include <vector>
#include <ranges>
int main()
{
std::vector v = {1, 2, 3, 4, 5};
std::ranges::subrange w(v.begin(), v.begin() + 2);
for (auto i : w)
std::cout << i <<... |
67,473,128 | 67,473,400 | Using exe or DLL for calling program from another program | I have a big program A that at some point calls my (big) program B. Program B is called only once in Program A. At the moment Program B is an executable Program (B.exe - compiled C++-Code).
Somebody proposed using a DLL of Program B instead of using the executable.
Are there any advantages in using a DLL ( like securi... |
Are there any advantages in using a dll ( like security, size, etc)
No. As a matter of fact, if you're looking at things like security, size, etc. using a DLL makes things worse. When you load a DLL, everything happens inside the loading process' address space. So any bug inside the DLL directly affects the rest of t... |
67,473,179 | 67,473,505 | Deduce template parameter from concept | I'm learning templates and concepts. I'm trying to make a concept for types that are derived from a class, but this class is a template.
template<typename T>
struct CAA{};
template<typename T, typename T2>
concept DerivedFromAA = requires() {std::derived_from<CAA<T2>,T>;};
Is it possible to use such concept in a func... | A template is not a type.
So if CAA is a template, then CAA<int> would be a type.
A type can't be derived from a template, only from another type. This means that the check has to be done on the type, not the template.
If you on the other hand want to deduce the inner type of aa, that can be done.
#include <concepts>
... |
67,473,658 | 67,473,874 | How to downcast shared_ptr without std::static_pointer_cast in C++? | we use EASTL and I can't use std::static_pointer_cast.
I receive a pointer to base class in my function and don't know, how to correctly cast it:
switch (command.code)
{
..
case CommandCode::firstCase:
firstCaseFunction(std::shared_ptr<firstCaseType>(static_cast<firstCaseType*>(command.context.get()... | std::shared_ptr<firstCaseType>(static_cast<firstCaseType*>(command.context.get()))
This extracts a non-owning raw pointer from context's ownership network, and passes it to a new std::shared_ptr as if it were owning. The solution is to use std::shared_ptr's aliasing constructor (overload #8 here):
std::shared_ptr<firs... |
67,473,818 | 67,474,004 | valgrind: Multiple std::vector::resize calls | I have been tracking down an off-by-one issue in a large C++ codebase. For some reason, I cannot understand the following Valgrind behavior. Could someone please shed some light here?
Code is:
% cat foo.cxx
#include <cstring>
#include <string>
#include <vector>
int main() {
std::vector<char> v;
#ifdef RESIZE9
v.re... | While I can't confirm this as a complete (cross-platform) 'solution', adding a line to show the actual capacity of the vector after the resize operation(s) may shed some light:
#include <cstring>
#include <string>
#include <vector>
#include <iostream>
//#define RESIZE9 1
int main()
{
std::vector<char> v;
#ifd... |
67,473,824 | 67,488,111 | C++ [] index operator overloading | Base.h
#pragma once
class Base {
protected:
std::string name;
public:
Base() {
//something
}
Base(std::string name) {
//something
}
std::string getName() {
return this->name;
}
void setName(std::string name) {
this->name = name;
}
};
Derived1
#prag... | operator[] should be a non-static member function with exactly one parameter. Template functions where the template parameter is used as the return type do not work, because the standard invocation of foo[x] does not allow the compiler to infer the template type.
To invoke your templated operator, you'd need to do
foo.... |
67,474,123 | 67,474,461 | Questions about the ownership transfer of unique_ptr | For the following code:
#include <memory>
#include <iostream>
#include <vector>
using namespace std;
struct pm
{
pm() : a(make_unique<vector<int>>(1, 10)){};
unique_ptr<vector<int>> a;
};
struct parms
{
parms() : a(make_unique<pm>()){};
unique_ptr<pm> a;
};
class test
{
public:
test() : p(make_u... | Your method getParams() transfers ownership to the caller.
unique_ptr<const parms> getParms()
{
return move(p);
}
Member is moved to the return value and now the caller owns the pointee. You are not storing the returned value here:
cout << t->getParms()->a->a->at(0) << "\n";
Though, even if you did, t does not ow... |
67,474,650 | 67,474,875 | Using SFINAE to detect if compiler supports std::atomic<std::shared_ptr<>> or not | As you may know, even though C++20 added std::atomic<std::shared_ptr<T>> specialization to the standard, most compilers does not support it yet. I was wondering if I can detect whether compiler supports this specialization or not using SFINAE.
I tried to write a code like this:
template<typename T, typename U=void>
str... | Unfortunately, I do not think it is ever possible with SFINAE. The checks are happening inside STL code with static_assert on the type within std::atomic<>, so overload is always viable for SFINAE. It's just that later during the game the static_assert fires.
This is not SFINAE-friendly technique, unfortunately. My rea... |
67,475,184 | 67,475,335 | Command Prompt Input and Output | I want to take data from 'input.txt' to run 'main.exe' and then save the result of that program with this data to 'output.txt'.
If possible, I would like to write wwith form <input.txt> <output.txt>.
| First you need to compile your c++ program, then run it with the two parameters. See cplusplus.com for some tutorials on file in and file out and the resource for taking in command line arguments: https://www.geeksforgeeks.org/command-line-arguments-in-c-cpp/
|
67,475,399 | 67,475,652 | Meaning of `{}` for return expression | I found by accident that the following compiles:
#include <string>
#include <iostream>
class A{
int i{};
std::string s{};
public:
A(int _i, const std::string& _s) : i(_i), s(_s) {
puts("Called A(int, const std::string)");
}
};
A foo(int k, const char* cstr){
return {k, cst... | return {k, cstr}; means that {k, cstr} is the initializer for the return value. Also, it indicates "return an object of the function's return type initialized with k and cstr, which means that the exact behavior depends on the returned object's type".
The return value can be initialized in two different ways:
return A... |
67,475,705 | 67,476,104 | Is it possible to use a c++ library from an older c++ version? | So I'm trying to use JSON as a file format for my c++ project. But I cant find a library for C++17. There are a few(nlohmann/json,RapidJSON) for older versions, such as C++11 but I don't know if it's possible to use an older one. Can I do this?
| C++ versions are largely backwards compatible with prior versions. Any incompatibility are (usually) done for a specific purpose and with some degree of deprecation or the like.
So broadly speaking, a C++11 library (header-only or compiled) will compile under a C++17 compiler. There are times when this will fail, but t... |
67,476,215 | 67,476,570 | How to efficiently identify string commands? | Given a series of commands and very unique code that must be run for each:
if(cmd == "cmd.setBoosterRocket")
...
else if(cmd == "cmd.windSales")
...
else if(cmd == "cmd.selfDustruct")
...
else if(cmd == "cmd.unleashHounds")
...
How might this be optimized? Be put into a switch statement, that is?
I co... | One possible approach is tokenization: make an enum type and a dictionary. This way you take advantage of the switch (in a more programmer and compiler friendly way than hard-coded hashes) and have just logarithmic complexity.
enum Command {SET_BOOSTER_ROCKET, WINDSALES, ETC};
const std::map<std::string, Command> comma... |
67,476,400 | 67,476,600 | How to correctly input binary from a file | I am trying to make a hex editor and I want to read from a file. I am using fsteam for this. I am still not very familiar to this library, so I am not sure what I did wrong.
What I am trying to do is to read the first 8 bits(1 byte) of the file as binary and then convert it into hex and display it. My problem is that I... |
I want to read 8 bits or 1 byte. And I want to input it in binary.
So, then simply read() 1 byte. The code you have shown is read()'ing 8 bytes instead. A char is 1 byte, and you are creating a vector with 8 chars in it.
Try this instead:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
usi... |
67,476,879 | 67,476,925 | Creating a file with variable name in c++ | so I want to create a file but the name of it will be dependent on the user input e.g. if the user types "shrek" the file must be named "shrek.txt". Thats what I came up with but it doesn't work.
int main(){
ofstream file;
string name = "abc";
file.open(name + ".txt");
file.close();
}
| I guess you are using an old C++ standard. If that's the case, fstream::open won't accept a std::string, only a C string (char*). You can use c_str in your string to obtain a const char* that will be accepted:
int main(){
ofstream file;
string name = "abc";
string file_name = name + ".txt";
file.open(f... |
67,477,384 | 67,477,585 | is setw() and "\t" the same thing? | Is setw() and "\t" the same thing tho?
And are they similar to "space" too?.
Can I use setw() in the place of "\t" or would it result in a completely different output?
| They have almost nothing in common.
std::setw(int n) set the width of the next element that goes into the stream. So if you have things like:
std::cout << "Hi," << std::setw(12) << "there!";
This would print:
Hi, there!
^^^^^^ <- 6 empty spaces were made here to fill the width
If you set the width to be long... |
67,477,402 | 67,477,684 | Calling C++ Functions in MASM Linker Error | So I am currently trying to run external C++ functions from an assembly program. I have assembly programs running properly, but I keep getting a linker error saying:
"Error LNK2019 unresolved external symbol _testFunc@0 referenced in function __main@0"
I'm wondering why I am getting this error, I assume it's because I'... | You declare .MODEL FLAT, stdcall. You should define the function
extern "C" __stdcall void testFunc()
|
67,477,403 | 67,477,616 | Making an index sequence tuple | Is there a way to create index tuple with compile-time known size like
std::tuple<int, int, ...> tup = make_index_tuple(100); // -> tup == (0, 1, 2, ..., 99)
Maybe somehow using std::make_index_sequence?
There is a kind of similar question about uninitialized tuple type but with structures involved
EDIT
I am trying ... |
pass a sequence of ints 0, 1, 2, 3, ..., 99 to [function arguments]
You don't need tuples. Do this:
template <std::size_t ...I>
void foo(std::index_sequence<I...>)
{
format("foo", I...);
}
int main()
{
foo(std::make_index_sequence<42>());
}
If you insist on std::apply, it understands std::array out of the ... |
67,477,452 | 67,477,500 | Using reinterpret_cast while respecting the strict aliasing rule | I know this code would cause undefined behaviour due to breaking the strict aliasing rule,
as we are point to the same memory location with a type int and float and dereferencing it, code could break after compiler optimizations take place:
int main(){
int a = 5;
float f = *reinterpret_cast<float*>(&a);
return (int... | Yes, it will still break the strict aliasing rule, as you will be trying to dereference a pointer to float, but float object never lived at this address.
Luckily, in C++ 20 you can use std::bit_cast for this purpose. Pre-C++20 you can just cast :), as even though this is UB, there is no sane compiler which would produc... |
67,478,033 | 67,478,824 | How should I specify the language in a CMake project that optionally supports CUDA? | I am adding optional CUDA functionalities to a CMake project. Right now, the project is organized as an executable and some static libraries. In the top level CMakeLists.txt file there is a project statement like this:
project (my_project LANGUAGES CXX)
And below there an option statement adds the parameter to regulat... | Use the enable_language command, it's pretty self-explanatory:
cmake_minimum_required(VERSION 3.20)
project(my_project)
option(CUDA_FEATS "Set to On to use CUDA features" ON)
if (CUDA_FEATS)
enable_language(CUDA)
endif ()
After that point, if CUDA_FEATS is true, then you certainly have enabled the CUDA language, ... |
67,478,051 | 67,478,104 | Checking container size in same "if" statement as reading from it | Let's say I have a vector of unknown length.
I want to check if there is a value at vector[3] that is equal to x.
I have to first check if the vector has a length of at least 4.
if(vector.length()>=4)
{
if(vector.at(3) == x)
// Do something
}
My question is: Is it correct to write the same code like this:
if(... | Yes, these are equivalent.
The logical AND operator && has what is referred to as short circuit behavior. If the left operand evaluates to false (i.e. 0) then the entire expression is false and the right operand is not evaluated.
|
67,478,122 | 67,478,620 | text-based battle system in C++ not working, not sure why | So I tried to make a little text-based battle system, but it kind of broke... I was wondering if someone could help me figure out why? I tried to use variables and simple math algorithms to make it as easy to run as possible, but it just keeps resetting after player 2's turn. It also broadcasts the "You Can't Heal!" (... | I fixed your code, but remember a few things next time:
Remember to use good formatting
main() cannot be called in your code
== is for comparisons and = is for assignments.
Note the use of reference parameters in the turn function.
Don't stop learning. :)
#include <iostream>
using namespace std;
void turn(int playe... |
67,478,179 | 67,478,255 | Less Than Overload C++ | struct nodeStructType {
char letter;
int count;
};
struct node {
nodeStructType data;
node* left;
node* right;
bool operator <(const node* comp)
{
return data.letter < comp->data.letter;
}
};
typedef node* nodePtr;
Hi! I'm working on a project and am overloading the < operat... | Declare the operator like
struct node {
nodeStructType data;
node* left;
node* right;
bool operator <(const node &comp) const
{
return data.letter < comp.data.letter;
}
};
And call it like
if ( *a < *b)
{
printf("yay!");
}
Or
if ( a->operator <( *b ) )
{
printf("yay!");
}
Ot... |
67,478,541 | 67,482,366 | Compare memberwise parameter packs of different lengths | template <int... ValuesOrSentinals>
struct type {};
template <typename T, typename U>
struct are_compatibles;
template <int... TVals, int... UVals>
struct are_compatibles<type<TVals...>, type<UVals...>>
: public conjunction<bool_constant<sizeof...(TVals) == sizeof...(UVals)>,
bool_constant... | Another way, with Enabler:
template <int... ValuesOrSentinals>
struct type {};
template <typename T, typename U, typename Enabler = void>
struct are_compatibles : std::false_type{};
template <int... TVals, int... UVals>
struct are_compatibles<type<TVals...>, type<UVals...>,
std::enable_if_t<siz... |
67,478,979 | 67,479,244 | texture is not a template | I am using CUDA in Microsoft Visual Studio 2019 for this code:
#include <cuda_runtime.h>
#include <cuda_runtime_api.h>
#include <cuda.h>
#include <device_launch_parameters.h>
#include <fstream>
#include <cstddef>
texture<float, 2, cudaReadModeElementType> texRef;
It gives me texture is not a template error, and there... | It's because your project is trying to compile your file with Cl, not nvcc.
Replace in your .vcxproj project file
<ClCompile Include="myfile.cu" />`
by
<CudaCompile Include="myfile.cu" />
If you updated cuda, you also need to update your ExtensionSettings in project files:
<ImportGroup Label="ExtensionSettings">
... |
67,479,139 | 67,479,167 | Specializing a Template Alias Inside a Template | I have a matrix class as follows.
template <typename T, std::size_t M, std::size_t N>
class Matrix
{
std::array<std::array<T, N>, M> data_;
};
I want to create a row alias inside this matrix for ease similar to
template <typename T, std::size_t M, std::size_t N>
class Matrix
{
template<>
using row = std::array... | This compiles for me:
#include <array>
template <typename T, std::size_t M, std::size_t N>
class Matrix
{
using row = std::array<T, N>;
std::array<row, M> data_;
};
This is not really specialization, just an ordinary using alias definition.
|
67,480,868 | 67,481,848 | malloc error while finding the second maximum element in an array | I encountered a specific malloc error while trying to find the second most maximum element in an array. This error did not pop while finding my element in an array which I created statically , so may be possible that I have made an error while dynamically creating the array. Can someone look into this and guide me plea... | As was said by @RetiredNinja to correct your mistake replace new int(size) with new int[size], also don't forget to always delete allocated pointers.
As already said by others if you're using C++ then best way is to use std::vector instead of manual new/delete, it manages all memory allocations automatically and saves ... |
67,481,420 | 67,481,589 | Why does it not let me execute this? | I'm new to C++ (1 week) , coding in general and I'm wondering how I can make this work, because I get errors whenever I compile & run. The idea is that the user inputs a gift code, and the program automatically opens it in a tab.
https://i.stack.imgur.com/4IKkm.png
#include <iostream>
#include <windows.h>
using namespa... | Adding your code and errors in your question instead of just a pic would be a great idea.
Anyway, To add strings together you must use the + sign site = "http//..." + codes
Not sure if there is any other errors but I highly recommend to indent your code to make it easier to read
|
67,481,996 | 67,497,922 | Custom op is replaced by another ops | I need to use Conv1D layers in a speech recognition model to run on microcontrollers. Since TFLM doesn't support Conv1D I thought to use the keras layer class: after that I tried to define and register the op to be supported by TF Lite.
However it seems that my op is replaced by another ops. How can it be possible?
| TFLite supports Conv1D through wrappring the existing Conv2D op with a Reshape op already. Did you try the conversion? I think your case is already supported by the TensorFlow Lite builtin op set. If not, please file a feature request at the TensorFlow github.
|
67,482,142 | 67,483,598 | How to divide Pixels in Subpixels? | I am Developing an OS, I have to Subdivide Pixels into Subpixels, I am Using GOP Framebuffers https://wiki.osdev.org/GOP ,
Is it Possible to Subdivide Pixels in GOP Framebuffers?
How can I do it?
I Found these only on Internet :
Subpixel Rendering : https://en.wikipedia.org/wiki/Subpixel_rendering
Subpixel Resolution :... |
How can I Implement It in My OS?
The first step is to determine the pixel geometry (see https://en.wikipedia.org/wiki/Pixel_geometry ); because if you don't know that any attempt at sub-pixel rendering is likely to just make the image worse than not doing sub-pixel rendering at all. I've never been able to find a san... |
67,482,222 | 67,482,404 | I want to combine characters to make a string | #include <stdio.h>
#include "serialcomm.h"
#include <windows.h>
#include <process.h>
#define BUFF_SIZE 256
int main()
{
CSerialComm serialComm;
BYTE buff[BUFF_SIZE] = { 0, };
int op = 0;
int port = 0;
int size = 0;
int size2 = 0;
int restart = 0;
char port_s[20] = "";
char send_s... | UPDATE: As per cplusplus.com, perhaps a more reputable source, it looks like this is your best option:
#include <string>
std::string s = "[ " + std::string(buff, size) + " ]";
As per geeksforgeeks, it looks like this is your second best option:
// converts character array
// to string and returns it
string convertTo... |
67,482,325 | 67,482,382 | How to set Material Dark Theme in Qt QML (QtQuick 2)? | I want to set Material Dark Theme for my application in QtQuick2.
I followed this official docs:
https://doc.qt.io/qt-5/qtquickcontrols2-styles.html
And applied one line in my main.cpp (changed nothing else from auto-generated code):
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickStyle>
#i... | A possible solution is to use the environment variable QT_QUICK_CONTROLS_MATERIAL_THEME (See https://doc.qt.io/qt-5/qtquickcontrols2-environment.html):
qputenv("QT_QUICK_CONTROLS_STYLE", QByteArray("Material"));
qputenv("QT_QUICK_CONTROLS_MATERIAL_THEME", QByteArray("Dark"));
QGuiApplication app(argc, argv);
You can ... |
67,482,683 | 67,482,986 | Run 2 threads indefinitly with join | What's the best practice to achieve this :
1 - Thread for gathering data
2 - Wait for (1) to finish and render data
And those, indefinitely
while (true) {
thread tGatherData(getData); // Get data
tGatherData.join(); // Wait for data
thread tRender(render); // Render data
... | If you don't want to create thread on each iteration of your loop, you may want to start 2 threads: one for gathering information, second for printing it, and place your loop in both threads(you should remember about synchronization)
For example here I've created two threads: first for reading from console, second for ... |
67,482,784 | 67,513,801 | Error : Invalid Character '(' in mnemonic | Hi I am trying to compile the below assembly code on Linux using gcc 7.5 version but somehow getting the error
Error : Invalid Character '(' in mnemonic
bool InterlockedCompareAndStore128(int *dest,int *newVal,int *oldVal)
{
asm(
"push %rbx\n"
"push %rdi\n"
"mov %rcx, %rdi\n" // ptr to dest -> RDI... | The question here was about Invalid Character '(' in mnemonic which the other answer addresses.
However, OP's code has a number of issues beyond that problem. Here's (what I think are) two better approaches to this problem. Note that I've changed the order of the parameters and turned them const.
This one continues t... |
67,483,415 | 67,483,700 | How to create n lists of random sizes with random numbers? | The problem is the following:
I want to create a k amount of lists, where k is inputted by the user. The size of each list will be a random number from 100 to 200. Then, each list will be filled with random numbers ranging from 0 to 50.
So for example if the user inputs 2 as the number k of lists that will be created, ... | I'd suggest using std::generate to generate values, and store them in a std::vector
#include <iostream>
#include <random>
#include <functional>
#include <vector>
#include <algorithm>
int main() {
int k;
std::cout << "What is the number k of lists?" << std::endl;
std::cin >> k;
//I googled this part t... |
67,484,674 | 67,484,872 | Problem with a parsing function (int to const char*) | I needed to create a parsing function so i wrote this:
inline const char* parse(const int &arg)
{
return std::to_string(arg).c_str();
}
Looks pretty rational - at least to me - but when i try to see the value of this function with std::cout instead of an integer value i get some random ascii characters.
So i trie... | inline const char* parse(const int &arg)
{
return std::to_string(arg).c_str();
}
A new string local to the function parse is created from the std::to_string(arg), and you get it's internal string with c_str. c_str of course returns a const char *, but now this creates an issue. The string is still local to the fu... |
67,485,194 | 67,509,255 | Calling __global__ CUDA functions from regular C++ code | I am adding a library using CUDA to a C++ project. As of now what I'm doing is to import a .cuh (or .h) header from a .cpp file, and a .cu file implements the functions in this header. But this header contains the declaration of the methods, which have the __global__ modifier that the regular C++ compiler complains abo... | I solved by creating a header with wrapper functions that are then implemented in a .cu file like this:
__global__
void real_foo(int number, int *out) {
*out = number * 2;
}
inline int foo(int number) {
int* x;
cudaMallocManaged(&x, sizeof(int));
real_foo<<<1,1>>>(number, x);
cudaDeviceSyn... |
67,485,524 | 67,703,410 | Gtest in VSCode, C/C++ intellisense shows errors | I have an issue, which I guess is caused by the Microsoft C/C++ plugin. Intellisense is showing errors at Google Test functions, but there are no actual errors (tests compile and run without any problem).
When I hover over the functions with these red error squiggles, it expands to the functionality, F12 (go to definit... | Solved it by editing c_cpp_properties.json:
"includePath": [
"${workspaceFolder}/**",
"${workspaceFolder}/Tests/packages/Microsoft.googletest.v140.windesktop.msvcstl.static.rt-dyn.1.8.1/build/native/include/**"
],
|
67,485,960 | 67,488,098 | Qt: Safe parsing of Windows format data under Linux | I have a Server-Client application in which JSON data is send between those. The Client has a Linux and a Windows version, while the Server application runs under Linux.
The Linux Client communicates just find, but I have problems with the Windows Client.
The problematic JSON data contains a text field with an apostrop... | I think windows client sends strings encoded in CP1251 or CP1252. And json decoder expects utf-8.
Maybe source code is not in utf-8 and has string literals. Qt4 has QTextCodec::setCodecForCStrings. Qt5 assume string literals encoded in utf-8.
$ echo -n "β" | iconv -f utf-8 -t cp1251 | xxd
00000000: 92
$ echo -n "β" | x... |
67,486,013 | 67,486,156 | How can I use method of which parameter is vector? | #include <iostream>
#include <iomanip>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
class Shape{
protected:
int _r;
int _w;
int _h;
public:
Shape(double r) : _r(r) {}
Shape(double w, double h) : _w(w), _h(h) {}
virtual double area(vector<Shape *>){
cou... | Polymorphism does not work with concrete classes!
By declaring vector<Shape> collection;, you declare a vector of Shape, not of Circle, Triangle or Rectangular. You probably want collection to be of type vector<Shape*> to be able to utilize polymorphism.
Another issue with your code is that you don't pass collection, w... |
67,486,071 | 67,487,169 | How to get value from nlohmann json | I tried several solutions but none worked. The problem is that I want to retrieve the values of nonce date pass, for the moment with this program I can only read them. Ideally I should be able to store them in a variable. Please let me know if you have any ideas on how to do this. Thanks
using namespace std;
using json... | One possibility is to add a constructor from Json to your class like this:
class sha1info {
public:
sha1info(std::string const& nonce, std::string const& date, std::string const& pass) noexcept
: nonce{nonce}, date{date}, pass{pass} {
return;
}
// Method for parsing class from Json
sha1inf... |
67,486,145 | 67,486,546 | Why is the output of the string 'text2' blank? | 'text1' is a sentence. I want 'text2' to contain the first word of the sentence in 'text1' (all letters before the first space).
The code gets compiled successfully, but, when executed, nothing gets printed on the screen.
Below is the code:
#include<iostream>
#include<string>
using namespace std;
int main()
{
int ... | you can't do text2[k]=text1[i-c] as text2 is empty, you need to resize it first.
#include<iostream>
#include<string>
using namespace std;
int main()
{
int i,k,c;
bool done=false;
string text1,text2;
getline(cin, text1);
for(i=0; i<text1.size(); i++)
{
if(text1[i]==' ' && done==false)
... |
67,486,205 | 67,487,100 | Using std::optional to avoid potentially unitialized variable? | Visual Studio generates spurious "potentially uninitialized variable" for code like:
bool oldValue; // Uninitialized
bool haveValue=false;
for(...) {
...
if (...) {
bool value=...;
if (haveValue && value!=oldValue) {
// Do something
}
haveValue=true;
... | Basically your initial implementation is kind of optional implementation done in place.
I would not be surprised if generated code would be exactly same (with gcc they are not, but very similar and std::optional version looks better, for clang differences are minimal still code for optional looks better).
This change w... |
67,486,877 | 67,491,607 | nlohmann json access nested value by single string | I have a json like :
{
"answer": {
"everything": 42
}
}
Using nlohmann json library in C++, I can access at this nested value like this :
std::cout << my_json["answer"]["everything"];
I'm looking for a way to access it with something like :
std::cout << my_json["answer.everything"];
| It won't be possible to implement this with the syntax j["name1.name2"] you used. Many overloads for operators, including the bracket operators () and [] can only be declared inside a class. Furthermore nlohmann::json has already defined the [] operator to work like j["name1"]["name2"]! This means you would have to mod... |
67,487,421 | 67,492,159 | GDI+ Image::SetPropertyItem not working as expected | I am trying to use SetPropertyItem to set a Date Taken property to a file (click here for MSDN docs description).
I have tried assigning a newly initialized FILETIME to an input image with no success (or error messages). To ensure that it was not an issue with Date Taken, I also tried following this MSDN example to no ... | You code works fine, but you must save the image back, for example like this
...
newImage->SetPropertyItem(propItem);
CLSID clsid;
GetEncoderClsid(L"image/jpeg", &clsid);
newImage->Save(L"Test2.jpg", &clsid);
...
BOOL GetEncoderClsid(const WCHAR* format, CLSID* pClsid)
{
UINT num = 0;
UINT size = 0;
Image... |
67,488,078 | 67,496,994 | Make Visual Studio use different minor version Toolset? | Under "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC", I have different directories such as :
14.16.xxxxx
14.24.xxxxx
14.25.xxxx.
However, I noticed Visual Studio always uses the newest minor version.
Can I set it to use an older minor version of the toolset?
| You can at a solution level. Following this guide:
Download whatever minor versions you need/want.
Optionally, go to your projects properties and add -Bv as an "Additional Options" in the C/C++ β Command Line menu item. This will output the compiler version upon building.
Go to C:\Program Files (x86)\Microsoft Visua... |
67,488,230 | 67,488,431 | Segmentation fault from big arrays | This is a simple code to get an array of a random walk. If I increase the array size anymore it gives me a segmentation fault. I need it to be larger and 2D (like a matrix). How can I do that without getting the error?
#include <iostream>
#include <fstream>
#include <time.h>
using namespace std;
int main(){
sran... | To use such a big array, you will need to use dynamic memory. Large array like that cannot be on the stack, it will overflow the stack.
One of the best tool for that is a std::vector:
#include <iostream>
#include <fstream>
#include <vector>
#include <time.h>
using namespace std;
int main(){
srand (time(NULL));
... |
67,488,266 | 67,488,619 | Use a derived class type as parameter of a base method in C++ | I have the following classes in the following files:
// Tensor.hh
template <class T>
class Tensor {
/* declarations */
}
// Tensor.cpp
#include "Tensor.hh"
// Implementation of Tensor.hh
// Kernel.hh
#include "Tensor.hh"
template <class T>
class Kernel : public Te... | Yes it is possible. In your Tensor.cpp you will have to include #include "Kernel.hh", and in your Tensor.hh you will have to add a forward declaration:
template<typename>
class Kernel;
Usually I would really avoid forward declaring template classes, and I would avoid circular dependencies. Sometimes they are not avoid... |
67,488,294 | 67,490,202 | What do I have to consider when using std::sort with a parallel execution policy? | With C++17, we got Execution Policies.
I am interested in the parallel policies
What do I have to consider when I use std::sort with a parallel policy?
Unlike std::transform or std::for_each, std::sort accesses two elements at the same time. Do I have to take data races into consideration here?
| There isn't anything extra to consider when calling std::sort with an execution policy. It is already UB for your compare to mutate the elements it is comparing.
The implementation is required to ensure there are no data races within any of the functions defined in std.
|
67,488,413 | 67,489,942 | Save results in a .txt file using makefile, but in a relative path | I have a cpp code that prints some data, I want it to save the results in a txt file, but I want it to be in a different directory.
My data tree
|
|--Code
| |--Oscilador.cpp
| |--makefile
|
|--Resultados
| |--(Where I want the txt to be save in)
My make file code is this
Oscilador.x:Oscilador.cpp
g++-10 -o0 ... | Please see the below code which will fix this issue.
Oscilador.x:Oscilador.cpp
g++ Oscilador.cpp -o Oscilador.x
Resultados.txt:Oscilador.x
# Output to Resultados.txt file under Resultados directory which is present one folder behind
./Oscilador.x > ../Resultados/Resultados.txt
rm Oscilador.x
The abov... |
67,488,801 | 67,489,926 | Install conan package without requirements? | Is there a possibility to install a conan package without requirements?
I build a metapackage, which only contains some configurations and depends on other binary packages in the requires section.
Now I want to access only the configurations w/out downloading all dependencies, Is there a possibility to do so?
conan dow... |
Is there a possibility to install a conan package without requirements?
Yes, conan download command. It ignores settings.
conan download downloads a package, but won't install it, e.g. there is no info, where it's downloaded
Not really, it's installed as equal in conan data folder. To obtain any package path, you c... |
67,488,867 | 67,489,769 | Are subclasses that only change the members valid practice? | Lets say I have a class A that has a member of type int.
I have a class B which is a subclass of A.
B is meant to initialize the members to some state and has no other purpose.
#include <string>
#include <iostream>
struct A {
int someInt;
A() : someInt(33){}
};
struct B : public A {
B() {
someInt =... | To answer your question as directly as possible, what you're doing is certainly "valid" in the sense that it will compile and run and produce a correct result. It's probably not the most common way to accomplish this though.
My recommendation for a more idiomatic approach would be to use a common base class and templat... |
67,489,014 | 67,502,471 | wxPython migration from 4.0.7 to 4.1.0: ListCtrl error while event handling | I'm currently migrating from wxPython 4.0.7 to wxPython 4.1.0. This changes the wx version from 3.0.x to 3.1.x.
Tl;dr:
Using a wx.ListCtrl I sometimes get an error when I call event.Skip() inside a wxEVT_SIZE event handler. To Skip() or not to Skip()? (i.e. whats the default event handling for a wxEVT_SIZE and do I nee... | I believe this assert can only be triggered if a handler calls Bind() from its event handler, but skips the event, i.e. pretends that the event wasn't handled at all. In an ideal world, this should be possible and I think the assert is actually over-eager and needs to be relaxed, but for now, if you really need to do i... |
67,489,491 | 67,489,628 | How to implement the below function getValue(m) for multimap in C++ | #include<bits/stdc++.h>
using namespace std;
void getValue(multimap<int,string> &m){
for(auto &mValue : m){
cout<<mValue.first<<" "<<mValue.second<<endl;
}
}
int main(){
int n;
cin>>n;
multimap<int,string> m;
for(int i=0;i<n;i++){
int num;
string str;
cin>>nu... | std::map<int, std::string> is a different type to std::multimap<int, std::string>, although they bear similarities.
The simplest way would to write a similar function:
void getValue(const std::multimap<int, std::string> &m){
for(auto &mValue : m){
std::cout<<mValue.first<<" "<<mValue.second<<std::endl;
... |
67,489,581 | 67,492,158 | Template alias for type trait doesn't work | I'm practicing SFINAE by a simple custom type trait:
#include <iostream>
#include <type_traits>
struct A{ int i, j; };
// Type trait
template<typename T>
struct is_class_A{ static const bool value = false; };
template<>
struct is_class_A<A>{ static const bool value = true; };
// (1)
template <typename T>
std::enabl... | Template variable syntax would be:
template <typename T> const bool is_class_A_v = is_class_A<T>::value;
|
67,489,966 | 67,490,621 | Failed to concatenation with my custom string class | I have nearly finished creating my own custom string class. However, it seems not going well when the program did not return the output that I was expected. In detail:
Input:
string a = "Hello"
string b = "World!"
Expected output:
HelloWorld!
!dlroWolleH
Actual output:
Hello
Here is my code:
#ifndef _STRING
#define _... | Your string does store the terminating null character at s[size - 1].
Then in inconst you take the null character not into account, but pretend that size is number of characters in the string.
char* string::inconst() {
char* t;
t = new char[size + 1]; // why +1 here ?
for (size_t k = 0; k < s... |
67,490,530 | 67,490,620 | Calculating the size of the array gives variable output | I'm calculating the size of the array using following code
int arr[] = {1, 2, 3, 4, 5, 6};
int size = *(&arr + 1) - arr;
This gives me 6 as output. However, when I create a function with the same code, the size becomes -8. What could be the reason for this behaviour.
int sizeArr(int arr[])
{
int size = *(&arr + 1... | It's the way pointer arithmetic works.
An expression of the form
pointer + amount
is, informally speaking at least, evaluated as
pointer + sizeof(*pointer) * amount
In other words, pointer arithmetic adds sizeof units of the type.
In your first snippet, sizeof(arr) is the size of the actual array. But in the function... |
67,491,112 | 67,491,284 | How to read bytes from file to hex string in C++? | I am trying to read a file which contains bytes into a hex string.
std::ifstream infile("data.txt", std::ios_base::binary);
int length = 10;
char char_arr[length];
for (int i=0; i<length; i++)
{
infile.get(char_arr[i]);
}
std::string hex_data(char_arr);
However the hex_data does not look like a hex string. Is th... | You are reading in raw bytes and storing them as-is into your std::string. If you want the std::string to be hex formatted, you need to handle that formatting yourself, eg:
#include <fstream>
#include <sstream>
#include <iomanip>
#include <string>
std::ifstream infile("data.txt", std::ios_base::binary);
const int le... |
67,491,200 | 67,491,304 | Alias for a function of a pointer to an object | I am making a game with a separate map class and a separate renderer class for rendering the map.
Here is a simplified version of what that looks like: (the function I am interested in is renderMap()
#include <iostream>
#include <vector>
class Map
{
public:
Map(int mapSize)
: data(mapSize,3) {} //Initializ... | Instead of calling accessData on each line, simply create a reference and use it for all other lines:
const std::vector<int>& dataPoint = pointerToMap->accessData();
std::cout << dataPoint[0];
Here you create a new variable that is a reference to the vector returned by accessData.
|
67,491,362 | 67,497,912 | How to add SDL2_gfxPrimitives to my visual studio 2019? | I am trying to create a graphics project in visual studio 2019 using SDL2.
I managed to connect it with my visual studio using this tutorial:
https://lazyfoo.net/tutorials/SDL/01_hello_SDL/windows/msvc2019/index.php
I want circles, lines, rectangles etc. as my output, so need SDL_gfx for that. The problem is I cannot c... | As fa as I'm concerned you should link the SDL library and SDL2_gfx Library to your project.
First of all, you should find the files that you have downloaded. And the follow the following steps:
1,Add the path to the header file to the Additional Include Directories(property - >c/c++ -> General -> Additional Include Di... |
67,491,590 | 67,607,253 | unresolved external symbol cuda_library::foo(int) in Visual Studio/CMake | Original question (title: .cu file is processed as a .cpp file in Visual Studio/CMake)
I am trying to add a static library with CUDA code to my C++ project. I have a top level CMakeLists.txt file, a static library that's added from there, and my CUDA-using library that's added from that library (both libraries have the... | I realized that there were two main things keeping this from working:
The inline in the function signature seemed to break it on its own (and at this point I do not care enough about it in my code to not remove it, if someone wants to investigate more on it they're free to do it).
The enable_language(CUDA) has to be i... |
67,491,716 | 67,496,061 | Sorting the array gives erroneous values | I have implemented quick sort in c++. Following is my code .
#include <iostream>
using namespace std;
template <typename T>
void swap(T *a, T *b)
{
T temp;
temp = *a;
*a = *b;
*b = temp;
}
template <typename T>
void PrintArray(T arr[], int n)
{
cout << "---------- Array ----------" << endl;
fo... | @FranΓ§oisAndrieux comments were very useful in finding out the problem.
As he pointed out that j is taking 8 as value which is out of bounds.
To solve the problem
step 1: quick_sort<int>(a,0, n-1); in the int main().
steps 2: knock off the custom swap function
|
67,491,724 | 67,492,582 | How to stop fstream from consuming character escapes? | I'm editing a file, and appending to it. I have a " in there somewhere I'm trying to preserve the escape character for. As this code writes other code, which then gets compiled.
#define EDIT_FILE fstream::out | fstream::binary | fstream::in | fstream::ate
#define REWRITE_FILE fstream::out | fstream::binary | fstream::i... | Are you in need of something like raw string literals?
#include <fstream>
int main() {
std::fstream file("test.txt", std::ios::out);
if(file) {
file<<R"f(\\\\\")f";
}
}
And then yields
\\\\\"
Raw string literals can be created using the syntax R"delimiter(raw_characters)delimiter". In the above c... |
67,491,877 | 67,661,545 | Using non-qtcore libraries on Visual Studio using Qt VS Tools causes LNK2019 | I am trying to use QSoundEffect from QtMultimedia. I have included the file like so:
#include <QtMultimedia/QSoundEffect>
and used QSoundEffect in my project.
When I try to compile my project after this, I get LNK2019 errors:
1>chatwindow.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: __... | For some weird reason, it worked when I manually added Qt5's libpath to library paths and Qt5Multimedia.lib to included libraries manually.
|
67,492,040 | 67,590,159 | How do I get a variable amount of input from cin? | I've been working on a calculator and I am very close to getting it working, but I need to find a way to have the amount of numbers and operators that the user puts in to be up to the user. This is a simpler test version of what I have so far that I need to apply this to. I left out a few things but this is the exact p... | Use getline to get a whole line of input from the user.
Then use that string to construct a stringstream, which you can use your >> on to extract the numbers and single-char operators. But now you get an error when you try to read past the end of the original string. It knows you are done, because it has the complete... |
67,492,436 | 67,493,572 | 1G colors in Windows with C++ MFC | I am using Visual C++ 2019 with MFC, on Windows 10 Home Premium. The video mode is 3840*2160 40-60 Hz (AMD FreeSync) 30 bit/pixel: 10 bit / color part, 1 073 741 824 colors.
I can give colors with COLORREF = unsigned int (32 bits), what is interpreted as
(red | (green << 8) | (blue << 16)), this has only 16 777 216 col... | GDI does not support 10 bit color. You need to use DirectX.
|
67,492,993 | 67,495,823 | Speed problem for summation (sum of divisors) | I should implement this summation in C ++. I have tried with this code, but with very high numbers up to 10 ^ 12 it takes too long.
The summation is:
For any positive integer k, let d(k) denote the number of positive divisors of k (including 1 and k itself).
For example, for the number 4: 1 has 1 divisor, 2 has two di... | largest_prime_is_463035818's answer shows an O(N) solution, but the OP is trying to solve this problem
with very high numbers up to 1012.
The following is an O(N1/2) algorithm, based on some observations about the sum
n/1 + n/2 + n/3 + ... + n/n
In particular, we can count the number of terms with a specific value.... |
67,493,236 | 67,493,772 | C++ template function dependent typename not recognized | In the following mcve:
template <typename T> class Class { public: class MemberClass {}; };
#include <list>
template <typename T>
Class<T> func(const typename Class<T>::MemberClass& start,
const typename Class<T>::MemberClass& finish)
{
Class<T> result; return result;
}
int main ()
{
Class<int... | Quite literally, every possible T that matches your Class has a MemberClass type. The compiler is not going to look inside all of them to find a match, because it'd have to instantiate templates just to see their contents, and it would potentially match too many things. So the langauge simply doesn't look inside like... |
67,493,256 | 67,493,412 | c++ - replace this by new object | Basically I want the this-pointer in foo() to point at a new object which points at *this.
Since I can't change the this-pointer, I am creating a new object which just takes over the array from *this and then empty *this and let it point at the newobject.
struct SomeClass{
int* value;
SomeClass* child;
SomeClass... | In the ~SomeClass() destructor, you need to change:
if(child){
child->~SomeClass();
}
to:
delete child;
There is more to destructing an object then just calling its destructor. The memory used by the object needs to be freed as well. That happens outside of the destructor. The destructor itself doesn't know HOW t... |
67,493,261 | 67,493,300 | Initialized values do not change / C++ | I'm making a program that prints the points and the length of a shape. I initialized points in the constructors of the subclasses and the length in main but still it doesn't show the initialized values that I set.
This is my result:
This is a Shape. It has 0 points and length: 1.82804e-322
This is a Shape. It has 1 poi... | For example the body of the constructor
protected: Shape(int Spoints, double Slength){
Spoints = points;
Slength = length;
}
does not make a sense because you are trying to reassign parameters instead of data members of the class.
You should write
protected:
Shape(int Spoints, double Slength)... |
67,493,345 | 67,493,611 | Trying to print unicode characters C++ assert failed | I've been trying to print Unicode characters. I'm new to C++. I'm on Windows 10 and using Visual Studio 2019.
I'm trying to print the following art in a console application:
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ββββββββββββββββββββββββββββ... | I don't think it's a good idea to mix modes and cout with wcout.
You could try to stick with std::wcout only and set the mode directly at program start - before you've made any output.
This could possibly work:
#include <fcntl.h>
#include <io.h>
#include <Windows.h>
#include <clocale>
#include <iostream>
#include <str... |
67,493,514 | 67,501,315 | Arduino servo not working when using wrapper and inheritance | I'm building a robot arm which is quite complicated, so I wrote a class with inheritance to control different servos without having to write too much code. The classes look as follows (some stuff is left out):
In servoPart.h:
#include <Servo.h>
#ifndef SERVO_PART_H
#define SERVO_PART_H
class ServoPart {
protected:
... | I found the solution here: When calling servo.attach() in the constructor, the order of variable initialization is messed up. Creating an init() function to be called in setup() solves this problem.
|
67,493,608 | 67,493,767 | frequency <unordered_map> behaviour | i try to implement freq unordered map but it has weird behavior , why when i use unordered_map it gives me keys with negative numbers and when i use map it will give my the correct keys values.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int maxOperations(vector<int>& nums, int k) {
unord... | When you use an ordered map, you traverse the keys in order. Thus, target is never negative. When you traverse an unordered map, it is unordered. Therefore, target is sometimes negative.
If the negative values are not correct, then you need to traverse the map in order and so you should not use an unordered map.
Anothe... |
67,494,105 | 67,517,425 | Error in ceres when trying to install opencv-python on Mac m1 | I am trying to install opencv-python on the Mac m1.
I have followed the instructions here:
https://sayak.dev/install-opencv-m1/
However I am getting an error in a c++ library when running the make -j8 command:
/opt/homebrew/include/ceres/internal/integer_sequence_algorithm.h:64:21: error: no template named 'integer_seq... | I think the error was in the CMakeLists.txt in the opencv repo.
I had to edit this file and set(CMAKE_CXX_STANDARD 14) to get it to work
|
67,494,307 | 67,494,881 | C++ Phone Book - User Input Into Arrays | I'm very new at C++ and I am having trouble with my phone book program.
The issue is when I go to add a contact, it saves the name and number in the arrays. If I choose switch case 2 after adding each contact, it'll list all the contacts and phone numbers normally. But if I select switch case 1 multiple times in a row ... | i think Johnny Mopp has given you the correct answer, but you said your new so i'd like to give you a slightly longer explanation, and a little bonus advice.
Consider your addContact function. You ask for values to be inserted into the name and numbers array at position i. You need to update that position after you add... |
67,494,740 | 67,495,124 | How can I dynamically change the speed of a .wav or. aiff file using an arduino in real time | I'm working on a prototype for a lightsaber that changes the pitch and volume of its hum sound as it moves. The current solution only changes the volume (easy), and it doesn't sound realistic enough. I know I need to use .wav or .aiff (not lossy like mp3) to accomplish this. Ideally I'm looking for a lightweight soluti... | To change the pitch of a stream of audio samples, you need to change its sample-rate. The "easy" way to do that would be to change the frequency of the audio hardware's sample-clock, e.g. if you wanted to increase the playback pitch by 10% you would set the DAC to convert 52,800 samples-per-second rather than its norm... |
67,495,087 | 67,531,211 | How to deploy Qt app compiled using MSCV so that it won't neet vc_redist installed? | Is there a way to deploy a Qt desktop application that is compiled using MSVC in such a way that it will be "portable" (just run exe from a folder, not install anything, not even install VC_redist)?
Of course, it is possible to use it if Microsoft Visual C++ Redistributable is installed on target computer, but is it p... | Just as you commented, you can use windeployqt to add Qt-related DLLs and resources. As for other required DLLs, you could use Dependencies to find them and MANUALLY copy them into your application folder, including MSVC DLLs.
PS: I know manually copy those DLLs is low efficient and fallible. This is why I ask Is there... |
67,496,044 | 67,503,389 | Compiling Curl and GTK | When I compile the following code
#include <gtk/gtk.h>
#include <curl/curl.h>
#include <iostream>
#include <string>
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
void pop_class()
{
... | The reason why all your errors seem to be related to curl, is because you forgot to tell the compiler to link to it in your second command.
In other words:
g++ -o temp_app main.o -pthread `pkg-config --cflags --libs gtk+-3.0` -export-dynamic
should become
g++ -o temp_app main.o -pthread -lcurl `pkg-config --cflags --l... |
67,496,946 | 67,497,233 | Is there a new way to shuffle an array in C++? | I am relatively new to coding (second semester of C++) and am working on a project where I need to shuffle a string array. I did a similar program in the past using random_shuffle() but have discovered that it has since been deprecated. Are there any other ways I can shuffle an array?
I'm using Xcode BTW, in case that ... | std::random_shuffle was deprecated due to its use of the default psuedo random generator, because it was terrible. Now, std::shuffle lets you use c++11's awesome new random device mechanic. You can see that in the overload:
template< class RandomIt, class URBG >
void shuffle( RandomIt first, RandomIt last, URBG&& g );
... |
67,497,056 | 67,497,112 | C++ BOOL FUNCTION WITH * , could you help me? What is wrong with my code? | Question:
Consider a structure to represent a point in 2D space and implement a
function that indicates whether a given point p is located inside or outside a rectangle.
The rectangle is defined by its lower left v1 and upper right v2 vertices. THE
function must return true if the point is located inside the rectangle,... | For the signature bool dentroRetangulo(Ponto* v1, Ponto* v2, Ponto* P), you have 3 pointer arguments. So you need to use -> to access the data member.
To pass pointer arguments, you need to use &.
The compile error message from modern compiler is very clear, just follow them and fix your code.
#include <ostream>
using ... |
67,497,125 | 67,497,133 | Forward declaration without using the class keyword | class Wheel
{
Car* car;
};
int main(){
return 0;
}
Above code does not compile however if I add a class keyword then the compilation works:
class Wheel
{
class Car* car;
};
Why does't the first example compile? I also understand the following is another way of accomplishing this:
class Car;
class Wheel
{
... | Just like you, the compiler reads from the top to the bottom. If you have an object pointer of a class without ever declaring said class, the compiler (like you) goes "wait, what is this class?"
(The compiler says "what is this" like:
error: βCarβ does not name a type; did you mean βcharβ?
It is saying, i don't know ... |
67,497,167 | 67,503,258 | SFML 0x000007b Error When on Different Machine | After compiling for release in Visual Studio, my application was successfully created and worked as intended on my machine. I tested it on my VM (same os/64 bit) and after launching it returned The application was unable to start correctly (0x000007b). I had a friend test it and he got the same thing.
Assuming it's a D... | One way to figure this out is the using the following replacement for depends to see if there is a missing dll in your install folder: https://github.com/lucasg/Dependencies
The problem could be that the missing dll is found on the other system but is 32 bit instead of 64 bit.
The main reason for using the program I me... |
67,497,370 | 67,497,578 | Splitting of strings | How do I separate the string into two , first one before ","or "." or " " etc and second one after that and then assign both of the to two different variables.
for example
string s="154558,ABCDEF; (This is to be inputted by the user ) string a = 154558; //It should be spilt like this after conversion string... | I believe it can be something as simple as using rfind + substr
size_t pos = str.rfind('.')
new_str = str.substr(0, pos);
Essentially what the code is doing is searching for the first '.' and then using substr to extract the substring.
|
67,497,538 | 67,499,483 | How can I use std::vector safely with mutex? | I use multithreading to read and write a global variable std::deque<int> g_to_be_downloaded_tasks, and I use std::mutex to protect concurrent access. but ThreadB can not get element after ThreadA inserts an element to this vector,
ThreadA
g_to_be_downloaded_tasks_mutex.try_lock();
g_to_be_downloaded_tasks.push_back(tem... | You are ignoring the result of try_lock, so you aren't meaningfully using a mutex. Your code has undefined behaviour because of a data race.
If you never want to block, use the result of try_lock
if (g_to_be_downloaded_tasks_mutex.try_lock()) {
g_to_be_downloaded_tasks.push_back(temp);
g_to_be_downloaded_tasks_... |
67,498,113 | 67,509,783 | but can I initialize that vector with a size and value in a hashmap (unordered_map)? | So, I can very easily initialize a hashmap from int to vector...
But can I initialize that vector with a size and maybe default values ??
For example : vector<int> a(2,0) <--Size and values are initialized ....
So is there something for unordered_map<int, vector<int>>
| You could create a wrapper around the vector like this:
struct DefaultSizedVector{
DefaultSizedVector() : data{2, 0} {}
vector<int> data;
};
Then the map type would be unordered_map<int, DefaultSizedVector> so then (by accessing the .data member) it would act like a vector except have a default size.
You could... |
67,498,125 | 67,498,912 | C++ double wierd behaviour during incrementing in for loop | I was making a progress bar when I noticed this, Something wierd is happening when incrementing doubles in for loop.
EDIT : I am not asking why floating points are broken !! My issue is that the for loop is iterating one extra time in case 1 and one less time in case 4 !
I have created 4 test cases. Please See the code... | The answer is that floating points are "broken" - or at least not trusted for exact values.
In loop 1, when it unexpectedly prints 1.0, the actual value is slightly less (0.999...), so the check that it is less than 1 is still true.
In loop 4, when you expect it to print 1.0, the actual value is slightly higher (1.0001... |
67,498,516 | 67,498,809 | C++ create temporary object to call member function | What's wrong with the line of code with compile errors (in comment), in the code below? I thought it is supposed to call the TestMe constructor with the const std::string, then call operator() on it. But it looks like it is trying to construct TestMe with variable a.
#include <iostream>
namespace
{
class TestMe
{
pu... | "Most vexing parse": https://www.fluentcpp.com/2018/01/30/most-vexing-parse/
TestMe( a )() is being treated as a declaration of a function named a that takes no arguments and returns a TestMe object.
Change your program slightly so that the line in question doesn't conflict with the name a:
#include <iostream>
namespa... |
67,499,125 | 67,499,592 | Conditionally provide a using declaration | Suppose I've got a class foo with template parameter T and I want to provide a using declaration for the reference and const-reference types corresponding to T:
template<typename T>
struct foo
{
using reference = T&;
using const_reference = T const&;
};
Is there a way to "enable" these using declerations only ... | You could inherit from a base class with a specialization for void:
template<typename T>
struct typedefs {
using reference = T&;
using const_reference = T const&;
};
template<>
struct typedefs<void> {};
template<typename T>
struct foo : typedefs<T>
{};
|
67,499,718 | 67,500,447 | Why is my function not outputting what I am returning? | I am trying to write a piece of code that justifies an input by inserting extra spaces between words, so that its length is exactly 40 characters.
I have written a function that I think should do this;
string justify(int size, string s) {
while (size < 40) {
for (int p = 0; p < size; p++) {
if (... | There is a huge amount of bugs in your code: size is not bound to s.size() (and you actually need s.size()). The inner loop will be infinite too, because p was growing with the same speed as s.size(). This is the fixed algorithm - I marked three main changes with inline comments.
But it is not correct for strings witho... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.