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,451,707 | 65,451,862 | Shouldn't "int i = *(short *) & float" preserve the sign? (C++) | The following Python3+ code attemps to compile a Cpp script and use it to convert from float to int while leaving the memory untouched; it is as follows:
import sys, os
import numpy as np
import matplotlib.pyplot as plt
# Build a C++ Script that accepts a str,
# converts it to a float, and prints
# the result of the... | The first problem with your code is that it is undefined behavior to read data which is one type as another unrelated type without certain properties, like a common prefix, or using a few types, like std::byte or char.
std::bit_cast is a c++20 way to do it correctly.
The second problem is that what the exact bits mean ... |
65,451,733 | 65,452,102 | Mac OS binary unable to open files | I am trying to compile a binary file that will open a txt file in the same directory that it is in next to it, read its components, store the first word into a string, and print it out. Here is the code:
#include <iostream>
#include <fstream>
int main(){
std::ifstream is;
is.open("text.txt");
std::string s... | Please use one of the solution provided in C++ Find execution path on Mac to find the path of executable and then you can use one of the solution from get directory from file path c++ and use it for your needs.
|
65,451,877 | 65,451,994 | How to safely call TerminateThread and FreeLibrary (WinAPI, C++) | I used to unload an injected library by calling FreeLibraryAndExitThread from a thread that was created using CreateThread.
The need to unload the library from a different thread rendered this approach impossible. Now I'm using TerminateThread (as it doesn't terminate the thread it's called from, but the one that is pa... | The only way to terminate a thread safely, in C++ especially, is to have that thread return from the function passed to CreateThread. This is usually done by setting (say) an atomic<bool> that the thread tests regularly to see if it should exit. You might also use a condition variable (or the Win32 equivalent) to wak... |
65,452,040 | 65,454,823 | Is there a performance difference by wrapping the code in an immediately invoked lambda expression? | Here is some code:
void f()
{
// stuff
{
// code
}
}
It is also possible to write it in a strange way like this using lambdas instead of braces:
void f()
{
// same stuff as above
[&]{
// same code as above
}();
}
Will there be any performance difference between the two versio... | Performance is hard to measure. Yet in this case it's still reasonable to reason about it.
Every lambda is actually its own class with operator() implemented. This class has the same characteristics as one written in an unnamed namespace. Some relevant elements: its visibility is limited to the .cpp file and linked to ... |
65,452,144 | 65,455,271 | Make wreturn-type an error, not a warning? | I am on gcc, it gave me a warning that i forgot a return value in a function with Wreturn-type.
However, I don't want it to be a warning, I want it to be an actual compiler error. Is there a way to stop compiling when Wreturn-type is encountered?
|
Is there a way to stop compiling when Wreturn-type is encountered?
You can make any warning an error with:
-Werror=return-type
You can make gcc "stop" compiling on errors with:
-Wfatal-errors
Make sure to read your compiler documentation.
|
65,452,234 | 65,483,176 | Visual Code C/C++ formatting of braces {} | In VSCode, I wanted my opening curly braces { to be in the same line, instead of a new line and for that I changed C_Cpp.clang_format_fallbackStyle from Visual Studio to LLVM, which seemed to work.
But it does this thing which I don't want, which is it formats my if-else statements like this:
if (condition){
do_som... | In your VS Code settings should be able to do something like
"C_Cpp.clang_format_fallbackStyle": "{ BasedOnStyle: LLVM, BreakBeforeBraces: Custom, BraceWrapping: { BeforeElse: true }"
For more info:
https://clang.llvm.org/docs/ClangFormatStyleOptions.html
Visual Studio Code formatting for "{ }"
https://code.visualstudi... |
65,452,272 | 65,452,390 | Iterating over vectors in a parameter pack | I have a function that takes in a parameter pack of vectors, These vectors will be of the same length, and I want to call a function with the values of both of these vectors at each index.
For example I pass in a function which prints out two integers that I pass in. I would put in two vectors of integers to the functi... | Something along these lines, perhaps:
template<typename RETURN, typename ... INPUTS>
std::vector<RETURN> thread_transform(
std::function<RETURN(INPUTS ...)> function,
std::vector<INPUTS>& ... inputs)
{
std::vector<RETURN> ret;
auto size = std::min({inputs.size()...});
for (int i = 0; i < size; ++i) ... |
65,452,293 | 65,452,362 | Tree implementation without using pointers? | I found this code somewhere that is a simple implementation of a tree. Is there a reason why the left and right have to be pointers to Node? In other words, can you still implement a tree without left and right being pointers and just being of type Node? If so, could someone please provide an example
#include <iostream... | A simpler example of a linked list, ie each Node has only one next:
struct Node {
Node next;
};
C++ does not allow this, you will get an error, but lets consider for a moment there was no error. Then every Node contains another Node and that member again contains another Node. And that Node has another member next... |
65,452,374 | 65,452,425 | How the linker find the correct library? | I know what preprocessing is, how compiler works, and how linker links the object files
But what I still haven't been able to answer is :
In an IDE like VS
suppose we have a library called DariushTest.o that implemented a function called print() and have a header file called test.h
and we have other libraries that impl... | So how linker links the print() function from DariushTest.o not from other libraries?
It doesn't. If you break the ODR by having the same function name in 2 different compilation units, then the behavior of the program is undefined. The linker might notice and diagnose the redefinition and might not.
|
65,452,477 | 65,452,583 | Download image from HTTP request triggering a breakpoint | I am trying to download an image onto the user's desktop from a URL using Win32. I have taken care of all the HTTP request stuff and know for a fact that it is all working well. When I go to call CreateFile() the Visual Studios debugger just says "Exception: Application.exe has triggered a breakpoint" and that it will ... | The way you are using filepath is all wrong.
You are declaring it as an array of MAX_PATH (260) number of PWSTR pointers.
When you refer to an array by its name alone, you end up with a pointer to the 1st element of the array. So, &*filepath is the same as &*(&filepath[0]), which is effectively &filepath[0]. And *filep... |
65,452,671 | 65,452,876 | std::cout does not print float as excepted | Why does std::cout << 1.00000001; print 1 to the console?
It Works fine with 1.0001, Its only after it exceeds a certain precision when it stops printing it properly.
These numbers are hard coded, so this question is not a duplicate. In that question, an irrational number was produced because two floating point numbers... | Summarizing my comments:
The number 1.0000001 cannot be represented by a float.
The compiler will pick a float value.
It can round however it wants (up, down or closest), that's implementation-defined.
So if you play a bit with this converter, you can see that after 1, the next float values are:
1
1.0000001192092895... |
65,453,464 | 65,461,462 | Successfully initialize XAudio2 in a Visual Studio Community 2019 Solution | From 'How to Initialize XAudio2' in Windows Developer
Microsoft Windows 10 SDK
Visual Studio 2019 Community
Microsoft.XAudio2.Redist NuGet package installed
Intel(R) Pentium(R) CPU 4415Y @ 1.60GHz x64
Windows 10 Pro for Workstations 64-bit operating system
The following code example:
#include <iostream>
#include <xau... | If you use an Error Lookup Tool, you'd see that 800401F0 translates to CO_E_NOTINITIALIZED.
As noted in the comments, you have to initialize COM first:
HRESULT hr = CoInitializeEx( nullptr, COINIT_MULTITHREADED );
if (FAILED(hr))
// error
I submitted an edit to note that fact on the Microsoft Docs page.
You shoul... |
65,453,470 | 65,453,569 | Inputting a file address from a .text file to OpenSSL encryption function in C++? | I want to direct multiple lines of output from a .txt file to that encrypt() function. The .txt file contains addresses of files I want to encrypt. The code compiles but no encryption pans out. I am using EVP_aes_256_cbc() for encryption. What am I doing wrong?
int encrypt(unsigned char* plaintext, int plaintext_len, u... | In C++, \ is used in escape sequences, so you have to write \\ to express \ in string literals.
You actually did this for the first and last \, but you have to do this for the other \s.
std::ifstream file("C:\\Users\NULL\source\repos\xFolder\YFolder\\test.txt");
should be
std::ifstream file("C:\\Users\\NULL\\s... |
65,453,829 | 65,454,120 | Fixing input problems in C++ for reference variables | bool isSafe(char arr[][N],int r,int c)
{
//to check that queens are not in the same column
for(int i=0;i<=r;i++){
if(arr[i][c]=='Q')
return false;}
//to check that queens are not in the same left diagonal
for(int i=r,j=c;i>=0&&j>=0;i--,j--){
if(arr[i][j]=='Q')
return false;}
//to check that queens are not in the same... | The simple solution is to use a vector.
int n;
cin >> n;
vector<vector<char>> v(n, vector<char>(n));
solveNQueen(v, 0);
bool isSafe(vector<vector<char>>& v,int r,int c)
{
int n = v.size();
...
}
If you need to know the size of a vector you can get it using the size method, v.size();.
|
65,454,059 | 65,454,069 | C++ The value of my input variable changes by itself? | int main() {
int m;
cin >> m;
int len = 0;
if (m <= 1) {
cout << m << endl;
return 0;
} else {
int a[] = {
0,
1
};
for (int i = 2; i <= m * m; ++i) {
cout << "second" << m << " " << m * m << endl;
a[i] = (a[i - 2... | The array a has only 2 elements, so writing (and reading) to a[2] and above is not allowed.
You should use std::vector to dynamically add elements to arrays.
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
int main() {
int m;
cin>>m;
int len=0;
if(m<=1) {
... |
65,454,103 | 65,454,162 | Do std library `emplace` functions make use of `std::in_place` tag | I want to know whether C++ standard library emplace functions make use of std::in_place tags (to indicate that the contained object should be constructed in-place)? Because emplace function got introduced in c++11 and std::in_place in c++17.
| The entire point of emplace and its ilk is to indicate that the object is being constructed in-place. The implementation isn't allowed to construct the item and copy/move it to its final location.
The main reason in_place is used in constructors is because constructors have to use overload resolution to tell which cons... |
65,454,398 | 65,454,422 | How to split a string into a vector by end of line | Hello so I'm trying to split the incoming request into a vector by line.
(example request)
GET / HTTP/1.1
Host: 192.168.0.51
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safar... | Simple solution would be to use a istringstream and getline.
#include <string>
#include <vector>
#include <sstream>
std::string request = ...;
std::istringstream buffer(request);
std::vector<std::string> lines;
std::string line;
while (getline(buffer, line))
{
lines.push_back(line);
}
|
65,454,427 | 65,455,433 | How do I give my include access to my source folder so when the library is used it can be indirectly accessed to the source via the include file? | Right now I have to do this to indirectly access my source headers
#pragam once
#include "../src/some_folder/some_header.hpp"
But I want to be able to access it like this
#pragam once
#include "some_folder/some_header.hpp"
so it looks much cleaner
Basically, since I want the headers of my library to be accessed ind... |
Basically, since I want the headers of my library to be accessed indirectly through one main header called Some_Libaray_Name.hpp.
If the main header includes a header, this header either needs to be a system header or it needs to be a header that is available at compile time. For this reason your classification of th... |
65,454,437 | 65,454,703 | friend funciton error: 'B' has not been declared | I tested the following code(just for test, I know it's a bad idea), and I couldn't understand why it has an error. Please help me!
There are two classes A and B, both in separate hpp files. I let them include each other(I think it doesn't matter because of the include guard), and it didn't go wrong until I added the de... | You do not ask for a solution, you ask for the reasons that your two workarounds remove the error, good way of learning. My respect.
In order to understand why you get the error and why you can get rid of it with the two methods you found yourself, you should "play preprocessor" and do the including yourself, while obs... |
65,454,449 | 65,454,513 | c++ class member function pointer does not work rightly in class | The member function pointer of objects are different, but they run on the same member function.
Code as follows:
class A {
public:
A *child = NULL;
void (A::*_backwardFunc)() = NULL;
void FuncA()
{
cout << "This is function A." << endl;
}
void FuncB()
{
cout << "This is func... | For a.print();, in print(), (child->*_backwardFunc)(); is calling a._backwardFunc (on child), it points to A::FuncA . If you want to call child->_backwardFunc (which points to A::FuncB), it should be
(child->*(child->_backwardFunc))();
LIVE
|
65,454,785 | 65,455,316 | Qt subdirs: use common source files | I need to use common source files (not library!) for two projects in Qt. I've created such structure:
main
main.pro
common.pri
project1
project1.pro
project2
project2.pro
shared
(common *,cpp, *.h, etc)
Each project*.pro contains a link to common.pri:
include(../common.pri)... | Since those source files don't belong to a project, they won't show up in the Projects view. But if you have a common folder in that very view, which refers to the common.pri, just right-click on it and use Add existing directory ... to add the shared folder and have the stray files in the view.
I don't really know wha... |
65,454,819 | 65,454,879 | What's the sequence of code running in the fields of derived class.?I want to know why I got this output,I cant understand it | I don't know the sequence of the code running,Please teach me
When I create a point A *p=new C, what happen?I even can't understand this equation,why their class are different and it still can be compiled?
#include <iostream>
using namespace std;
class A
{
public:
A( ){cout << "A Constructor" << endl;}
virtual ~A... |
A *p=new C; creates object of class C, creation of this object involves next steps.
Constructor of class A is called, because if C is derived from some bases then first all bases constructors are called.
In constructor of A string A Constructor is outputed, hence first string of output.
Then constructor of B is cal... |
65,455,024 | 65,455,067 | Mutilple definition when linking object files | Suppose we have B.h, main.cpp and B.cpp, main.cpp -> main.obj and B.cpp -> B.obj
Because of separate compilation, I think main.obj and B.obj should both have the definition of class B. Why it doesn't have the error:multiple definition of B when linking them?
B.h
#ifndef B_H
#define B_H
class B {
public:
vo... | Neither main.obj nor B.obj contains the definition of B. Object files have no need to contain type definitions, since the purpose of type definitions is to help produce the executable code and data for an object file. If two source files both operate on the same type, they both need to have that type’s definition inclu... |
65,455,464 | 65,455,611 | Is the Rule of 5 (for constructors and destructors) outdated? | The rule of 5 states that if a class has a user-declared destructor, copy constructor, copy assignment constructor, move constructor, or move assignment constructor, then it must have the other 4.
But today it dawned on me: when do you ever need a user-defined destructor, copy constructor, copy assignment constructor, ... | The full name of the rule is the rule of 3/5/0.
It doesn't say "always provide all five". It says that you have to either provide the three, the five, or none of them.
Indeed, more often than not the smartest move is to not provide any of the five. But you can't do that if you're writing your own container, smart point... |
65,455,597 | 65,456,179 | Adding scalar to Eigen matrix (vector) | I just started using Eigen library and can't understand how to add a scalar value to all matrix's members?
Let's suppose that I have a matrix:
Eigen::Matrix3Xf mtx = Eigen::Matrix3Xf::Ones(3,4);
mtx = mtx + 1; // main.cxx:104:13: error: invalid operands to binary expression ('Eigen::Matrix3Xf' (aka 'Matrix<float, 3,... | Element-wise operations with Eigen are best done in the Array domain. You can do
mtx.array() += 1.f;
A slightly more verbose option would be:
mtx += Eigen::Matrix3Xf::Ones(3,4);
You should also consider defining mtx as an Array3Xf in the first place:
Array3Xf mtx = Eigen::Array3Xf::Ones(3,4);
mtx += 1.f;
If you then... |
65,455,821 | 65,455,853 | C++ How to call a Child Method from Parent | I'm working on a small project, and I found myself in a situation like this :
class A{}
class B : class A {
public:
void f();
int getType() const;
private:
int type;
}
class C : class A{
public:
int getType() const;
private:
int type;
}
I want to know if there'... | As you've seen, this code won't compile because A doesn't have an f method. In order to make it work, you'd have to explicitly downcast the pointer:
B* tmp = dynamic_cast<B*>(v);
tmp->f();
|
65,456,066 | 65,456,147 | How to use std::unordered_multiset with a custom class? | I am trying to declare an unordered_multiset which is going to contain objects of a custom class, but I can't find any examples out there for this. Following the documentation, it seems that I need to declare an operator== in the class, alongside the hashing function(operator() const) which, as per the documentation:
... | you can replace string with your struct i guess:
#include <bits/stdc++.h>
using namespace std;
// Custom Hash Functor that will compute the hash on the
// passed string objects length
struct StringHashBySize {
public:
size_t operator()(const std::string & str) const {
int size = str.length();
retur... |
65,456,145 | 65,456,999 | File scope variables in C++ optimised differently in gcc and clang | I was playing around with Godbolt and I was surprised to see that the following simple C++ code had different compiled outputs on x86-64 gcc 10.2 and x86-64 clang 11.0.0 with -O2 level optimization.
static int x = 0;
int const y = x;
int main()
{
x = 0; // should be optimised out?
}
gcc:
main:
mov DWO... | Optimizers only optimize whatever got implemented into them.
In this case, I believe that Clang is correct with the optimization as the initialization in main is the very first assignment happening to a global.
This global can't be touched, as initialization of globals over multiple compilation units can't rely on glob... |
65,456,266 | 65,456,342 | Is std::vector::data() reallocation-safe? | As far as I know, taking a pointer or reference to std::vector element is considered bad practice. But what about std::vector::data()? Does the pointer taken by data() remain valid after reallocation?
|
As far as I know, taking a pointer or reference to std::vector element considered as bad practice.
References and pointers can avoid copying overhead, which is not a bad practice if you can ensure that the std::vector will not be reallocated during the reference or pointer lifetime.
(BTW, in C++, there is no need to ... |
65,457,181 | 65,457,223 | does std::move make sense on a stack variable | I need to create a list of struct of size 1024. So I'm trying to optimize push operation into the list by making use of move semantics. But move semantics makes sense only for heap allocated memory(as per my knowledge). Can somebody suggest me a better way of doing this. This is my code
#include <iostream>
#include <li... | Given your current definition of St:
struct St {
int32_t arr[1024];
};
Technically, moving and copying both results is the same for this particular definition of St.
However, semantically it does make sense to mark st for moving as you are done with it, and st will be destroyed anyway. For example, if you later de... |
65,457,302 | 65,457,342 | Returning constructor arguments in braces? | I am new to C++ and the brace initialization (or uniform init) really is confusing. What exactly happens when a function returns a list of arguments in braces? Thanks a lot for claryfying.
std::vector<double> foo()
{
return {1, 2}; // is this the same as: std::vector<double>{1, 2} or std::vector<double>(1, 2)? or som... | return {1, 2};, the return value is list-initialized from {1, 2}, as the effect, the returned std::vector<double> contains 2 elements with value 1 and 2.
return std::vector<double>{1, 2};, the return value is copy-initialized from std::vector<double>{1, 2}, as the effect, the returned std::vector<double> contains 2 ele... |
65,457,636 | 65,458,240 | How to correctly destroy window that is running from another thread? | The goal that I am trying to achieve is to listen session notifications about lock, unlock and so on. I have to do it in another thread due to architecture and avoiding blocking main thread. Here is what I am doing:
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
... | Provided WndProc function handles WM_CLOSE and WM_DESTROY.
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
So you could send WM_CLOSE message with hwnd of the window created in the thread:
PostMessage(hwnd, WM_CLOSE, 0, 0)
|
65,457,817 | 65,457,922 | How to make void not return when answer == true | I made this program and when I type "yes" it should end my program instead it's waiting for me to say something more and then it comes with my void nottrue(); what should I do to avoid this? Here's my code
#include <iostream>
using namespace std;
void CharacterWorld();
void nottrue();
int main()
{
CharacterWorld... | While return nottrue() works , it's nothing but a function call, because both caller and called function have no returned value. You don't alter flow in any way.
You have to use results returned by function for control flow. E.g.
bool CharacterWorld()
{
//...
if (yesorno == "yes")
{
cout << " Okey! ... |
65,457,905 | 65,458,162 | Alignment of tuple of arrays for SIMD load | I have a tuple like this
tuple<array<float, 4>, array<float, 4>, array<float, 4>>
Now I wanna load those arrays into a sse register with
_mm_load_ps(get<0>(tuple).data());
_mm_load_ps(get<1>(tuple).data());
_mm_load_ps(get<2>(tuple).data());
but the intrinsic requires the memory adress to be aligned on a 16-byte boun... | You might use alignas and have something like:
template <typename T, std::size_t N, std::size_t Align>
struct aligned_array
{
alignas(Align) T data[N];
};
and then
std::tuple<aligned_array<float, 4, 16>,
aligned_array<float, 4, 16>,
aligned_array<float, 4, 16>>;
|
65,458,163 | 65,458,201 | Template argument for std::vector initialization | There is a struct called Matrix with a template argument N and data_ field:
#include <cstddef>
#include <vector>
template <std::size_t N>
struct Matrix {
std::vector<std::vector<int>> data_{N, std::vector<int>(N)};
};
Why is it not possible to initialize data_ using round brackets?
std::vector<std::vector<int>> d... | Default member initializer (since C++11) doesn't support parentheses initializer, but only braced initializer and equal-sign initializer.
Through a default member initializer, which is a brace or equals initializer included in the member declaration and is used if the member is omitted from the member initializer list... |
65,458,252 | 65,458,278 | C++, Error: expression must have integral or unscoped enum type | So I have this code.
#include <stdio.h>
int main()
{
float S, Y, P;
printf("Sisestage laenusumma eurodes:\n");
scanf("%f", &S);
printf("Sisestage laenuperiood aastades:\n");
scanf("%f", &Y);
printf("Sisestage intressim44r protsentides:\n");
scanf("%f", &P);
float K, T;
K = (S * (P /... | ^ is for bitwise operation (xor), not power.
You might use std::powf instead.
K = std::powf((S * (P / 100 / 12)) / (1 - (1 + (P / 100 / 12))), -12 * Y);
|
65,458,586 | 65,459,475 | Array queries give wrong answer | I have a problem and I have no idea how to start, here it is:
You are given a permutation of 1,2,...,n.
You will be given q queries, each query being one of 2 types:
Type 1: swap elements at positions i and j
Type 2: given a position i, print the length of the longest subarray containing the ith element such that the ... | long long atMostSum(int arr[], int n, int k, int a){
long long ans = arr[a];
for (int i = 0; i <= a; i++) {
long long sum = 0;
for (int j = i; j < n; j++) {
sum += arr[j];
if(sum > n) break;
if(i <= a && a <= j) {
ans = max(ans, sum);
... |
65,458,621 | 65,458,801 | How can I use a enum variable as template argument? | If we have an enumeration type:
enum E {
E1,
E2,
// ...
};
and based on E, a class template:
template <E T>
class C { /* ... */ };
Is there a way of using a declared variable of the type E as a template argument?
Example code:
E example_type = E1;
C<example_type> example_class;
| For integral (which an enumeration is) and arithmetic types, the template argument provided during instantiation must be a constant expression. For example:
enum E {
E1,
E2,
};
template <E enum_val>
class Foo {
};
int main() {
constexpr E var = E1;
const E var2 = E2;
Foo<var> foo;
Foo<var2> fo... |
65,458,675 | 65,458,900 | No matching function for call to sqrt | writing a function for columnwise computation of sample skewness in Rcpp I'm in trouble using sqrt()-function. I know that sqrt(x) works for NumericVector types (tested it in a separate file), however in my code (where I'm trying to pass doubles) it does not work.
Here's my code:
#include <Rcpp.h>
#include <cmath>
usin... | To be brief, there are few recurrent and common beginner errors we can avoid:
do not include unneeded headers (mostly harmless, but Rcpp already brings math headers)
do not use a globally flattened namespace Rcpp especially after you get compilation errors on symbol visibility
With that and the required minimal cha... |
65,458,745 | 65,458,876 | How to do sorting in a text file in c++ | I am working on my C++ (File Handling) Project but got stuck on a point
Here is my .txt file
SNO, Name, NoOfPeopleLiked
1, The Shawshank Redemption, 77
2, The Godfather, 20
3, Into The Wild, 35
4, The Dark Knight, 55
5, 12 Angry Men, 44
6, Schindler's List, 33
7, The Lord of the Rings: The Return of the ... | I've implemented next solution using std::regex module. Plus some strings operations. And of cause sorting!
In my code input file is called 0302.txt, please rename it to what you need before running code.
Try it online!
#include <vector>
#include <string>
#include <regex>
#include <fstream>
#include <tuple>
#include <i... |
65,458,916 | 65,459,524 | How to write a Makefile (for a c++ project) with a header in the parent directory? | I am currently struggling with make, any tip or tutorial is very much appreciated.
My project folder structure looks like this:
/project
bar.hpp
/folder1
main.cpp // #include "foo.hpp" #include "bar.hpp"
foo.cpp // #include "foo.hpp" #include "bar.hpp"
foo.hpp // #include "bar.hpp"
Makefile
Thi... | This line is wrong:
OBJ = $(SRC: .cpp=.o)
By adding a space before the .cpp you're saying that OBJ should replace all words in the variable SRC that end in " .cpp" with an ending of .o. But there are no words in the variable SRC that end in " .cpp", so no changes are made, and the value of OBJ is the same as the valu... |
65,459,286 | 65,459,484 | Unhandled exception thrown: read access violation. x was 0x20B4112 | using namespace std;
float str_to_float(char x[]) {
int j;
float val1 = x[0] - '0';
float val2=0,factor=1;
for (int i = 1; x[i] != '.'; i++) {
val1 = (val1 * 10) + (x[i] - '0');
j = i;
}
for (int k = j + 2; k != '\0'; k++) {
**val2 = val2 + (x[k] - '0')*factor;**
... | There are 2 mistakes:
For the second loop, change the condition to x[k] != '\0'.
The variable factor should be initialised to 0.1.
Also, to avoid some runtime errors (for example, in the case of 0.908), start the first loop from index 0, so that variable j has a valid value before starting the second loop.
Have a loo... |
65,459,418 | 65,459,606 | How to translate Morse Code to English in C++? | I am currently trying to find a way to create a function to translate morse code to english. Here's my code (NOTE: NOT THE WHOLE CODE)
int main()
{
string const morseCode[] = {".-", "-...", "-.-.", "-..", ".", "..-.",
"--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-",
".-.", "...... | What you are doing here is you are not splitting the code into letters using " " as the separator. Try this,
string convertToEnglish(string morse, string const morseCode[], string const alpha[])
{
string output;
string compile;
string currentCodeLetter;
int totalMorseCode=38;
string str = morse;
istringst... |
65,459,527 | 65,459,589 | Undefined reference ld linker. (C++) | I wrote a code split into several .h, .cpp files
two functions take string type arguments (the code fragment below)
I am getting this error:
/usr/bin/ld: /tmp/cclLgueo.o: in function `main':
main.cpp:(.text+0x1dc): undefined reference to `doloop(std::__cxx11::basic_string<char,
std::char_traits<char>, std::allocator<c... | You need to compile all the translation units:
g++ func.cpp main.cpp
|
65,459,722 | 65,459,779 | Why is the pointer displaying the value and not the address? | I have this code:
int *array_ptr{nullptr};
array_ptr = new int[10]; // allocate array on the heap
for(int i=0; i<10; i++){
array_ptr[i] = i;
std::cout<<array_ptr[i]<<std::endl;
}
delete [] array_ptr; // deletes allocated space
To my understanding, int *array_ptr displays the actual value, whereas int ar... | Pointer's mean is "Which value is in the indicating adress?"
If you want to see addressing of variables you have to use & operator.
Try this in the for loop
std::cout << &array_ptr[i] << std::endl;
|
65,460,194 | 65,460,385 | My game of Snake crashes when you eat an apple, and the apple spawns inside your body after picking a new position (C++, SDL) | I thought I'd attempt to make Snake since it is a pretty easy game to make. I was having an issue where the apple would spawn inside the snakes body, and so I came up with a way to prevent that from happening:
void getRandomApplePos() {
// variable that tells the while loop whether the moving of the apple was succe... | You are initializing your random number generator within your loop.
Note that the RNG is deterministic. It means that you will end up drawing the same numbers all over again as in the previous loop.
Initialize the RNG once at the start of your program. This way, the numbers drawn may be expected to be different within ... |
65,460,406 | 65,463,628 | How to export a function of a regular MFC DLL that is statically linked to MFC to use with a non MFC Win32 Console App in C++ | I am very new in C++ world and this kind of task.
I am having a hard time to resolve this issue.
Any help is kindly appreciated!
I have created a regular MFC DLL that is statically linked to MFC. (This is the first time i ever created a MFC project)
MFC DLL Header File Content
// Serial.h
#pragma once
#ifndef __AFXWI... | The question is resolved by @dxiv's comment:
You cannot import a member function like SerialApp::Init to a non-MFC app,
because that app does not know about the SerialApp class, and cannot
know about it since SerialApp is derived from CWinApp which is an MFC
class, while your app is non-MFC. If you want to export a fr... |
65,460,523 | 65,460,688 | E447: Can't find file "iostream" in path | I'm currently using Vim. To open iostream I go over it with cursor and type in g f. After that in the bottom of the screen I get this message: E447: Can't find file "iostream" in path. (All of my files .cpp files work perfectly fine)
| gf looks up the filename under the cursor in the directories specified in the path option. By default (on unix systems), the path option is set to .,/usr/include,,. This default is not sufficient to find C++ standard library headers directly.
In order to make gf find the C++ standard library headers, you can add the /u... |
65,460,620 | 65,461,788 | How to properly create a header for functions, without multiple definitions error? | I have a header which defines some functions I need. I include them in two files which are themselves included in main.cpp, but I get the multiple definitions of function error, despite the fact that I put
#ifndef MYFUNCTION_H
#define MYFUNCTION_H
//code
#endif
in my code.
So what did I do wrong? Here is my header:
#i... | In C++, the One Definition Rule (ODR) states that objects and non-inline functions cannot have more than one definition in the entire program and template and types cannot have more than one definition by translation unit. As cppreference states under One Definition Rule:
One and only one definition of every non-inlin... |
65,460,664 | 65,460,840 | Getting error while passing a function as a parameter within a class | I am trying to do something with ESPAsyncWebServer library. I have a class in ServerManager.h called MyServerManager. When I compile the code I get this error. What am I doing wrong? How can I fix it?
25:67 is the bold word "this"
src\ServerManager.cpp: In lambda function:
src\ServerManager.cpp:25:67: error: 'this' wa... | Try to add this to the outer lambda capture list:
void MyServerManager::init()
{
if (!LittleFS.begin())
{
Serial.println("Something went wrong while begin LittleFS");
}
// > vvvv <
server->on("/", HTTP_GET, [this](AsyncWebServerRequest *request) {
request->send(... |
65,461,006 | 65,461,064 | How to store an Embind 'val' in a C++ class - error: call to deleted constructor | I managed to use the Embind val transliteration to create a Web Audio API AudioContext and use it inside a function. But I do not understand how I can store it for later use in a C++ class instance field (mContext). When I compile the following code, I get
SC_WebAudio.cpp:62:20: error: call to deleted constructor of 'e... | val has no default constructor. Judging from the implementation, you might be able to initialize it with null or undefined as part of the initializer list:
class SC_WebAudioDriver : public SC_AudioDriver : mContext(val::undefined()) {...}
Alternatively, you can set a default value in the class definition:
class SC_Web... |
65,461,029 | 65,461,287 | Fold expressions in algorithms for std::tuple access | When dealing with generic structures to hold some combination of other entities I often end up using std::tuple with the need to apply operations to individual elements of the std::tuple. For example, when I implemented a "zip iterator" the underlying ranges and iterators were stored in a std::tuple. While it is reason... | I'd start with code that generates a tuple of integral constants.
template<TupleLike Tuple>
constexpr auto tuple_indexes(Tuple&&);
Which is std::tuple<std::integral_constant<std::size_t,0>, std::integral_constant<std::size_t,1>, ..., std::integral_constant<std::size_t,N-1> for an nary tuple.
Now we get:
bool operator=... |
65,461,036 | 65,461,142 | Why am I getting worst performance with a private dynamic array | I want to use OpenMP to parallelize a for-loop calculator which does something like:
B = (int*)malloc(sizeof(int) * N); //N is known
for(i=0;i<500000;i++)
{
for(j=0;j<M;j++) B[j]=i+j; //M is different from N, but M <= N;
some operations on B which produce a variable L;
printf("%d\n",L);
}
I don't ne... | The main issue is that the iterations of the loop are not being assigned to threads as you wanted. Because you have added again the clause parallel to #pragma omp for, and assuming that you have nested parallelism disabled, which by default it is, each of the threads created in the outer parallel region will execute "s... |
65,461,276 | 65,461,408 | 'use of overloaded operator is ambiguous' when using reverse vector iterators in Clang with libc++ | As far as I understand C++ ADL this compilation error is legit.
But at the same time I dont understand why this failure happens only on clang + libc++ configuration, and only when we use reverse iterators. Normal vector iterators dont lead to this.
#include <vector>
#include <iostream>
namespace NS1
{
struct Foo
{
... |
As far as I understand C++ ADL this compilation error is legit. But at the same time I dont understand why this failure happens only on clang + libc++ configuration, and only when we use reverse iterators. Normal vector iterators dont lead to this
Well, if one examines the error message, one sees the actual types of ... |
65,461,570 | 65,461,639 | Are virtual functions safe in real-time audio programming? | Real-time audio programming has particular constraints, due to the need to avoid audio glitches. Specifically, allocating and deallocating memory, or otherwise interacting with the operating system, should not be done in the audio thread.
When calling a virtual function, the program must find the relevant virtual table... | Yes, it's fine. Virtual function dispatch is just like writing (*(obj->vtable[5]))(obj, args...). It doesn't involve any operations of unknown or possibly surprising complexity like allocating memory or I/O.
|
65,461,889 | 65,462,050 | Why can I use assignment operator on begin() even if it is an rvalue? | I can't seem to get around this specific problem for some time now.
For example if I have the following code:
void foo(std::vector<int>::iterator &it) {
// ...
}
int main(){
std::vector<int> v{1,2,3};
foo(v.begin());
}
I would get compile error:
initial value of reference to non-const must be an lvalue.
... | The reason is historical. In the initial days of the language, there was simply no way for user code to express that a type's copy-assignment operator should only work on l-values. This was only true for user-defined types of course; for in-built types assignment to an r-value has always been prohibited.
int{} = 42; //... |
65,462,283 | 65,462,335 | How do I sort a vector of strings in descending order? | I have this following code where there is a vector of strings. Each string is an integer. I want to sort this in a descending order.
The regular sort function did not solve my problem.
Can someone point out how to do this? I want the output as 345366,38239,029323. I want the leading zero in 029323 as well.
#include <io... | You can use a comparator function like this:
vector<string> v = {"345366", "029323", "38239"};
std::sort(v.begin(), v.end(), [](const std::string &s1, const std::string &s2) -> bool {
return std::stoi(s1) > std::stoi(s2);
});
for(auto i : v)
cout << i << endl;
Check this std::stoi() reference.
Edit: From the ... |
65,462,437 | 65,462,678 | Why can the same expression be returned either by copy or by reference? | I know the differences between T& operator[](); and T operator[](), the former one returns a reference, the latter one returns a copy of the result.
But what confuses me is that the same expression container[idx] could be used in the return statement for the two different kinds of return types in the declarations.
How ... | It's fundamentally no different from this case:
int i = <whatever>;
int &j = i; //Reference
int k = i; //Copy
The i expression does not stand alone. It is being used in a specific context, and the nature of that context determines what happens to the expression.
The return statement is performed in the context of the ... |
65,462,582 | 65,462,604 | Could not use gcc 10.2.0 even after installing it in macOS Big Sur | I seem to have a problem with GCC compiler lately.
I installed GCC compiler version 10.2.0 on macOS Big Sur (11.1). My apple machine is still the intel based one. The details of Clang version and all is as follows:
jakehamster@Jakes-Air ~ % gcc --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr... | You compile with GCC on mac like this:
g++-10 -std=c++11 test.cpp
Check version:
g++-10 --version
gives
g++-10 (Homebrew GCC 10.2.0) 10.2.0
|
65,462,644 | 65,487,843 | SDL not compiling with project in Xcode | I am trying to use SDL in Xcode. I included the necessary header files. However, I keep getting error messages at compilation that look like this: Undefined symbol: _AudioObjectAddPropertyListener. I keep getting 100 of these error messages. My code to test SDL looks like this: if (SDL_Init(SDL_INIT_VIDEO)) {cout << "S... | Steps:
Open project configuration
Go to build settings tab
Add library search paths
In other linker flags add -L/usr/local/lib -lSDL2 -lm
Try to compile again
|
65,462,696 | 65,462,716 | How to fix "error: invalid use of non-static data member 'tree::root'" error in c++? | I have this code below:
#include <bits/stdc++.h>
#define DEFAULT_NODE_VALUE 0
using namespace std;
class node{
public:
int val;
node* right = 0;
node* left = 0;
node(int a):val(a){}
};
class tree{
public:
node* root = new node(DEFAULT_NODE_VALUE);
tree(int inp_val){
root->val = inp_v... | Argument defaults are not evaluated in the scope of the method. Instead of using a default argument, use overloading.
void inorder_traverse() {
inorder_traverse(root);
}
void inorder_traverse(node *temp) {
// code
}
|
65,462,900 | 65,462,988 | Why does printf output float 1.45 with one decimal place, and 1.445 with two decimal places in different behaviors? | printf("%.1f, %.2f", 1.45, 1.445);
output
1.4, 1.45
1.45 is sliced but 1.445 is rounded.
I found this,
Why printf round floating point numbers?
Which explained the specification recommands to round the float.
Edit:
I tested it with VS2017 (in a C++ project) and Dev-C.
| [Edited: I didn't originally print them to quite ridiculous enough levels of precision, so the answer gave incorrect reasoning behind the result.]
If you print them out to ridiculous levels of precision, the truth comes out:
#include <stdio.h>
printf("%20.20f, %20.20f", 1.45, 1.445);
Result:
1.44999999999999995559, 1.... |
65,463,235 | 65,463,648 | How to create pcl::PointIndices from std::vector<int> with `pcl`(Point Cloud Library) in c++? | I'm using pcl in c++, apologizing for not being able to create a pcl tag.
I'm realizing a pipe line of point cloud segmentation with pcl. I want to know how to create pcl::PointIndices from a extracted indices of type std::vector<int>, so I can input it into another filter.
First filter can generate indices of type std... | This:
ror_indices->data = sor_inliers; // #### How to do this line?
Should be:
ror_indices->indices = sor_inliers;
|
65,463,240 | 65,463,292 | How do I go about fixing my calculator answers in my c++ program with a basic menu? | I have a basic menu program that gives the user different programs to choose from and run, when I run the simpleCalculator option and iput values and the operation of arithmetic the output is always the wrong answer but when I first programmed the calculator program without the menu and it being in its own function it ... | You seem to be confused about returning values from a function, and printing values in a function. These are not the same thing.
If you print the values in the function then the function should be void (i.e. nothing is returned) and the printing happens inside the function (obviously)
void simpleCalculator()
{
...
... |
65,463,442 | 65,463,540 | "Heap use after free" error in LeetCode Online Judge but not Visual Studio | I am coding a solution to the LeetCode problem "Odd Even Linked List" which can be read here.
My code is failing the test case with the error
================================================================
==31==ERROR: AddressSanitizer: heap-use-after-free on address 0x6020000000d8 at pc 0x0000003d7f1d bp 0x7fff37cf96... | Most things that you can do wrong in a C++ program fall into the category of undefined behaviour. Using memory after is has been freed, dereferencing a null pointer, reading an uninitialised variable, reading or writing beyond the bounds of an array, all of these invoke undefined behaviour.
Undefined behaviour means th... |
65,463,799 | 65,463,979 | Optimization. How to speed up the given C ++ code? |
This is my code. 1<=i<=j<=n j-i<=a 1<=n<=1000000 0<=a<=1000000
#include <iostream>
using namespace std;
int main(){
int n, a, r = 0;
cin>>n>>a;
for(int i = 1; i <= n; i++){
int j = i;
for(j; j <= n; j++){
if(j-i<=a){
r++;
}
}
}
cout<<... | After accounting for both positive numbers, negative numbers, and zeros, your double-nested for-loop can be simplified into this:
if (n < 1)
{
r = 0;
}
else if (a == 0)
{
r = n;
}
else if (a < 0)
{
r = 0;
}
else if (n <= a)
{
r = (n * (n + 1)) / 2;
}
else
{
r = (n-a)*(a + 1) + (a * (a + 1)) / 2;
}
... |
65,463,810 | 65,465,088 | Are C++ pointers allocated same address every time they are newly allocated? | I am new to C++ and I am trying to implement Huffman Codes in it. To do so I had to implement a tree-like structure in it which required me to implement pointers in a structure. But the problem that I am facing is that every time I allocate a new value to a variable it is getting the same address and the tree that I am... | Problem is in node.erase() it is deleting the nodes which you are pointing through temp.left and temp.right. A slightly better way is to form vector of node* then form nodes through new operator and store the pointer in the vector. This way when you do node.erase() it will only erase the pointer and not the node itself... |
65,464,005 | 65,464,030 | Why is this C++ program not showing any output? | I am trying to write code for a binary search, but it is not showing any output. Please tell me my errors.
#include <iostream>
using namespace std;
int main(){
int a[]= {1, 3, 5 , 7, 32};
int n;
cin>>n;
int last=(sizeof(a)/sizeof(a[0]))-1;
int first=0;
while(first<=last){
int mid=(last... | The way you calculate mid is wrong, it should be this:
int mid = (first + last) / 2;
Preferable way is this to avoid overflow (first + last can overflow) :
int mid = first + (last - first) / 2;
or with >> operator:
int mid = (first + last) >> 1;
|
65,464,202 | 65,464,313 | constexpr using standard library algorithms | When built using C++17/C++20 x64 gcc/clang, the below snippet yields a compile error whereas de-referencing the iterator directly via *std::max_element(std::begin(arr), std::end(arr)) works fine. Any ideas as to why? I've also observed similar behavior with other standard algorithms that have become constexpr since C++... | it has to store a pointer to the element of arr.
Since arr is not static, it's located on the stack, so its address can't be determined at compile-time.
It will work if you make arr static.
|
65,464,298 | 65,464,318 | how to end a loop at a particular time in unordered_multiset | Good morning,
I am trying for a loop when a particular condition is met in an unordered_multiset with the end operation. But it does not work and I get a Segmentation fault in the next iteration of the loop.
Code:
std::unordered_multiset<Element, ElementHash>::iterator itr;
Element elementTemp1("");
for (itr = almacen.... | What about this:
unordered_multiset<Element, ElementHash> :: iterator itr;
Element elementTemp1("");
for (itr = almacen.begin(); itr != almacen.end(); ++itr) {
Element tmp(*itr);
if(tmp.getNombre == "prueba"){
break;
}
}
The break stops the execution of the for loop at that point. Is that what you want?... |
65,464,381 | 65,464,424 | how to create an 'n' sized array in c++? | I'm trying to create an array of n size, but everytime I try to do that I get an error saying:
expression must have a constant value -- the value of variable "n" (declared at line 33) cannot be
used as a constant
I worked like this before but that was on codeblocks. This time I've downloaded mingw manually and have b... | int arr[n]; is invalid C++ with runtime n, it uses VLA extension.
use std::vector instead:
int n;
std::cin >> n;
std::vector<int> arr(n);
|
65,464,407 | 65,464,523 | OpenGL independent rotation | I'm trying to draw these shaped bellow this this:
What I want
Tried this code:
glLoadIdentity();
glColor3f(0.98f, 0.83f, 0.73f);
glBegin(GL_POLYGON);
for (float i = 0; i <= (2 * p); i += 0.001) {
x = 100 * cos(i)-10;
y = 115 * sin(i)+270;
glVertex2f(x, y);
}
glEnd();
... | You have to rotate the object around its center and move the rotated object to its position in the world. glRotatef rotates the vertices around (0, 0). Draw the object around (0, 0) and glTranslate to move the object to its position in the world:
glTranslate(-10.0f, 270.0f, 0.0f);
glRotatef(-135.0f, 0.0f, 0.0f, 1.0... |
65,464,625 | 65,465,261 | How to use errno the same way in C++11 as it was in C++03 | Trying to understand :
C.2.9 Clause 19: diagnostics library [diff.cpp03.diagnostics]
19.4
Change: Thread-local error numbers
Rationale: Support for new thread facilities.
Effect on original feature: Valid but implementation-specific C++ 2003 code that relies on errno being the same across threads may change behavior i... | C++11 us the first official standard that has a notion of multi-threading. This implies that if you use multiple threads in C++03 or C++98 you are using undefined behavior.
The whole idea about this change is about the following code:
functionThatSetsErrNo();
if (errno == something)
...
If you run this code and th... |
65,464,680 | 65,464,724 | How to fix "terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_M_construct null not valid" exception? | I have code below that consist of binary tree data structure:
#include <bits/stdc++.h>
#define DEFAULT_NODE_VALUE 0
using namespace std;
template <class T>
class node{
public:
T val;
node* right = 0;
node* left = 0;
node(T a):val(a){}
};
template <class T>
class tree{
public:
node<T>* root = new ... | You're trying to initialize an std::string with 0. std::string doesn't have a ctor that takes just an int, but it does have one that takes a pointer, and an integer literal 0 can convert implicitly to a pointer--specifically, a null pointer.
But, when you pass a pointer to initialize an std::string, it's required to be... |
65,464,867 | 65,471,459 | For loop in C++ stops after a single iteration w/ pointer variable | So first all I'll preface this with: I just started using c++.
I have a structure that I store the pointer to in an unordered_map, setting members' values in the struct pointer as I get them through my process. Then I no longer need them in a map so I transfer then to a vector and loop through them.
Though on the secon... | After many hours of trial and error I have determined the issue (aside from doing things in a way I should, which I've since corrected) it was something I messed up on that caused this issue.
TLDR:
Items wouldn't exist that I assumed did and tried to read files with a blank path and parse the contents that didn't exist... |
65,464,973 | 65,465,074 | what is wrong with this code ? it's not showing any output after executing | The function must return an array of integers representing the frequency of occurrence of each query string in strings.
matchingStrings has the following parameters:
string strings[n] - an array of strings to search
string queries[q] - an array of query strings
Example
strings[]={"ab","ab","abc"}
queries[]={"ab","abc",... | That code works. I don't know why you didn't use size() method in vector.
#include <bits/stdc++.h>
using namespace std;
vector<int> matchingStrings(vector<string> strings, vector<string> queries) {
unordered_multiset<string> m;
int ms=0;
vector<int> res;
int y;
for(int i=0;i<strings.size();i++)
... |
65,465,002 | 65,465,040 | Is any difference between bitwise copy and shallow copy? | With respect to the question What is the difference between memberwise copy, bitwise copy, shallow copy and deep copy? author of first answer says:
Shallow Copy
Refers to copying just the immediate members of an object, without
duplicating whatever structures are pointed by them. It is what you
get when you do a bit-w... | A bit-wise copy is a shallow copy but not necessarily vice versa.
The reason is that due to padding there can be bits in objects that you usually ignore, yet they are part of an object.
For example this
struct bar {
int x;
foo b;
};
Can lool like this in memory:
| x | some padding | b | more padding |
When yo... |
65,466,164 | 65,466,255 | Exception Thrown Your project has triggered a breakpoint | I am working on a project in C++ file handling and already spend a lot of time to fix this bug but failed and looking for help.
Here is my .txt file
SNO, Name, NoOfPeopleLiked
1, The Shawshank Redemption, 77
2, The Godfather, 20
3, Into The Wild, 35
4, The Dark Knight, 55
5, 12 Angry Men, 44
6, Schindler... | Comparators must return true if the first item is to be sorted earlier than the second item and false otherwise. This implies that the comparator must return false for equal items. Your comparator does not do this
return get<2>(l) >= get<2>(r);
Change to this
return get<2>(l) > get<2>(r);
You actually had quite a hel... |
65,466,513 | 65,466,583 | Why does ansi escape doesn t work on codeblocks, and how to fix it? | For example this piece of code :
#include <iostream>
using namespace std;
int main()
{
cout << "\033[31m" << ".";
return 0;
}
prints a red dot in a visual studio console, but in a codeblocks console it prints this :
[31m*
If anyone knows how to fix this problem for the codeblocks console.
Thanks
| Every console can use control code sequences as it likes. There are numbers of different standards. If you like to control your output with a given set of control sequences, you have to satisfy that the used console is able to handle them. Some terminal emulators can be configured to use a special emulation, some other... |
65,466,547 | 65,466,562 | Can someone please tell me what is wrong with my code? | I want to manipulate a pointer to an array of structs by adding values to the array and printing them.
This is the code:
#include <iostream>
using namespace std;
struct words {
char letter;
bool marked;
};
int main(){
int ncols, nrows;
words* data;
data = new words [ncols * nrows];
cout << "In... | Simple error. You used the nrows andncols variables before they had any value. Obviously you should only use a variable after it has been given a value.
Change your code like this
cout << "Insert ncols : ";
cin >> ncols;
cout << "Insert nrows : ";
cin >> nrows;
data = new words [ncols * nrows];
|
65,466,946 | 65,467,709 | Specify thread model on ubuntu mingw (if possible) | Im running a program on linux with g++ and everything works fine. If i compile using x86_64-w64-mingw32-g++ it crashes with error: ‘std::thread’ has not been declared.
The part where my code crashed is fairly simple:
#include <thread>
int main()
{
int cores = std::thread::hardware_concurrency();
}
I figured out t... | It seems that the package g++-mingw-w64-x86-64 provides two executables:
x86_64-w64-mingw32-g++-posix: which uses posix
x86_64-w64-mingw32-g++-win32: which uses win32
Using the first executable should solve your issue.
|
65,467,084 | 65,467,198 | C++ error: invalid suffix '.d' on floating constant | Hello I have the following declared arrays in C++:
int arr[5] = {1,2,3,4,0};
float arr2[10] = {1.2f,0.0f,2.0f,1.4f,0.0f,4.2f,5.3f,0.0f,0.0f,0.0f};
double arr3[6] = {0.0d,0.0d,5.3d,0.0d,0.0d,0.5d};
When I compile this code the compiler returns the following error:
error: invalid suffix '.d' on floating constant
I tri... | Floating point literal suffixes are:
(no suffix) defines double
f F defines float
l L defines long double
Supposed you put the d to make the literal a double, you can remove it. I suppose gcc offers it as extension for the sake of consistency (allows to use a suffix also for doubles), but also gcc will accept no suff... |
65,467,188 | 65,467,321 | How to create a new struct for an unknown amount of inputs | I have a program that reads from a text file the name of a movie and fields related to that movie. I want to include those movies as a struct but I don't know how to initialize automatically.
This is my code to read from the txt file.
string line;
while (getline(z, line))
{
istringstream iss(line);
... | Something like this
struct movie {
int rank;
string title;
string actor;
float rating;
};
vector<movie> all_movies; // this vector will hold all the movies
string line;
while (getline(z, line))
{
...
movie m; // this is one movie that we've read from line
m.rank = ...; ... |
65,467,373 | 65,467,460 | Why I am able to modify using constant range based loop? | #include <iostream>
#include <map>
using namespace std;
int main()
{
int number = 10;
map<int*, int> intmap;
intmap.insert(pair<int*, int>(&number, 1));
for (auto const & x : intmap)
{
(*x.first)++;
}
for (auto const & x : intmap)
{
cout << (*x.first) <... | You are not modifying map or map elements. You are modifying pointee, and there's nothing to prevent you from doing that (apart from changing map type).
The type of x is const std::pair<int* const, int>&, or a reference to const pair. Notice that the first element of the pair is a constant pointer, but it is not pointi... |
65,467,399 | 65,467,430 | How to deallocate memory | I have a void function which I call in the main and I want it to use a new value for pi each time is called, and not adding them. I thing I should deallocate the memory for the array of type Dir, but I can't figure it out. The implementation is as follows:
void throwSeries(int n)
{
double pi;
double faults;
do... | You have to initialize numCicle before adding something to that.
In other words,
double numCicle;
should be
double numCicle = 0;
|
65,467,837 | 65,467,868 | I am trying to get max output in a 2d vector | I am trying to get max output in a 2d array like
Input: accounts = [[1,2,3],[3,2,1]]
Output: 6
Explanation:
1st customer has wealth = 1 + 2 + 3 = 6
2nd customer has wealth = 3 + 2 + 1 = 6
Both customers are considered the richest with a wealth of 6 each, so return 6.
current input = [[1,2,3],[3,2,1]];
current output = ... | You need to re-initialise an array's sum counter before inner loop:
for(int i=0;i<accounts.size();i++)
{
temp = 0; // re-initialise before taking every array/account's sum here
for(int j=0;j<accounts[i].size();j++)
{
temp = temp + accounts[i][j];
}
if(temp > max)
{
max = temp;
... |
65,468,069 | 65,468,173 | Preventing implicit conversion operator only for binary operators | I'm having an issue that I've boiled down to the following, where an == operator usage compiles even though it's supposed to fail (C++17, tested on GCC 5.x, 8.x, and 9.x):
template <int N> struct thing {
operator const char * () const { return nullptr; }
bool operator == (const thing<N> &) const { return false; }
}... | You can just provide a deleted version of the operator for the case where it shouldn't work, e.g.:
template <int N> struct thing {
operator const void * () const { return nullptr; }
bool operator == (const thing<N> &) const { return false; }
template <int X>
bool operator == (const thing<X> &) const = delete;
}... |
65,468,120 | 65,468,270 | LLVM ERROR: out of memory ?? How to fix this error (if its fixable) | Okay I am Solving https://leetcode.com/problems/longest-increasing-subsequence/
My code is Correct and runs fine without memonization(TLE), but after memonized it gives error :
LLVM ERROR: out of memory
PLEASE submit a bug report to https://bugs.llvm.org/ and include the crash backtrace, preprocessed source, and associ... | Your int dp[2555][25000005]; array is probably way too large for your stack as it is approximately 2555*25000005*4=255 GB (if an int is 4 bytes). If you have enough memory (physical and pageable) you can simply allocate all that memory on the heap by using malloc()/free() or an STL container like std::vector. Otherwise... |
65,468,135 | 65,478,109 | Crash when trying to call node js callback using C++ addon | I am trying to call some native api from node js and perform long running task. I am using libuv for that perposes, store js callback to perform some meaningful task in separate thread and call callback later. This is what I've done so far:
task.cpp
struct Work {
uv_work_t request;
Local<Function> callback;
};
sta... | Looks like the issue is that you're using a v8::Local<...> in a long-lived object. That doesn't work because the lifetime of a Local is tied to the surrounding HandleScope: the Local becomes invalid when the HandleScope dies. See https://v8.dev/docs/embed#handles-and-garbage-collection for details. The solution is to u... |
65,468,629 | 65,468,659 | STL Sort - Debug Assertion Failed | Program in C++. I sorted a vector using STL sort and the boolean comparator (here, cmp1 and cmp2 functions). However, upon running the program and reading the values of the vector, it returns:
Debug Assertion Failed!, Line:1618, Expression: invalid comparator. Here, the function that returns the error from the algorith... | Comparators must return false for equal elements. Change
bool cmp1(int st, int dr) {
return (st >= dr);
}
bool cmp2(int st, int dr) {
return (st <= dr);
}
to
bool cmp1(int st, int dr) {
return (st > dr);
}
bool cmp2(int st, int dr) {
return (st < dr);
}
A comparator should only return true when the ... |
65,468,972 | 65,469,110 | OpenGL loading rgb texture from stb image | I have a class for creating textures from a path but when i try to load in a texture with 3 channels
(rgb) it gives me read access violation exception when running this line
glTextureSubImage2D(m_RendererID, 0, 0, 0, m_Width, m_Height, m_DataFormat, GL_UNSIGNED_BYTE, data);
I tried to change the parameters in the stbi... | When an RGB image is loaded to a texture object, GL_UNPACK_ALIGNMENT needs to be set to 1.
By default GL_UNPACK_ALIGNMENT is 4, so each line of an image is assumed to be aligned to 4 bytes. The pixels in the buffer have a size of 3 bytes and are tightly packed, this would cause a misalignment:
glPixelStorei(GL_UNPACK_A... |
65,469,015 | 65,470,479 | Can't link against static library with Mingw on Linux | I have installed the GMP library and try to cross-compile with mingw-w64-posix.
My Library is in /usr/local/lib.
My compile command looks like the following:
x86_64-w64-mingw32-g++-posix src/factorial.cpp -o bin/factorial.win.o -I/usr/local/include -L/usr/local/lib -lgmp -lgmpxx
It throws an undefined reference error:... | OK -
The link errors (__gmpz_init, __gmpz_clear, etc.) are GMP "internals". They're supposed to come from libgmp, the C-language base library.
The code that's referencing them (.text$ZN23__gmp_binary_multiplies4evalEP12__mpz_structPKS0_S3[ZN23__gmp_binary_multiplies4evalEP12__mpz_structPKS0_S3], etc.) is "name mangl... |
65,469,243 | 65,469,360 | why is my unordered_map getting bigger and bigger | I used unordered_map, the key is string, the value is a class IpsegInfo.
I read a file and used the file data to update the value in map, the map size always same but the map space in memory is getting bigger and bigger.
My code update the map from file every 30 minutes, the file has 10million lines and the length neve... | IpsegInfo *info = new IpsegInfo(ss[1],ss[2],ss[3],ss[4]);
map[ss[0]] = *info;
Here you create a IpsegInfo using new. That means that you should also delete it using delete.
Instead you simply override it, creating a memory leak. Use RAII to make your data automatically managed:
IpsegInfo info =... |
65,469,480 | 65,470,820 | Read file with unknown character type | I need to read text from a file that could contain any type of character (char, char8_t, wchar_t, etc). How can i determine which type of character is used and create an instance of basic_ifstream<char_type> depending on that type?
| So I guess you want to auto-detect the encoding of an unknown text file.
This is impossible to do in a 100% reliable way. However, my experience shows that you can achieve very high reliability (> 99.99%) in most practical situations. The bigger the file, the most reliable it is to guess its encoding: some tenths of by... |
65,469,533 | 67,428,743 | Where is query pipelining in libpq? | I'm developing a high load server application using C++ and libpq (libpqxx is very unstable). I use async queries in threads to improve performance. But I've discovered that, for example, PQsendQuery("SELECT 1;SELECT 1;") works faster then executing PQsendQuery("SELECT 1") two times.
Is there any way to call bunch prep... | libpq supports support query pipelining in PostgreSQL 14. You can use it on old PostgreSQL versions so long as you're using a new libpq. See commit acb7e4eb6b.
I wrote a patch for it in 2016 as a bit of a fire-and-forget weekend hack Thanks to the efforts of many others, it has been turned into a mature feature and mer... |
65,469,782 | 65,470,056 | Why the [] operator in sorted_vector_map? | I do not understand what the operator [] does in sorted_vector_map.
Specifically when the key does not exist, what value is added to the data structure?
What is value_type(key, mapped_type())?
Is it a constructor call to std::pair by default?
What is mapped_type()?
Is it also a constructor call?
mapped_type& operator... | Container is the template argument that defines what container is used by sorted_vector_map to store the key-value pairs and defaults to a std::vector(std::vector<std::pair<Key, Value>, Allocator>>)
value_type is Container::value_type (typedef typename Container::value_type value_type;) which (for the default template ... |
65,470,828 | 65,470,852 | Determining the size of a array which was passed a value | #include <iostream>
using namespace std;
int main(){
char word[100];
char count;
int j=0;
cout<<"Enter a word or a phrase"<<endl;
cin>>word;
cout<<endl<<word<<endl;
j=sizeof(word);
cout<<j;
}
What I want to do in the above program is to find out the length of the string(word) that was i... | The size of the array is, indeed, 100.
But you're looking for the number of characters set inside that array until the first null byte, i.e. the length of the "C-string" inside the array.
strlen does that.
You'd be much better off with a nice std::string though, if for no other reason than you currently perform no boun... |
65,470,965 | 65,675,322 | As long as I can provide a hasher function for my types why I need to specialize std::hash for my types? | As long as I can provide my hasher for my class types why should I specialize std::hash<my_class_type>?
I've implemented this example:
class Foo;
template<>
class std::hash<Foo>;
class Foo
{
public:
Foo(std::string const& s, int x) : str_(s), x_(x){}
std::string str()const {return str_;}
int get_x() const{... |
As long as I can provide my hasher for my class types why should I [do I need to] specialize std::hash<my_class_type>?
You don't need to. Here are some reasons for doing so anyway:
If your class is a part of an API (internal or external doesn't matter) and you are expected to provide users of the class the possibili... |
65,470,979 | 65,471,031 | Github Actions path does not update | Right now, I'm trying to build a tool from source and use it to build a C++ project. I'm able to extract the tar file (gcc-arm-none-eabi). But, when I try to add it to path (using $GITHUB_PATH, not add-path), the path doesn't apply on my next action and I can't build the file. The error states that it can't find the gc... |
I can't even debug by seeing what's in the path because running echo $(PATH) just says that PATH cannot be found. What should I do?
First, PATH is not a command so if you want to print its value, it would be something like echo "${PATH}" or echo "$PATH"
Then, if you want to add a value to an existing environment vari... |
65,471,002 | 65,471,080 | Implicit type in lambda capture | I'm starting out with C++ programming, and am curious why this is legal:
auto myFun = [n=0]() mutable {return n++;};
I would have thought this wouldn't work, as C++ is a strong typed language, but it seems that the compiler infers the integer type?
| Lambdas, were introduced with C++11. There were no default initializer values in C++11:
auto myFun = [n]() { /* body */ };
That's all you had in C++11. Whatever the type of n was, that's what you captured, type and value.
Default initialization values were introduced with C++14. I suppose that it would've been possibl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.