question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
65,148,167 | 65,148,219 | Appending to map with set<size_t> in it | Hey my mentor(kinda) gave me this task and i am having trouble solving it .
So basically i am getting const vector<string> &data full of string and i need to check their place, like where are they in that vector so here is an example:
getting an input with: data={"chair","desk","table","chair","chair","desk"}
my ... | You can implement this quite easily by using an index-based loop:
map<string, set<size_t>> index(const vector<string> & data)
{
map<string, set<size_t>> res;
for (std::size_t i = 0u; i < data.size(); ++i)
res[ data[i] ].insert(i);
// ^string^ ^index
return res;
}
|
65,148,174 | 65,148,832 | Error in MSVC variadic template handling? | I'm attempting to maintain some code with variadic template functions that seems to work perfectly in GCC but fails in MSVC. I'm not very comfortable with this type of functions, but I have been able to reduce the problem to the following
#include <vector>
template<
template<typename...> class Container1>
std:... | The workaround is to pass in the template parameters that std::vector wants.
template<
template<typename...> class Container1,
typename... Rest>
std::vector<int> process(Container1<int, Rest...> c);
|
65,148,186 | 65,148,268 | Why do you need SFINAE in `std::add_pointer_t`? | I've been hacking around the standard library lately, since I need to implement a subset of it (mostly template stuff) for a system which doesn't have an stdlib implementation.
I came across this "possible implementation", in cppreference:
namespace detail {
template <class T>
struct type_identity { using type = T; }... | I'm not sure if this is the only bad case, but your implementation fails for so-called "abominable function types":
add_pointer<void() const>::type // hard error instead of void() const
|
65,149,079 | 65,150,275 | Cannot move view matrix and direction view matrix is pointing in simultaneously | When I move around the scene (without moving my 'head', which is where my view matrix is pointing) everything works just fine. When I look around without moving, everything works just fine. But it is when I combine the two that my head (view matrix) starts going wild. I'm assuming the issue is in my math/logic, but I j... | Your problem is that regardless of where you look at, pressing W will always subtract MOVE_DISTANCE from your world-space position.z coordinate, even though moving "forward" or "backward" would not necessarily mean "moving along the world's Z axis".
So, you must determine the axes of "forward" (in order to move forward... |
65,149,295 | 65,152,014 | Is there a better way of looping through each element in an array without using an indexed for loop? | I have a triangle class consisting of a triangle's sides perimeter and many helper functions.
I have created a function that will populate an array of instances of triangle. Let us say I will create 3 objects so the triangles parameter will be set to 3.
void populate_triangle(triangle in_array[], int triangles) {
f... | As mentioned in the comments, you can use a std::vector.
std::vector keeps track of its own length so when you write your methods, there's no need to include the length as an extra argument, it's automatically deduced in the range for loop.
With a std::vector your method might look something like this:
void populate_tr... |
65,149,718 | 65,150,686 | overloading << operator whilst accessing private elements (friend) | I'm writing a program that requires me to overload the << operator whilst accessing private members of the class. It goes like this:
A.h
#pragma once
#include <ostream>
#include "B.h"
using namespace std;
class A {
public:
A(B* b) {
this->b = b;
this->x = 0;
}
friend ostream& operator<<(... | In main(), a and b are pointers. This code:
cout << a
cout << b
Is effectively calling this:
cout.operator<<(a)
cout.operator<<(b)
Because std::ostream has a member operator<<(void*) for printing a pointer, and all pointers are implicitly convertible to void*. This is why you are seeing memory addresses in the outp... |
65,149,793 | 65,151,295 | Why is there no movement of objects in the vector when additional memory is reserved? | There is the following code:
#include <iostream>
#include <vector>
class Test {
public:
Test() {}
Test(int x) : x(x) {}
Test(const Test&) noexcept = delete;
Test& operator=(const Test&) noexcept = delete;
Test(Test&& r) noexcept { x = std::move(r.x); }
Test& operator=(Test&& r) noexcept {
... | The statement v.reserve(10); causes your vector to reallocate its storage so it can accommodate at least 10 elements. Presuming capacity is less than 10, this is a four step process :
New storage is allocated, enough so capacity will be at least 10.
The elements from the previous storage need to be moved to the new s... |
65,150,569 | 65,151,438 | UE4 4.26 on mac: undefined symbols Z_Construct_UClass_UPhysicalMaterial | trying to get my project up and running on macos big sur, but I'm facing a linking error (full paste here : https://pastebin.com/raw/qt7qkjYu):
[10/13] Link UE4Editor-LastRenegade.dylib
Undefined symbols for architecture x86_64:
"Z_Construct_UClass_UPhysicalMaterial()", referenced from:
Z_Construct_UClass_ULRNB... | Ok, in 4.26: you need to add PhysicsCore to your MyGame.Build.cs
|
65,150,650 | 65,179,005 | How can I use SetCurrentConsoleFontEx with fonts loaded by AddFontMemResourceEx? | My main goal is to set the console font to Unifont using windows API functions. I can successfully do this by calling AddFontResource with the filename. I would rather use AddFontMemResourceEx because then I can load the font from a Resource.
I tested a variety of calls to load the font, and here are the results:
AddFo... | From the doc,
This function allows an application to get a font that is embedded in
a document or a webpage. A font that is added by AddFontMemResourceEx
is always private to the process that made the call and is not
enumerable.
For other content, please refer to zett42's answer,
You are calling AddFontResourceEx() ... |
65,150,670 | 65,151,173 | How to correctly implement hash insert function in c++? | I need to read a file and then store each word to the hash table with linked list collision handling, and count how many times each word appeared (node's value). When I run my code with small text (like 30 lines) it works, but starting from about 100 it crashes (Segmentation fault: 11). I know my hashCode function is b... | Most likely char is signed in your system, so converting it to integer in line sum = sum + int(key[k]); results in negative value, and then you get segmentation fault when try to get buckets[index] with negative index.
A quick way to fix it would be at first to convert key[k] to unsigned char, and only then to int:
for... |
65,150,862 | 65,151,108 | SendInput does not send the exact amount of pixels I specify | I prepare the input buffer like this
...
buffer->mi.dx = x;
buffer->mi.dy = y;
buffer->mi.mouseData = 0;
buffer->mi.time = 0;
buffer->mi.dwExtraInfo = 0;
buffer->mi.dwFlags = (MOUSEEVENTF_MOVE);
SendInput(1, buffer, sizeof(INPUT));
std::cout << "moving " << buffer->mi.dx << "," << buffer->mi.dy << " relative to current... |
Any ides on why this is happening and how can I fix it?
I'm guessing it's mouse-acceleration. This is mentioned in the documentation:
https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-mouse_event
Relative mouse motion is subject to the settings for mouse speed and acceleration level. An end user... |
65,151,131 | 65,151,240 | Troubles on retracting pointer values | My teacher have forced us to use the skeleton code and I am now dealing with a ***[struct] variable.
struct Node
{
Thing thing;
int quantity = 1;
Node *next = nullptr;
};
I have a map as followed
Node ***map = new Node**[width];
Node **temp = new Node*[height];
for (int i = 0; i... | Nowhere in your code do you give map[0][2] a value so a crash is no surprise
Take a look,
map[i] = temp;
so therefore map[0] is equal to temp. Now look for temp[2] where is that given a value? Nowhere, so therefore map[0][2] has no value.
EDIT well the posted code has now been editted so that temp[2] is given a value.... |
65,151,373 | 65,151,455 | I can't assign value to object in list c++ | I have struct Point, it contains setters for x and y:
struct Point {
int x;
int y;
Point() {
x = 0;
y = 0;
}
Point(int _x, int _y) {
x = _x;
y = _y;
}
Point& operator=(Point other) {
swap(x, other.x);
swap(y, other.y);
return *this;
... | This method:
Point get(int i) {
if (i >= length && i<0) return Point();
Element *t = first;
while(i--) t = t->right;
return t->data;
}
returns a Point by value. The object returned is not the object in the list. Hence here:
snake.get(0).setX(99);
You do setX(99) of a Point, but that Point is the tempo... |
65,152,011 | 65,177,294 | Visual Studio export .editorconfig has no content for c++ | I have tried exporting my C++ formatting settings into a .editorconfig but with the 2 methods I have attempted, the config is almost completely blank except for a brief comment header and the language file format selectors.
Using the method described here:
https://stackoverflow.com/a/51437947/2033725
Generates an edito... | You could select the folder path to save .editorconfig in Tools->Text Editor->C/C++->Code Style->General->Generate .editorconfig file from settings.
Then you need to compile this project. Then editorconfig will appear in the save path you just set.
|
65,152,051 | 65,152,117 | converting std::string to double with negative values results in zero or throws an exception | Context
A number is read from an input file as a std::string and converted into a double.
My solution
I tried a variety of approaches based on what I could find on the web:
std::string str = "‐12.5799";
std::cout << str << std::endl;
double d;
std::stringstream(str) >> d;
std::cout << d << std::endl;
std::... | That is not an ordinary ASCII hyphen/minus character.
It is instead the following sequence of codepoints:
U+00AD : SOFT HYPHEN [SHY] {discretionary hyphen}
U+2010 : HYPHEN
Your parsing attempts are therefore failing.
When in doubt, copy/paste your text into a hex editor, or an online tool such as https://babelstone.c... |
65,152,598 | 65,152,627 | Changing the address a pointer is pointing to in C++ | Okay, I'm sure this has already been answered here a million of times, but I've been searching the site for some time now and I can't seem to get an answer I'm satisfied with. I'll be glad if you could point me in the direction of a duplicate solved thread about this.
So I have this pointer in C++, p, which points to a... | The parameter p of g is declared as pass-by-value, it's copied from the argument, any modification on the pointer itself like p = ... has nothing to do with the original argument. The reason is just same as
void g(int p) { // p is passed by-value
p = 65; // modification has nothing to do with the argument passe... |
65,152,628 | 65,184,154 | Check same enum, C++ | I am abstracting my problem now but I am in this kind of situation.
Let's say I have 2 enums that are in the same namespace.
namespace some_namespace {
enum class Something{
S,
O,
M,
E,
T,
H,
I,
N,
G
};
enum class Else{
E,
... | The answer was simpler than I thought.
So I declare enum like this.
namespace some_namespace {
enum class Something{
S = 0,
O = 2,
M = 4,
E = 6,
T = 8,
H = 10,
I = 12,
N = 14,
G = 16
};
enum class Else{
E = 1,
L = 3,
... |
65,152,839 | 65,155,088 | Printing from a custom heterogeneous container in C++ | I am reading a blog about building a custom heterogeneous container in C++. In the blog, the author used visitor pattern to print out each element of the container ordered by their types. I'm wondering if it is possible for me to write a visitor such that I could print out the elements in the order they were inserted?
| As you store element by type, you loose insertion order, so you have to change
template<class T>
static std::unordered_map<const heterogeneous_container*, std::vector<T>> items;
by
template <class T>
static std::unordered_map<const heterogeneous_container*,
std::vector<std::pair<std::size_t, ... |
65,152,846 | 65,152,916 | Multiple definition error #include -ing .h header | [the Environment is QTCreator 4.2.1, the compiler is MinGW 5.8]
I've created a header "header.h"
with the following code :
#ifndef HEADER_H
#define HEADER_H
int variable = 0;
#endif // HEADER_H
And I tried to include the header in two .cpp files, getting multiple definition errors.
But than I changed the code like t... | There are three main reasons that get combined to explain this:
They are two completely different "things". The syntax may look quite the same, but they do two completely different things in C++.
The One Definition Rule
#includeing a header file is logically equivalent, and is exactly equivalent to physically insertin... |
65,153,317 | 65,206,384 | clang in neovim giving pp_file_not_found error for c++/pytorch basic example | I'm following this very basic c++/pytorch example:
pytorch_installing
And I can walk through this example with no errors. However, when creating the example-app.cpp file (or editing it at any point in time) with neovim, clang throws an error 'torch/torch.h' file not found [clang: pp_file_not_found]. My CMakeLists.txt f... | Since the compilation succeeds with cmake-make, it is possible to ask CMake to generate the compilation database (typically a compile_commands.json file) with cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=1.
Once the file is available, it can be read by the autocompletion compiler (clang in this case), which prevents the autoc... |
65,153,489 | 65,153,519 | using overloaded << operator in another << overload in a different class | So here's the problem. I have a class B where I have overloaded the << operator and a class A where the << operator is also overloaded. However, the << overload in class B doesn't seem to be working in the << overload in class A. It simply returns the address of b as if the << overload in class B doesn't exist.
Any hel... | os << a.b // ...
a.b is not a B, for which you defined an overload, look closer at your code:
class A {
private:
B* b;
};
That's a B *, and not a B, and no overload exists for that.
If you want to call the overload here, use os << (*a.b) // ...;
|
65,153,819 | 65,153,880 | Capturing by const reference in mutable lambda | I'm looking for a way to capture by const&, or even const for that matter on a mutable lambda. Something like the syntax below. Is there a good way to do this?
#include <future>
#include <vector>
int main() {
std::promise<int> p;
const int N = 2;
std::vector<int> v = {1,2,3};
auto foo = [const& N, const& v, p =... | Use std::as_const:
#include <future>
#include <utility>
#include <vector>
int main() {
std::promise<int> p;
const int N = 2;
std::vector<int> v = {1,2,3};
auto foo = [&N, &v = std::as_const(v), p = std::move(p)]() mutable {
// v.push_back(4); // does not compile
p.set_value(v[N]);
};
}
|
65,153,854 | 65,157,395 | Problems with boost::read_graphviz in GitHub actions | I use Conan in the project to install boost 1.74.0. When I try to call read_graphviz function I get such error in GitHub actions while building:
undefined reference to `boost::detail::graph::read_graphviz_new
I include only <boost/graph/graphviz.hpp> header from boost library.
On my computer everything is ok, but I i... | I just forgot to add target_link_libraries(project_name boost_graph boost_regex)
|
65,154,494 | 65,194,452 | vscode note recognising imported libraries for python and c++ despite code working | Recently set up c++, noticed that the #include <library> were underlined.
error read: library.h file can not be accessed
despite this the code still ran, recently start a new python project and same thing, vscode doesnt recognise my imported modules but despite this the code runs fine.
Anyone know the source of this?
n... |
About Python:
The reason why the terminal displays "No name'K_UP' in module'pygame.locals" is that "K_UP, K_DOWN, K_w, K_s, " these are constants of "locals.py" of module "pygame".
Usually, Pylint recognizes imported statements in VSCode as importing files or methods or classes in files.
1).When we import the pygame.... |
65,154,566 | 65,154,594 | Copy an image bit by bit C++ | I recently found some documentation on file open modes in C++ and, using ios_base::binary, tried to open an image (.JPG), read the bits one by one, and write them in a separate file (ofstream) with a .JPG extension. The problem is that I get an error when trying to open the newly created image: Error interpreting JPEG ... | fin >> a skips whitespace, even if the file is opened in binary mode. Use get instead. You can also simplify your while loop.
char a;
while (fin.get(a))
fout.put(a); // fout << a; would also work
|
65,154,693 | 65,154,834 | How to return number of occurrences in hash table c++? | I have a text file and i inserted all words to the hash table with insert method, and then i did find method that suppose to return number of occurrence of word written but it does not return anything, what can be wrong. So if the word in the if condition it enteres it, but i am not sure how to correctly return value v... | You're most of the way there and just need a small fix and a small change.
First a the fix. In HashNode
class HashNode
{
public:
string key;
int value;// constuctor accepts and assigns an int, not a string
public:
HashNode(string key, int value)
{
this->key = key;
this->value = value;
... |
65,154,738 | 65,154,837 | How do I update a 2d array to convert grades to their GPA values? | I have a 2d array that holds students grades for several courses. I would like to be able to convert the grades to their GPA counterpart, assuming A = 4.0 B = 3.0 and C = 2.0 however I am not sure how to iterate through the array and update it to these new values. Here is what the array looks like
int Students[3][5] = ... | I don't understand what is going to be converted, but with a two nested loop you can do this, for example
for(int i = 0 ; i < 3 ; i++){
for(int j = 0 ; j < 5 ; j++){
Students[i][j] = ......
}
}
this is how you can iterate all items.
|
65,155,040 | 65,155,161 | c++ template class store reference or value with same template argument | I want to design a class which can store value or reference, but with the same argument in the template declaration. I can not figure out how to write the template class. Can any one give me some advise
tempalte <typename T>
class Holder {
// ......
Holder(T &value);
Holder(T value);
}
class CannotCopy {
CannotCopy... | So if I understand you correctly, you sometimes want the class to have ownership of the element you pass into it (when constructed in place) and sometimes you want to use it as a reference to ownership stored elsewhere.
I, unfortunately, speak from experience when I tell you this is a bad idea. At first glance, this lo... |
65,155,121 | 65,155,273 | Why no overload chosen on forward reference for function templates? | Snippet:
#include <iostream>
template<typename T>
struct Printer{};
template<typename T>
void test(T&&)
{
std::cout << "Primary template called\n";
}
template<typename T>
void test(Printer<T>&&)
{
std::cout << "Specialized template called\n";
}
int main()
{
auto t = Printer<int>{};
test(0);
test... | Forwarding reference only works for T&&, not C<T>&& nor const T&&.
test(0); // Call test(T&&) with T=int
test(t); // Call test(T&&) with T=Printer<int>&
|
65,155,241 | 65,183,206 | How to deal with precision loss in vtk for reading/writing ply? | I'm trying to parse binary mesh data (ply) into a text ply and I need to maintain a 3-decimal precision. The code below produces a valid ply file. The data I'm dealing with has up to 10 digits. The problem is: the output coordinates are snapped to some grid which is maybe due to some precision loss.
# Expected X, Y, Z ... | As I suggest in my latest comment, if you use the original PLY file library, you can be sure that you won't lose any precision. Apparently somewhere internally VTK is casting your doubles to floats. The original PLY code is pretty simple, so you can figure out what it does and be sure that it won't do that cast.
Here... |
65,155,264 | 65,155,304 | Given a a class with a non-type template parameter, is it possible that for any pair of values of the argument the classes are mutually friend? | In the code below, I would like that A<N> is a friend of A<M> for any pair of M and N. Is it possible?
Below you can find my attempt, which does not compile.
template <int N> class A {
int x = N;
template<int M> friend A<M>;
public:
template<int M> void copy(const A<M>& a) {
x = a.x;
}
};
void... | Yes. The correct syntax is
template<int M> friend class A;
|
65,155,791 | 65,587,889 | Make C++ class partially constexpr and save RAM | I have written code for a controller that has buttons and lamps. It is based on Arduino/ATmega2560. RAM is very limited. Changing to another device is no option.
Each button and lamp is modelled as a C++ class instance. They are derived from an abstract class Thing, which contains a pointer mpTarget that indicates conn... |
Use small state
Eliminate all virtual methods (and probably all base classes) to reduce class state.
Use Non-Type template parameters to move references from data (RAM) to code (ROM)
Use an enum based on a char for state when possible:
enum binary_enable_state : char {
BINARY_ENABLE_ON,
BINARY_ENABLE_OFF
};
... |
65,156,394 | 65,156,421 | Can't construct object because member doesn't have default constructor | When compiling my program, I am getting this error:
error: constructor for 'parser' must explicitly initialize the member 'lexer_inst' which does not have a default constructor
As the error mentions, my member "lexer_inst" doesn't have a default constructor. However, I don't want it to be default-constructed in the fi... |
How can I keep "lexer_inst" uninitialized?
You can’t, and you shouldn’t. Change your constructor to
parser::parser(source_file& file)
: file(file)
, ast_arena(file.data.length * 4)
, lexer_inst(ast_arena, file) {}
That is, exclusively use the member initialiser list to set up your class, don’t attempt to... |
65,156,523 | 65,168,272 | Unexpected behaviour with using STM32 QSPI over HAL | I am using the QSPI (or dual-SPI) interface of the STM32L452 to create instructions for an LED driver using the HAL. I have managed to get it to work but I have to set quite absurd configuration options for the command to make it work.
Here's my initialization code:
hqspi.Instance = QUADSPI;
hqspi.Init.ClockPrescal... | This is embarrassing.
qspiCommand needs to be static.
|
65,156,899 | 65,163,926 | Debugging with gdb and armadillo | When using the armadillo C++ library I need to compile with g++ flag -larmadillo to link the run-time armadillo library. If not, I get many undefined reference errors.
However when I want to debug with gdb, I still get these undefined references. How can I get gdb to use a linked library without errors? Or otherwise, h... | For me it worked when I changed the type to "type": "shell", in the tasks.json file. This is the settings I used for the basic example in Armadillo documentation.
tasks.json
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "C/C++: g++ build active file",
... |
65,157,114 | 65,157,158 | GLSL translation in fragment shader not working as expected | I wrote a simple GLSL shader that creates a pattern similar to the colored squares pattern shown on this page. Then I added code to move the pattern across the screen by following this example. This is my code:
st = vec3(TexCoord.x , TexCoord.y , 0.0);
vec3 translate = vec3(cos(u_time),sin(u_time), 0.0);
st+= translate... | You need to shift the texture coordinates by an offset < 1.0:
vec3 translate = vec3(5,2, 0.0);
vec3 translate = vec3(0.5, 0.2, 0.0);
Texture coordinates are in range [0.0, 1.0]. Translating the texture by an integral multiple of 1 has the same effect as translating the texture by 0.0.
Note that the result of the sin a... |
65,157,371 | 65,157,599 | C++ lambda function pass by reference problem | I used a lambda function in order to store point cloud into each instance of a vector. Even I pass the vector by reference, when I try to access each instance of the vector, I get this error:
typename boost::detail::sp_member_access<T>::type boost::shared_ptr<T>::operator->() const [with T = pcl::PointCloud<pcl::PointX... | I assume Point, Cloud and Cloud::Ptr are something like this:
struct Point {
int x,y,z,intensity;
};
struct Cloud {
std::vector<Point> points;
void push_back(const Point& p) { points.push_back(p);}
using Ptr = Cloud*;
size_t size() const { return points.size(); }
};
It turned out they are somethin... |
65,157,514 | 65,168,473 | Why do Clang and MSVC not like a member typedef declaration with a redundant set of parentheses? | Consider
using foo = int;
struct A {
typedef A (foo)();
};
GCC and ICC accept the snippet, while Clang and MSVC reject it. Clang's error message is
<source>:4:15: error: function cannot return function type 'void ()'
typedef A (foo)();
^
<source>:4:13: error: typedef name must be an identifier
... | Clang is wrong: foo in the typedef declaration in A does not refer to the namespace-scope typedef-name foo
W.r.t. the standard rules, the enclosing namespace/scope alias declaration
using foo = int;
is a red herring; within the declarative scope of class A it will be shadowed by names declared in A
#include <type_tr... |
65,157,958 | 65,158,509 | Error using Connections in c++ defined QML Type | when using Connections on a c++ defined QML Type, I get the following error:
Cannot assign to non-existent default property.
Following code produces the error:
main.qml
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
import QtQml 2.15
import myextension 1.0
Window {
id:root
width: 6... | Your error has nothing to do with Connections objects, or your custom C++ class. You will get the same error if you do this:
QtObject {
Item { }
}
Everything in a QML object has to be stored in a property, including child objects. But it doesn't usually look like a property because they use a default p... |
65,158,447 | 65,158,579 | Error whilst creating a template operator | I've written a generic tree in c++, and one of my tasks is creating a tree of trees.
Inorder to do so i need to create an operator between trees.
lets say i can get all the comparison info i know from the info in the root.
i created these template operator overloading.
template <class T>
class tree {
tree_node<T>* root... | You either need to define the non-template function in the class
template <class T>
class tree {
// ...
friend bool operator<(const tree<T>& tree1,const tree<T>& tree2){
return tree1.get_root()->data<tree2.get_root()->data; //assuming < operator
}
};
or declare the friend function template:
templat... |
65,158,592 | 65,158,669 | Define a matrix template with using | I want to define a matrix with using keyword to use templates.
#include <vector>
template <typename T>
using row = std::vector<T>;
template<typename T>
using Mat = std::vector<row> >;
I think this definition is ok, but I don't know how to instantiate now the matrix.
I tried with Mat<int> m(3, row<int>(3));, but It w... | You have small typos, it should be
template <typename T>
using row = std::vector<T>;
template<typename T>
using Mat = std::vector<row<T>>;
int main() {
[[maybe_unused]] Mat<int> m(3, row<int>(3));
}
Demo
|
65,159,486 | 65,159,555 | Options to setting a integer to a value | i've seen that some people initialize integers with "()" insteadt of "=". I.e.:
unsigned int a(1);
unsigned int b = 1;
Is there any side-effect using "()"? I know that this will probably have something to do with the contructor of an integer. Am i right?
Thanks for help
| For an integer, it makes no difference.
For a class, it makes a difference - the parentheses would use the constructor; the equal sign the assignment operator. The two should have the same performance and outcome, but it depends on how they are coded.
There is a third way (and often recommended) way, using 'universal i... |
65,160,150 | 65,406,750 | Is it necessary to free the memory of strings in C++ received from C#? | I have the following exposed DLL functions in C++.
// center_of_rotation_api.h
// CENTER_OF_ROTATION_API is a macro like __cdecl(dllexport) on Windows
CENTER_OF_ROTATION_API void SerializeMesh(Mesh * mesh, const char * path);
CENTER_OF_ROTATION_API const char * SerializationError(Mesh * mesh);
From C#, I use the follo... | No, the C# marshaler will take care of this for you. The char* will be valid during the lifetime of the PInvoke call. If your C++ code expects to own the char*, you should make a copy in SerializeMesh.
Here is a primer on string marshaling. If you really need to use a const char*, you might need to set the MarshalAsAtt... |
65,160,392 | 65,160,473 | How to use std::optional for error handling when creating objects without instantly destructing them? | Error handling is a challenge in C++ constructors. There are several common approaches but all of them has obvious disadvantages. Throwing exceptions for example, may cause leak of the allocated resources earlier in the constructor, making it an error prone approach. Using a static init() method is another common solut... | Your class violates the rule of 3/5.
Instrument the copy constructor and simplify main to get this:
#include <optional>
#include <iostream>
class A
{
public:
A(int myNum);
~A();
A(const A& other){
std::cout << "COPY!\n";
}
static std::optional<A> make(int myNum);
bool isBuf() { return _... |
65,160,442 | 65,160,582 | How to increment shared_ptr in C++? | I get shared_ptr from the function. Shared ptr points to a big array of bytes. I want to return this shared_ptr but point it to the 16th byte in this array.
Example with raw pointers (working):
uint8_t* SomeFunction() {
uint8_t* array = SomeOtherFunction();
return array + 16;
}
Example with shared pointers (doesn'... | Aliasing constructor might be used:
std::shared_ptr<uint8_t[]> SomeFunction() {
std::shared_ptr<uint8_t[]> array = SomeOtherFunction();
return {array, array.get() + 16};
}
|
65,160,620 | 65,201,351 | MPI Send and Receive modes for large number of processors | I know there are a ton of questions & answers about the different modes of MPI send and receive out there, but I believe mine is different or I am simply not able to apply these answers to my problem.
Anyway, my scenario is as follows. The code is intended for high performance clusters with potentially thousands of cor... | From how you describe your problem, I think MPI_Isend is likely to be the best (only?) option for A because it's guaranteed non-blocking, whereas MPI_Send may be non-blocking, but only if it is able to internally buffer your send buffer.
You should then be able to use an MPI_Barrier so that all processes enter B at the... |
65,160,622 | 65,160,764 | C++ Streams Should Not create New Line | i try to make program that write timestamp to file with c++ here is my code :
#include <time.h>
#include <iostream>
#include <unistd.h>
#include <fstream>
using namespace std;
int main()
{
fstream outfile;
outfile.open("time.txt",ios::out|ios::app);
string savetime;
for(;;){
time_t t = time(NULL... | #include <iostream>
#include <fstream>
#include <ctime>
#include <unistd.h>
using namespace std;
int main()
{
fstream outfile;
outfile.open("time.txt",ios::out|ios::app);
char savetime[100];
for(;;){
time_t t = time(NULL);
strftime(savetime, sizeof(savetime), "%A %c", localtime(&t));
... |
65,160,820 | 65,162,433 | SDL2 cannot open any BMP files | Im trying to play around with SDL2 following lazyfoo's tutorials to get accustomed to it, but even the basic most program doesn't work properly. I can open a basic blank window with no image and keep it open, but as soon as I try to open a BMP file in a window, it all acts weird and doesn't work anymore. My code, that ... | The constant SDL_WINDOWEVENT_SHOWN is not a valid flag for the function SDL_CreateWindow. That constant is not intended as a flag, but as an event ID. You probably meant to use the constant SDL_WINDOW_SHOWN instead.
The constant SDL_WINDOWEVENT_SHOWN happens to have the same value as SDL_WINDOW_FULLSCREEN (both have th... |
65,160,855 | 65,161,235 | C++ Std::stof doesn't work for float less than FLT_MIN? | I'm having issues with the following line of code:
float temp = std::stof("-8.34416e-46");
My program aborts as soon as it reaches this line. It's clear that this float is less than FLT_MIN, but such floats are allowed to exist. (For example, float temp = -8.34416e-46; works fine. Is the stof method supposed to only w... | An Alternative
Convert to double with std::stod and then assign to float. Add bounds checking if desired.
Converting “-8.34416e-46”
The C++ standard allows conversions of strings to float to report underflow if the result is in the subnormal range even though it is representable.
When rounding to the nearest representa... |
65,160,985 | 65,161,154 | How to take template assignment without friend c++ | I write template for ::iterator and ::const_iterator. template class - base_iter
In this classes store some value. How I can use assignment between class base_iter and base_iter without friend and c++11 features?
Something like
::iterator it1 = ::const_iterator it2
To make it1._value == it2._value
and construct like
it... | You cannot overload operator= outside class definition. If this code is inside a class definition for iterator_base<T> then it will also have access to iterator_base<T>::p.
|
65,161,136 | 65,179,505 | in c++ my operator overloading prefix not work | Question has been modified
I have a list class (like linking list) that contain add() and begin() functions
add() function that adds to tail
begin() function that returns the address of the first element (head)
i try to make my class support for-range for(:) so i try to implementation begin(), end() and operator++() f... | Thank you everyone, I solved the problem by implementing the Iterator Class by myself like what you said
my class is now support for range for(:)
#include <iostream>
using namespace std;
class List
{
struct Node
{
int info;
Node * next;
Node(int val): info(val), next(NULL) {}
};
... |
65,161,156 | 65,172,415 | How to decrypt using openssl EVP? | I'm trying to decrypt a file using C (but I can change to C++), but I don't know how to use the EVP library correctly.
The console command that I want to replicate is:
openssl enc -rc2-ecb -d -in myfile.bin -iter 1 -md sha1 -pbkdf2 -pass pass:'Yumi'
My actual C code using EVP is:
unsigned char salt[8] = "Salted__";
c... | The following hex encoded ciphertext could be decrypted with the posted OpenSSL statement, if this data would be contained hex decoded in myfile.bin:
53616C7465645F5F2DC4C4867D3B9268C82E23A672D6698FB51D41EA8601367A9112623EC27CDEB18FD1444BDB8D8DE16F1A35706EC7FED266CB909D28BF6BEC
The decryption would result in:
The quic... |
65,161,418 | 65,162,470 | How to implement complete binary in c++? | I want to try make insertion of complete binary tree using recursion . I make a piece of code and I cannot catch problem why value not inserted. I make height function and count nodes function with help of these function and recursive call I want to insert new node in Complete binary tree. In main get root by using get... | You would need to go through a debugger to see what is wrong with your code. I will tell you how I would do this:
First, you need a function to check if the tree is full. We will reuse your functions to do this:
bool isTreeFull(node* head) {
return head != NULL && countNumNodes(head) == (1 << find_height(head)) - 1;
... |
65,161,639 | 65,162,046 | Bit width of a class | there is a class declared as:
class Payload {
uint8_t m_a : 1;
uint8_t m_b : 5;
uint8_t m_c : 2;
uint8_t m_d : 4;
};
you see, the sizeof(Payload) == 2. So far so good. The total amount of bits is 12, it exceeds the 8bit thus 2Bytes are occupied.
But is there a way how to get the amount of bits the clas... | No, not in a standard-conformant way.
[class.bit]/1:
the bit-field attribute is not part of the type of the class member
which means this information cannot be extracted at compile time. Any kind of attempt to find this information using runtime introspection techniques would rely on, at best, implementation defined... |
65,161,782 | 65,162,666 | Suppress "Avoid unnamed object" warnings for function returns | I have a log function that I sometimes pass the return of on to another function, and sometimes call alone
LogReturnStruct Log(string message) { writeToFile(message); return {message};);
this is because i sometimes want to log something is about to be attempted, as well as if it succeeded or not
void Handle(LogReturnS... | It seems you might use [[gsl::suppress(es.84)]], but it should be used at call site :-/
MACRO can then help:
LogReturnStruct LogImpl(string message) { writeToFile(message); return {message}; }
#define Log(s) [[gsl::suppress(es.84)]] LogImpl(s)
Cleaner solution is to avoid the warning and create 2 functions (You alrea... |
65,161,879 | 65,161,978 | Exporting class vector to .dat in C++ | So I'm making a basic cryptocurrency in C++ and I'm trying to export the Blockchain to a .dat file so that the peers can download the blockchain
Blockchain class:
#ifndef BLOCKCHAIN_H
#define BLOCKCHAIN_
#include <cstdint>
#include <vector>
#include "block.hpp"
class Blockchain
{
public:
Blockchain();
... | The problem is here
std::ostream & operator<<(std::ostream & out, const Blockchain & p) {
out << p << std::endl;
return out;
}
I'm not sure what you were expecting but you've written a function which just calls itself. So when you try to output a Blockchain you just get a stack overflow and that's why your pro... |
65,161,963 | 65,162,022 | Argument of type "const char *" is incompatible with parameter of type "LPCWSTR" Visual Studio 2019 | I'm new to C/C++ coding on windows, and have had this error when running my code. A similar question was asked before which I will link below, however, this solution does not work for me because I do not have the option to change my character set.
argument of type const char* is incompatible with parameter of type "LPC... | There are two ways to fix this.
First is to use a string made of wide characters:
OutputDebugString(L"Lets test this out \n");
// ^
Second is to call the version of the function that takes a narrow character string:
OutputDebugStringA("Lets test this out \n");
// ^
Since the Windows API p... |
65,161,992 | 65,162,265 | Qt 5 library missing | I was trying to compile using MinGW's windeployqt. As parameter I put my .exe file and when I try to start my application it tells me that the libgcc_s_seh-1 library is missing. So I try to add it manually and it gives me the same error of the previous post:
The application was unable to start correctly (0xc000007b).
H... | windeployqt can be a tricky customer: It picks its information where to find the Qt libraries from the %PATH% variable in Windows. If you have two or more Qt / mingw instances installed, this might end up in a unhealthy mixture. Replace the wrong path to mingw in the environment by the correct value.
|
65,162,064 | 65,162,391 | Destructing objects with private destructors | I'm currently working on a program that generates C++ code. This generated C++ code sometimes needs to destruct a Class, so it uses
ptr->~MyClass();
, because this works in all corner cases (including for example inherited destructors). Or so I thought: If there is a private destructor:
class MyClass {
~MyClass();... | You could use SFINAE:
template <typename T>
auto destruct(T* t) -> decltype(t->~T()) { t->~T(); }
auto destruct(void*) { /* throw, exit, ... */ }
Demo
|
65,162,436 | 65,162,680 | Ordering 2d array in lexical order | I have an 2d array of char, and I am trying to order them in alphabetical order. In each rows there is a word build of chars and I am trying to sort it.
I built something, but I don't understand why this is not working. If you have a solution for me, please explain what you are doing, in order to understand why I don't... | That's it.
#include <bits/stdc++.h>
using namespace std;
char matrix[4][5] = {
{'h','e','l','l','o'},
{'r','e','a','d','y'},
{'a','p','p','l','e'},
{'p','o','i','n','t'} };
int n = 4, m = 5, k = 0;// number of rows and columns
char temp;
int main()
{
for ( int i = 0; i < n; i++ )
for ( i... |
65,162,784 | 65,163,505 | using std::stringstream as a the text that gets thrown as runtime error | So basically, I am checking if a window is created in SDL and if not a runtime error is thrown. The following was suggested to me by someone in code review.
if (!windowCreated())
{
std::stringstream buffer;
buffer << "Could not intialize SDL properly: " << SDL_GetError();
}
But in line std::stringstream buffer... | Make sure you have #include <sstream> in your code in order to use std::stringstream (in your case, prefer std::ostringstream instead). You are likely missing that header file include, but the class has been forward-declared in another header file that you are including. That would explain why the compiler thinks the c... |
65,163,372 | 65,163,384 | How do I convert this stoi use in c++11 to atoi? | I cant really update my C++ compiler right now, and would like to know how I can change stoi to atoi without getting a compiling error
int getInput(int columns)
{
// declare the variable to hold user input
int userInput;
string userValue;
// prompt for the column number and read the column number
co... | Firstly, add #include <cstdlib> to your code to use atoi if you don't have that.
Then, replace stoi(userValue) with atoi(userValue.c_str()).
|
65,163,537 | 65,164,439 | CreateRemoteThread causes process to crash without error code | I'm attempting to execute a simple function inside another process (the "host"). To do this, I call WriteProcessMemory to copy the function to the host, then use CreateRemoteThread to execute that function. The host process just crashes, with no error codes.
I use Notepad++ (32 bit) as an example host. I also compile m... | The solution to the immediate problem was to compile in release mode. I'm not exactly sure why, so if anyone has an idea I'd love to hear it in a comment.
As @RaymodChen has mentioned, this process is more complicated than I once thought, and I was unable to run any significant amount of code in the host process.
If an... |
65,163,601 | 65,163,649 | How to take a integer as user input and compare it with a txt file, and then get the next line? | My question is concerning how I can get the portion where I'm input streaming from the txt file to properly loop through the text file and compare the integers and then get the next line the txt file looks something like this. I'm supposed to create this as a function and use the return values in another code. However,... |
Using while(!myfile.eof()) is not a good idea. Instead of that, you should check if readings are successful and exit from the loop when it failed to read.
Using std::getline after >> operator of ifstream will cause trouble because >> will leave newline character after things read and std::getline will stop at that.
Yo... |
65,163,779 | 65,163,802 | Error message "Undefined reference for std:string" | I have some code that reads the name of the file from arguments and outputs that file into the command line:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[])
{
if (argc != 2)
{
pr... | You haven't included std::string into your code. It's located in the <string> header. <string.h> is a C header which doesn't contain std::string.
|
65,163,812 | 65,164,023 | How to efficiently calculate a function on a vector of variants? | I have a vector of variants that can store either uint64_t and double types, and I want to calculate the median over them.
At any given time, the vector is composed entirely of uint64_t's or double's
The solution I have so far as outlined below works but it seems redundant in terms of code, and I want to know if there ... | The difference in the duplicated code is a type, so you can factor out a function template like this:
template<typename T>
data_variant calculate_median_impl(const std::vector<data_variant>& data)
{
std::vector<T> vec;
for (auto& i: data)
{
vec.emplace_back(std::get<T>(i));
}
co... |
65,163,878 | 65,163,939 | c++ finding argmax of vector from specific indices | from here, i know that we can get the argmax of a `vector like this:
vector<int> v{ 3, 1, -14, 1, 5, 9 };
vector<int>::iterator result = max_element(v.begin(), v.end());
int argmaxVal = distance(v.begin(), result);
// argmaxVal = 5 because v[5] = 9
How do i get the argmax of vector from index 2 to 4?
Or, in general, ... | You can simply adjust the input iterators to std::max_element:
std::vector<int>::iterator max = max_element(v.begin() + 2, v.begin() + 4); // [2, 4)
int argmaxVal = distance(v.begin(), max); // absolute index of max
You can also replace std::vector<int>::iterator with auto for convenience with C++11.
|
65,164,522 | 65,164,645 | C++ old struct operator overloading syntax changed? | I am building my old CPP codes from 20+ years ago, but g++ gives build error. Can someone explains me what has changed? Thanks. (It was fine in turbo C)
error:
t_overload.cpp:8:40: error: no matching constructor for initialization of 'Point'
Point operator+(Point& v) { return Point(x+v.x, y+v.y); }
... | Point(Point& v)
Copy constructors should take constant parameters, this should be:
Point(const Point& v)
But given what that copy constructor does, it's completely unnecessary. You can get rid of it, completely.
Point operator+(Point& v)
Similarly, the parameter to the overload should be constant:
Point operator+(c... |
65,164,548 | 65,166,546 | Is there an easy way of skip download_step if folder exists, in cmake ExternalProject_Add | I need the ExternalProject_Add in CMakeLists.txt to skip download_step for git downloads if there is already a folder with the repo cloned, like the update_step if you provide a GIT_TAG, but don't want to write a custom DOWNLOAD_COMMAND. Basically just need the project to build fully offline if the dependencies where a... | When call a function or macro, CMake allows to substitute a variable, which contains several parameters at once. That is, you may conditionally define a variable which is responsible for DOWNLOAD step:
set(FRESH_DOWNLOAD off CACHE BOOL "download a fresh copy of all dependencies")
include(ExternalProject)
if (NOT FRESH... |
65,164,784 | 65,164,923 | Adafruit RTClib TimeSpan calculation fails on ESP32 | I'm currently trying to measure remaining time until a given timestamp using Adafruit's RTClib library. My RTC module is a DS3231.
here is my TimeSpan object in code:
TimeSpan remaining = next.depart - rtc.now();
However when i try to print the remaining minutes i get no data.
Here is my code that prints the output:
... | Your line of code:
Serial.println(String("remaining time: " + remaining.minutes()));
is not doing what you think it's doing.
remaining.minutes() returns type int8_t not type String. You're adding it to a C character pointer to the C string remaining time: - if the value is greater than the length of that string th... |
65,165,060 | 65,165,061 | How is it possible to find all occurrences of a method if the Visual Studio „Find All References“ does not work? | The special case I am dealing with is to find all usages of the method
CTime::Format in the entire solution. Please assume that the Visual Studio functionality „Find All References“ does not work for this case.
| In order to find all usages of the method CTime::Format follow the steps:
Step 1: Replace the string CTime by the string CCTime in the entire solution.
Step 2: Implement the following:
#include "atltime.h"
class CCTime : public CTime
{
public:
[[deprecated("--> uses the method CTime::Format")]]
CString Format(... |
65,165,243 | 65,165,476 | So I'm having this problem with rejecting decimals from ((a % 1) != 0) | So im having a problem with rejecting decimals, Im rejecting any characters but when it comes to decimals it just seems not to be working. ((a % 1) != 0) was the equation i used
Also, I'm having a problem with the do loop, when the user inputs 'y' or 'Y' it seems to double the last value that was recorded from the pre... | Recommendation:
pass a and b by ref.
int whatItDoes(int* a, int* b) --> int whatItDoes(int& a, int& b)
Your Question:
if I understand your code correctly - an ascii character '.' translates to the numeric value of 46 (google Ascii table). So, 46 % 1 == 0.
You can explicitly check for the decimal, if( (a % 46) == 0 ), ... |
65,165,501 | 65,165,626 | 2d array with index input function in c++ | i have a problem with input array in function ;
in this code i take an array parameter with the indexes from user and the function will print the table of 2D array with parameter reserve it ;
here is the code :
#include <iostream>
#include <windows.h>
using namespace std ;
const char * table[3][2]={{"m1",... | An array of arrays cant simply be converted to a single pointer.
Generally, when you need to do C-style casting (like in (char * )table) you should take that as a sign that you do something wrong.
Now to solve your problem... You have to remember that arrays naturally decays to pointers to their first element. That is,... |
65,165,690 | 65,188,991 | Vulkan Push Constants never assigned or updated | I have been reading through Sascha Willem's example on push constants here and have attempted to implement them myself.
Oddly the VkPhysicalDeviceProperties.limits.maxPushConstantsSize is 1437341456 bytes which makes me think something else is very wrong. After rechecking it is showing as a more realistic value of 256 ... | After taking a look at your shader, this does not seem to be a problem related to the push constants, but rather the lack of taking the actual vertex position into account.
In this line:
gl_Position = ubo.proj * ubo.view * ubo.model * vec4(pushConsts.position, 1.0);
You only multiply the push constant position, which ... |
65,166,023 | 65,419,667 | Compiling C++ GUI for Windows (on macOS) | I'm using macOS Catalina (v10.15.7) to compile the following example code from gtkmm's online book:
#include <gtkmm.h>
int main(int argc, char *argv[])
{
auto app = Gtk::Application::create(argc, argv, "org.gtkmm.examples.base");
Gtk::Window window;
window.set_default_size(200, 200);
return app->run(wi... | From an element chat room, I was told that the pkg-config on macOS seems to be using the macOS version of its libraries for compiling. Even if compile-time errors like uid_t are resolved, the libraries wouldn't be able to link properly.
In the end, it was much easier to compile the executable directly on a Windows mach... |
65,166,128 | 65,166,221 | OpenGLES 3.0: "Only consts can be used in a global initializer " | I am a newbie following the book <OpenGL ES 3.0 cookbook> chapter2, but I get stuck with this error during installing the demo APP with this:
2020-12-06 16:16:10.888 7549-7578/com.demo.hellosquare E/glOpenGLES3Native: Could not compile shader 35633:
ERROR: 0:6: 'RadianAngle' : Only consts can be used in a global initia... | The issue is related to the line:
mat2 rotation = mat2(cos(RadianAngle),sin(RadianAngle),
-sin(RadianAngle),cos(RadianAngle));
rotation is a variable in global scope. Global variables can only be initialized with constant expressions. RadianAngle is not constant because it is a uniform variable. T... |
65,166,281 | 65,166,293 | C++ and ambiguous treatment of string literals | In my C++/Linux application I want to create a temp folder.
The code is very simple:
std::string tempFolder(mkdtemp("foo"));
To my surprise I received a warning message:
warning: ISO C++11 does not allow conversion from string literal to 'char *'
Ok, as I remember C++ treats string literals as std::string, not a cha... | mkdtemp(3) - Linux manual page says:
The mkdtemp() function generates a uniquely named temporary directory
from template. The last six characters of template must be XXXXXX
and these are replaced with a string that makes the directory name
unique. The directory is then created with permissions 0700. Since
it will b... |
65,166,317 | 65,166,841 | Array of k-digit integers with digits of sum s | my task is to make a program that finds max and min element of array of k-digit numbers whose digits are equal to s. For example,
input: 1 3
output: 101 101
input: 2 3
output: 200 101
I've got correct outputs for this examples, but when I enter "10 10" program does not work and it gives runtime error.
#include <iostrea... | As usual, such questions should not be answered using brute force. This will result in high time and memory consumption.
With this kind of questions, always the good algorithm will win.
So, let's think. One requirement is to find a value with the maximum sum of its specified number of digits. What would be the maximum ... |
65,166,777 | 65,167,190 | Multiple calls to setlocale | I am trying to figure out how Unicode is supported in C++.
When I want to output multilingual text to console, I call std::setlocale. However I noticed that the result depends on prior calls to setlocale.
Consider the following example. If run without arguments it calls setlocale once, otherwise it makes a prior call t... |
Is there something that setlocale(LC_ALL, NULL) does that needs to be taken care of in future setlocale calls?
No, setlocale(..., NULL) does not modify the current locale. The following code is fine:
setlocale(LC_ALL, NULL);
setlocale(LC_ALL, "ru_RU.UTF8");
wprintf(L"Привет!\n");
However the following code will fail... |
65,166,782 | 65,166,829 | SFML C++: mysterious bugs happening in my software possibly relating to <iostream> and header files? | I am making a project and to keep it organized I made a header file called include.h that will store all the global variables and includes.
yesterday it worked but today it puts me some weird bugs and I can't find the answer to them.
#include <SFML/Graphics.hpp>
#include <iostream>
#include <stdio.h>
enum GameModes { ... | I think the redefinitions are happening due to lack of header guards!
Maybe today you are including that header in two files, so now that code gets ran twice and thus all it's symbols redefined.
You can also use #pragma once at the beginning of all your header files to tell your linker to only include that file once.
H... |
65,166,862 | 65,169,212 | Unordered map vs map | Does anyone know why Dict class is invalid but Dict2 is fine?
#include <string>
#include <unordered_map>
#include <map>
#include <variant>
class Dict
{
public:
Dict() {}
private:
std::unordered_map<std::string, std::variant<Dict, std::string>> data;
};
class Dict2
{
public:
Dict2() {}
private:
std:... | I believe the behavior is undefined in both cases. Dict2 just happens to compile by accident of implementation; "seems to work" is one possible manifestation of undefined behavior.
[res.on.functions]/1 In certain cases (replacement functions, handler functions, operations on types used to instantiate standard library ... |
65,166,896 | 65,166,913 | Operator equals overloading c++ apparently not working | Can someone explain me why the cout doesn't get called here?
#include <iostream>
using namespace std;
class Test {
public:
int a = 1;
Test &operator=(const Test &other) {
cout << "overloading here" << endl;
return *this;
}
};
int main() {
Test t1;
Test &t3 = t1;
return 0;
}
... | Test &t3 = t1;
is creating a reference for Test and initiaizing that. = operator is not used there.
There are no cout other than inside operator=, so cout won't be called.
Note that
Test t3 = t1;
(without &) will also not call operator= because this is an initialization of object and a constructor is used for... |
65,166,912 | 65,167,438 | Guaranteed copy elision for uniform braced array initialization - Shouldn't this be mandatory since C++17? | As far as I understand the new rules correctly
https://en.cppreference.com/w/cpp/language/copy_elision
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0135r0.html
This code should compile for C++17 standard conform compilers
struct NonTrivialClass
{
~NonTrivialClass( ){ }
};
class MainNonTrivialClass
{
... | This should also work pre-C++17, where this syntax is direct-initialization. See How to initialize array of classes with deleted copy constructor (C++11) which refers to GCC bug 63707.
|
65,166,936 | 65,167,086 | How to create a class and store it instead of just creating it | I have a Window and a Renderer class. The following is how I instantiated these classes.
class SDL_UI
{
private:
Window window;
Renderer renderer;
Event event;
public:
SDL_UI(const char* name, int sw, int sh)
{
init();
window = Window(name, sw... | The first thing I would try is to use an initializer list
SDL_UI(const char* name, int sw, int sh) : window(name, sw, sh), renderer(window)
{
init();
while (true)
{
if (event.handleEvents()) SDL_Quit();
}
}
This avoids the default construction, copying and assign... |
65,166,958 | 65,167,303 | How to get the std::fill function to work with a std::map? | I want to use the std::fill function from the algorithm library to fill in '-' in the second part of the pair. Is this possible to achieve?
#include <algorithm>
#include <map>
int main()
{
std::map<int, unsigned char> board(10);
// What I want the std::fill to do the equivalent of
for (auto& cell : board... | fill assigns to each element of the range it is called on, whereas you want to assign to the values of those elements (key-value pairs). From C++20 you can use the ranges::views::values range adaptor:
std::ranges::fill(std::ranges::views::values(board), '-');
If you can't use C++20, your code will work by changing fil... |
65,167,716 | 65,167,800 | a bug with if and else if statement | I'm making this for my college project, my problem is whenever I put these 3 specific inputs: 98, 95, 96; it will output 96.33333, and it would never output the Equivalent Grade line. Sorry I'm just a beginner, I'm still not familiar to coding jargons. Can anybody help me how I could fix this bug? I would appreciate it... | Neither the first condition
if(gen <= 100 && gen >= 97)
nor the second one
else if (gen <= 96 && gen >= 94)
apply here. Specifically 96.333 is neither >= 97 nor <= 96 but in between.
A simple solution would be to round gen:
gen = std::round(gen);
|
65,167,794 | 65,903,113 | Can you use a variable into an argument in c++? | I am making a simple mp3 player and I want to involve user input as part of a mciSendString function in c++ where the user can enter the mp3 file name and it is appended to the mciSendString argument. My code is as follows
string x;
mciSendString(_T("open \"x\" type mpegvideo alias mp3"), NULL, 0, NULL);
You see, obvi... | I found how to do it. Based off @Remy's answer, I concatenated the strings and used c_str() function. Thank you all anyways for your help.
|
65,167,951 | 65,168,054 | I am trying to push each letter of a word into a vector, but it is throwing an error | This is my code:
#include <iostream>
#include <string>
#include <bits/stdc++.h>
using namespace std;
int main()
{
string word = "hi";
int i = 0;
vector<string> vec;
for(i ; i < word.length() ; i++)
{
vec.push_back(word[i]);
}
return 0;
}
I am trying to push each letter of string "hi" into a vector vec using for ... | Indexed access ([] operator) on std::string returns char& and not std::string itself.
Vector declared is vector of string so insertion into vector requires string type not char&
If you want to have vector of char, change accordingly
|
65,168,140 | 65,214,098 | Function pointer reference | I need to hook 10/20 functions like these:
static void* __cdecl HookSoundFileSubBZR(char *FileName, int a2, int a3, int a4);
__declspec(naked) void HookSoundFileSub_BZCC_Asm(char *Src, int pedx, int
a3, int a4, int a5, int a6);
static BOOL HookSoundFileSubWCP(int a1, DWORD *a2, DWORD *a3, int a4, c... | Just declare
PVOID HookFunction;
and then
HookFunction = (PVOID)HookSoundFileSubBZR;
etc. (But you want HookFunction in the DetourAttach call, not &HookFunction.)
|
65,168,584 | 65,168,708 | error: could not convert 'tab' from 'vector<std::vector<std::__cxx11::basic_string<char> >>' to 'vector<std::__cxx11::basic_string<char>>' | here is my code which write a column j of a board t in an other board tab! I am a beginner so I don't understand the problem :(
vector<string> colonne(vector<vector<string>> t, int j) {
vector<vector<string>>tab;
for(int i=0; i<t.size(); i++){
for(int n=0; n<=j; n++){
if(n == j){
... | Your code has numerous problems. I think (based on your description) that the code you are trying to write is this
vector<vector<string>> colonne(vector<vector<string>> t, int j) {
vector<vector<string>> tab(t.size());
tab[j]=t[j];
return tab;
}
The code above creates a new board tab with the same number ... |
65,168,841 | 65,168,990 | How to cast an integer to a constant void pointer? | int getNumber(){
int number;
cin >> number;
return number;
}
const void * getPointer(){
const void *p = (const void *)getNumber();
return p;
}
Gives me an error:
warning: cast to pointer from integer of different size
and the console crashes
| getNumber() returns a copy. You cast the copy to a pointer. (There is a difference between the copy and the address of the copy, which is what the pointer should be)
int nb = getNumber();
const void *cp_void = (const void *)nb; // this will not yield the expected result.
int *p_nb = &nb; // memory adress to variable ..... |
65,168,905 | 65,169,234 | Can't use <filesystem> in visual studio | I'm trying to use filesystem, but it doesn't work in VS19. Even with /std:c++17. Any ideas why? Maybe I have to install some special packages?
Edit. Compilation error:
Edit 2. header:
| Make sure that you apply the /std:c++17 setting to all configurations. The default behavior of changing project properties only updates the active configuration. In my brief testing I had the Intellisense error with Visual Studio 2019 Version 16.7.3 until I made this switch.
|
65,169,083 | 65,169,257 | Enum: type name is not allowed | I am a .Net C# programmer trying to program in C++. I have an application that uses a third party library. When i try and use an Enum from the library in a function for this library I get an error message of type not allowed:
I have included the library:
#include <Trading.h>
using namespace Trading;
Trading.h include... | The syntax for naming a member of an unscoped enum declared in a class or namespace TimeInForce is:
TimeInForce::Day
The period (.) is used for accessing non-static members of classes.
|
65,169,178 | 65,169,516 | How do I use binary arithmetic operators in combination with templates? | I've written a class Number that contains only one attribute: T value. I'm currently learning about templates, so T is the data type. What I want to achieve is doing the following sort of computation.
Number<int>(2) + Number<double>(1.2)
What I have so far can do a operation, but it fails when there are two different... | Besides declaring a friend operator+ with two template parameters as suggested, you can also place a secondary template for the member function operator+, which allows you to do casting plus.
template<typename T>
class Number
{
public:
T value;
Number(const T&num1)
{
value = num1;
}... |
65,169,389 | 65,169,434 | Set an element of a `const` array as the length of another array in c++ | I defined a const int array like this :
const int arr[] = { 100 , 200, 300, 400 };
Now i want to set one of the elements of above array as the length of another array like the following :
char buffer[arr[3]];
But it gave me a compile time error :
non-constant arguments or reference to a non-constant symbol
I studi... | There are really two different kinds of constant "things" in C++.
The one that you know as the const keyword: you can't modify it at runtime.
And the one that's known as a constant value to the compiler at compile time.
That one would be:
constexpr int arr[] = { 100 , 200, 300, 400 };
C++ requires an array size to be ... |
65,169,415 | 65,169,619 | Efficient & safe intersection of more than two sets | Here is a C++ program which uses std::set_intersection twice to compute the intersection of 3 sets (then prints the result). It produces the expected result 3 but:
Is it safe to pass in 'newset' as both a source & destination set in the second call to set_intersection? As I understand it, with begin() and end() I'm pa... | As you can read on cppreference,
[...] The resulting range cannot overlap with either of the input ranges.
so you're in undefined behavior land.
As a proof by verification of this, I can tell you that I've copied your code, compiled it, run it, and for me it prints 23, so your correct result is just a coincidence.
Th... |
65,169,577 | 65,169,683 | Can I set up structs to 'using' a type when given a type? ('explicit specialization of non-template struct') | I have the following struct and there will be many of these with different 'input' and 'output' types.
#include <string>
template <>
struct Corresponding<const char*> {
using CorrespondingT = std::string;
};
This causes the error:
explicit specialization of non-template struct
'Corresponding'
templa... | You simply forgot to declare the primary template.
#include <string>
// You need this
template <typename T>
struct Corresponding;
template <>
struct Corresponding<const char*> {
using CorrespondingT = std::string;
};
Without it, as the error says, Corresponding is not a class template (or indeed anything), so ca... |
65,169,587 | 65,170,715 | How to improve time efficiency of CRC-5 calculation? | I have just started to study the CRC and how to implement it in software. My information source is mainly following document. Here is mentioned some simple algorithm for calculating CRC for any generator polynomial. I have attempted to write this algorithm in C++ language. I have tested it for generator polynomial x^5... | Just a quick glance shows several unnecessary statements. You don't need crc &= ~1U;, since the crc = crc << 1; already put a zero there. You don't need message = message & ~0x2000;, since you are only ever looking at one bit in there. Just let the other bits shift up and away. You don't need the crc = crc & ~0x20;, s... |
65,169,944 | 65,170,092 | Char variable goes Over the limit | I'm doing an intensive course in C++ and I am the kind of person that likes and wants to understand everything under the sun otherwise I can't continue with my homework.
char anything[5]{};
cin >> anything;
cout << anything << endl;
I can write 'Hello' in the console and it's all good. Writing 'H' is good too, and 'He... | [trigger warning: car crashes, amputations, cats]
if I write over 5 characters the program shouldn't allow it, but it does.
That's an overstatement.
The language doesn't allow it, but the compiler and runtime don't enforce that. That's because it would deduct from performance to perform bounds checking all the time ... |
65,170,061 | 65,170,293 | HBITMAP, created by CreateCompatibleBitmap is black and white | I have read an article about backbuffering, which I have recreated in the following way:
void paint(HWND handle)
HDC device = GetDC(handle);
HDC backBufferDevice = CreateCompatibleDC(device);
RECT boundRect;
GetClientRect(handle, &boundRect);
HBITMAP backbufferBmp = CreateCompatibleBitmap(
... | So after looking into the question a little bit further, it seems like I was doing the backbuffer HBITMAP wrong. It should be created as compatible with the main HDC:
...
HDC device = GetDC(handle);
HDC backBufferDevice = CreateCompatibleDC(device);
RECT boundRect;
GetClientRect(handle, &boundRect);
HBITMAP backbuffe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.