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 |
|---|---|---|---|---|
69,708,068 | 69,749,258 | C/C++: Streaming MP3 | In a C++ program, I get multiple chunks of PCM data and I am currently using libmp3lame to encode this data into MP3 files. The PCM chunks are produced one after another. However, instead of waiting until the PCM data stream finished, I'd like to encode data early as possible into multiple MP3 chunks, so the client can... | I examined the source code of lame and the file lame_main.c helped me to come to a solution. This file implements the lame command-line utility, which also can encode multiple wav files, so they can be appended to a single mp3 file without gaps.
My mistake was to initialize lame every single time I call my encode funct... |
69,708,154 | 69,802,699 | Setting Up Neovim for C++ with CMAKE | I'm using coc for code-completion and ale for linting my c++ files, this works fine when I have all my headers and source files in the same directory, however when I have a CMake project with the typical include & src directories (for headers and .cpp files respectively) this setup fails to realize that my headers are ... | Please check CMake's documentation regarding CMAKE_EXPORT_COMPILE_COMMANDS.
Here is part of my .nvimrc for example:
nnoremap <F5> :wa <bar> :set makeprg=cd\ build\ &&\ cmake\ -DCMAKE_BUILD_TYPE=debug\ -DCMAKE_EXPORT_COMPILE_COMMANDS=1\ ../view\ &&\ cmake\ --build\ . <bar> :compiler gcc <bar> :make <CR>
This generates... |
69,708,428 | 69,708,477 | initialize array of pointer and matrix | I want to initialize array of pointer.(not a normal array) But this doesn't work.
int* arr = new int [5];
arr = {1,2,3,4,5};
Also I don't want to do it like this:(Because if the size changes I have to change the code)
arr[0] = 1; arr[1] = 2; ...
Is there an easy way to do this? what about a matrix?
int** mat = ...
ma... | You can write for example
int* arr = new int [5] { 1, 2, 3, 4, 5 };
Or for example you could use the algorithm std::iota like
int* arr = new int [5];
std::iota( arr, arr + 5, 1 );
or some other algorithm as for example std::fill or std::generate.
If the array will be reallocated then it is much better in this case to... |
69,708,571 | 69,708,780 | How to pass vector to func() and return vector[array] to main func() | int multif(std::vector<int> &catcher)
{
printf("\nThe array numbers are: ");
for (int i = 0; i < catcher.size(); i++)
{
catcher[i]*=2;
//printf("%d\t", catcher[i]);
return catcher[i];
}
}
Can someone help me to understand how to pass above catcher[i] to main func() in the for... | Your multif() function:
int multif(std::vector<int> &catcher)
{
printf("\nThe array numbers are: ");
for (int i = 0; i < catcher.size(); i++)
{
catcher[i]*=2;
//printf("%d\t", catcher[i]);
return catcher[i];
}
}
This will double the first element of catcher and return it. I d... |
69,708,700 | 69,708,879 | Pointer to portions of array. Operations with filtered array | Following the question in Pointer to portions of array, a structure that does operations with portions of an array was proposed.
However, I am having a problem when calling functions that change entries in the matrices.
When defining operations for matrices it is standard to pass by reference. However, when I use the s... | The clue is in the error message: Your test function takes an lvalue reference but the temporary subMat object constructed as the argument in the test(subMat(myBlockMatrix[0])) call is an rvalue.
The simplest fix for this is to redeclare the test function template to have a forwarding reference argument:
template <type... |
69,708,765 | 69,708,978 | How can I sort a pair of vector in some given range? | I know how to sort pair of vectors using std:sort(v.begin(), v.end()); But this will sort all the pairs of the vector.
But I want to sort the vector in a specified range.
#include<bits/stdc++.h>
#define ll long long
using namespace std;
bool sortbysecdesc(const pair<int,int> &a,const pair<int,int> &b)
{
return... | What you need is something like the following
#include <tuple>
#include <vector>
#include <iterator>
#include <algorithm>
//...
std::sort( std::begin( v ), std::end( v ),
[]( const auto &p1, const auto &p2 )
{
return std::tie( p2.second, p1.first ) < std::tie( p1.second, p2.first ... |
69,709,284 | 69,709,574 | C++ Check if the package has been installed via Swift Package Manager and include a file | I have a set of C++ packages resolved with the Swift Package Manager and another Package Manager (let's call it PMX).
PMX cannot resolve one of the dependencies, but I have to run CI on it. Is it possible to somehow check that the package is being compiled with the SPM system and include the appropriate imports and if ... | Found a solution, this flag exists and it's called SWIFT_PACKAGE
This solution has worked perfectly for me:
#if defined(_WIN32) || defined(_WIN64) || (defined(__APPLE__) && defined(SWIFT_PACKAGE))
#include <MyFile.h>
#endif
Blog post mentioning the issue
|
69,709,450 | 69,709,571 | Facing debugging problem when implementing doubly linked list in C++ | I am implementing a doubly linked list where each node has two pointers. One points to the next node in the list, while the other points to the previous node.
The node struct consists of an integer and a node-pointer to the next node in the list. And another pointer to the previous pointer in the list.
The class contai... | In other to call new Node(val) where val is an int, your Node needs a constructor that takes an int as an argument.
Perhaps:
struct Node
{
int value;
Node *next;
Node *tail;
Node(int v) : value(v), next(nullptr), tail(nullptr) { }
};
|
69,709,668 | 69,709,889 | accessing struct by a pointer | Im currently experimenting with pointers and i have several questioins to my code
ps. this is just for experimenting Im not going to use this in any code
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
struct obj
{
int* IntPtr;
obj()
{
IntPtr = new int[2];
IntPtr[0] = 123;
... | Even if the syntax errors in your code were fixed, the premise of what I suspect you are trying to do would still be fundamentally flawed. Taking a pointer, converting it to a number representing a memory address, shifting it around to land on another object and accessing it this way is simply not something you are all... |
69,709,958 | 69,710,155 | Where to insert an #include when multiple files need it C++ | Let's say I have 4 source files main, aux1, aux2 and aux3, all of whom work with strings and therefore need to #include <string>.
The main one will include the 3 aux, since it will use it's functions, but none of the aux needs to include main nor any other aux.
Where should I include string and how could something like... | Headers should include what they use. Deviating from this leads to pain on the long run. Hence:
// aux1.h
#include <string>
// aux2.h
#include <string>
// aux3.h
#include <string>
// main.cpp
#include "aux1.h"
#include "aux2.h"
#include "aux3.h"
You could in principle include <string> in main before you include the... |
69,709,983 | 69,711,108 | Am I implementing Euler's Method correctly in C++? | I was asked to write a C or C++ program to solve the given differential equation
This must be achieved numerically using Euler method. The user should be able to enter the velocity(v), the initial value of x(0) and the final Time (T) at the beginning of the program.It should also plot the numerical solution for times 0... | You have a fundamental error with the Euler method concept.
my_aprox[i + 1] = my_aprox[i] + dt*v
Remember, to calculate a new approximation you have to have "a priori" the initial value which, with the next approximation will be the next initial value an so.
|
69,710,244 | 69,713,691 | Accessing only one executable at a time to a function in .so library | I'm developing a system of executables which run together (and communicate via ROS). I have a .json configuration file which is common for all the executables and a libCommon.so which is a library of functions to read certain values from the .json. The library is linked statically to all the executables in CMakeLists.t... | Executables live in their own memory space. They do not share memory with other executables, even if they are both using the same shared library1.
There are no interprocess mutexes in standard C++. You have to find an interprocess mutex from outside the standard.
boost has them, and most OS file system APIs can be us... |
69,710,300 | 69,713,941 | Print library value from function on display | I'm trying to print the return value(WiFi.localIP) on my display from the library ESP8266WiFi. But I'm getting an error. For the display I'm using the SSD1306 library.
The purpose of this is to print the IP adress of the ESP8266 on the display.
ERROR:
Arduino: 1.8.16 (Windows 10), Board: "LOLIN(WEMOS) D1 R2 & mini, 80 ... | Used toString() method from the ESP8266WiFi library (line 162-173).
String ipstat = WiFi.localIP().toString();
|
69,710,587 | 69,710,983 | C++ vector of strings into associative vector of ints | Im having trouble to convert a string vector with size of ~ 1.0000.0000 elements to an associative vector with integers.
Input:
std::vector<std::string> s {"a","b","a","a","c","d","a"};
Desired output:
std::vector<int> i {0,1,0,0,2,3,0};
I was thinking of an std::unordered_multiset as mentioned in Associative Array w... | This code will output your desired output for your given input. And it will process 1.000.000 strings of length 3 in 0.4s. So I think unordered_map is a viable choice.
#include <string>
#include <iostream>
#include <unordered_map>
#include <chrono>
#include <random>
// generator function for creating a large number of... |
69,711,295 | 72,350,398 | C++ execute python file using ShellExecuteA | So im trying to execute a python file (no console) using C++ shellapi.h ShellExecuteA but it wont work and return a value 42 if i do
int value = ShellExecuteA(nullptr,"open",path.c_str(),nullptr,nullptr, SW_HIDE );
and return (error 2) if i use GetLastError(); from errhandlingapi.h
here is the entire function in C++
v... | To fix it make the file you want to execute .py , instead of .pyw
|
69,711,555 | 69,711,808 | How to get integers until \n for n number of lines | My input :
the first input is number of lines the input will contain
5
7 3 29 0
3 4 3
2 3 4 55 5
2 3
1 2 33 4 5
My issue is how can I store them in vector of vector..?
My concept..
.
.
.
cin>>n;
vector<vector<int>>vec;
while(n--)
{
vector<int>vec2;
for(**Getting input until the line**){
vec2.emplace_back(... | Here's my suggestion, YMMV.
Read each line into a string.
Use istringstream to extract the integers from the string, into a vector.
After string is processed, push_back the vector into the outer vector.
unsigned int rows;
std::cin >> rows;
std::string text_row;
for (unsigned int i = 0U; i < rows... |
69,711,608 | 69,717,395 | Why XRecordDisableContext() is not working? | void Callback (XPointer, XRecordInterceptData *pRecord) { std::cout << "my logs\n"; }
int main ()
{
if(auto* const pDisplay = XOpenDisplay(nullptr))
{
XRecordClientSpec clients = XRecordAllClients;
auto* pRange = ::XRecordAllocRange();
pRange->device_events = XRecordRange8{KeyPress, ButtonRelease};
... | One way is to move below statement into the Callback() or some equivalent other thread. For testing purpose, I changed the code as below where after few event raised, I disable from the Callback() and it works.
::Display* pDisplay;
XRecordRange* pRange;
XRecordContext context;
#define CHECK(EVENT) if(*pDatum == EVENT)... |
69,711,686 | 69,712,159 | Rebuild CMake target when dependency changes | There are countless similar questions on here but I can't find one that addresses exactly this issue:
I'm using to CMake to build shared libraries a and b and executable prog. prog should be linked against a but not against b. However, at the same time I want prog to be rebuilt whenever b is outdated. In practical term... | I see that generator expression do not work in OBJECT_DEPENDS context. Touché. Anyway, just do a small proxy:
cmake_minimum_required(VERSION 3.11)
project(test)
add_library(a a.cpp)
add_library(b b.cpp)
add_executable(prog prog.cpp)
add_custom_command(
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/b_is_build
COMMAND ${CMAKE_C... |
69,712,496 | 69,712,519 | Use of incomplete types in templates | Is it legal to use an incomplete type in a template if the type is complete when the template is instantiated?
As below
#include <iostream>
struct bar;
template <typename T>
struct foo {
foo(bar* b) : b(b) {
}
void frobnicate() {
b->frobnicate();
}
T val_;
bar* b;
};
stru... | Clang is correct in reporting an error (as opposed to a warning or being silent about it), though MSVC's and GCC's behavior are also consistent with the standard. See @HolyBlackCat's answer for details on that.
The code you posted is ill-formed NDR. However, what you want to do is feasible.
You can defer the definition... |
69,712,790 | 69,712,832 | how to emplace_back (append) in vector without declaring variables..? | If number of input are given as first input.
If I need to store them in vector
I can easily do it by creating a variable and using the variable I can append it in the vector
I'm fascinated to know , is there any other way so that I need not have to use a variable..
INPUT
4
1 5 3 2
How vector take inputs
vector<int>ve... | Yes, just do this:
std::cin >> vec.emplace_back();
The return type of vector::emplace_back() in C++17 is no longer void. Instead, it returns a reference to the inserted element. So vec.emplace_back() will construct an element by default and return its reference.
|
69,712,879 | 69,712,977 | Drag and Drop QTreeWidgetItem to QGraphicsView with custom data | I've a class containing a QTreeWidget, where I have some QTreeWidgetItem.
I want to drag and drop a QTreeWidgetItem into a QGraphicsScene, in order to create an object in there. The object is a rectangle with the text of the QTreeWidgetItem in there.
I was able to perform the drag and drop operation, and I've my dropEv... | DND of models uses an internal Qt format so a possible solution is to use a dummymodel:
void Scene::dropEvent(QGraphicsSceneDragDropEvent* event) {
event->acceptProposedAction();
if(event->mimeData()->hasFormat("application/x-qabstractitemmodeldatalist")){
QStandarditemmodel dummy_model;
if(dumm... |
69,712,962 | 69,713,171 | Constexpr CRTP destructor | I created the constexpr version of the Curiously Recurring Template Pattern and all seem to work as expected, except the destructor who "under normal circumstances" should be marked as virtual. As I can understand, virtual is the vital enemy of constexpr.
In my example I implemented two interfaces with no data-members.... |
except the destructor who "under normal circumstances" should be marked as virtual
Something is iffy here. It sounds like you are operating on the assumption that "All classes should have a virtual destructor", which is incorrect.
virtual destructors are only required if there is a possibility that a derived class mi... |
69,713,155 | 69,713,287 | When iterating over a 2D structure, is it faster to iterate over the total length or use nested loops to iterate over the rows and columns? | I can think of two different ways to iterate over a 2d range, either using nested loops to iterate over the rows and columns separately:
for (int i = 0; i < width * height; i++) {
int x = i % width;
int y = i / width;
//Do stuff
}
or using a single for loop to iterate over the area and computing the row an... | width * height might overflow. Signed integer overflow is (still) undefined behavior. i % 0 is undefined behavior. i / 0 is undefined behavior too. You can protect the first version against such problems, though in the second version none of this issues is present.
Don't do premature optimization. This:
for (int y = 0;... |
69,713,776 | 69,715,088 | How to tell when all instances of Thread A have finished from Thread B | I am currently making a program in C++ that simulates Waiters and Customers in a restaurant using threads. The program runs 40 Customers threads and 3 Waiters threads, with functions like this:
void *customer(void * vargp){
//depending on assigned table, call waiter 1-3 using semaphore
sem_post(&callWaiter);
... | With semaphores, a straightforward way would be to use sem_getvalue() on a semaphore initialized to the number of customers.
int num_customers(bool = false){
int v;
sem_getvalue(&customers, &v);
return v;
}
As customers leave, each performs sem_wait() on that semaphore. When sem_getvalue() returns 0, it me... |
69,713,981 | 69,714,007 | Is there any advantage of using a range for loop rather than an iterator? | for (auto& i : just_a_vec )
Or an iterator for loop.
for (std::vector<std::string>::iterator it = just_a_vec.begin(); it < just_a_vec.end(); it++)
| Iterators predate range-based for loops, so they used to be the only of these two alternatives available. Nowadays, range-based for has mostly replaced iterators when dealing with a simple loop.
However, iterators can be used in various other contexts as well. For example, you can do std::sort(v.begin(), std::next(v.be... |
69,714,664 | 69,719,236 | Magic Square confusion | #include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std ;
int main()
{
const int maxsize=21 ;
int magq[maxsize][maxsize] ;
int size ;
cout << "Magic Square" << endl ;
cout << "Size (odd): " ;
cin >> size ;
if( size<=0 || size>maxsize)
... | This program is about creating a magic square according to the "de la Loubère" method. There is a very good explanation on Wikipedia here. Or, because I saw some German text here.
The mechanism is totally simple. Always Go up and right (take boundaries into account). If t´his place is already filled, then go one down.
... |
69,714,747 | 69,719,351 | Identity of unnamed enums with no enumerators | Consider a program with the following two translation units:
// TU 1
#include <typeinfo>
struct S {
enum { } x;
};
const std::type_info& ti1 = typeid(decltype(S::x));
// TU 2
#include <iostream>
#include <typeinfo>
struct S {
enum { } x;
};
extern std::type_info& ti1;
const std::type_info& ti2 = typeid(declty... | This program is well-formed and prints 1, as seen. Because S is defined identically in both translation units with external linkage, it is as if there is one definition of S ([basic.def.odr]/14) and thus only one enumeration type is defined. (In practice it is mangled based on the name S or S::x.)
This is just the sa... |
69,715,426 | 69,715,501 | Can we access private members of another object within a method of a class? | #include <string>
#include <iostream>
#include <vector>
using namespace std;
class Test {
public:
int testing() {
Test t;
return t.x;
}
private:
int x = 0;
};
int main() {
Test a;
cout << a.testing() << endl;
}
I did not know I can access the private data member x of the t (the ... | Colloquially, C++'s private is "class-private" and not "object-private".
Scopes are associated with lexical elements of source code, not with run-time entities per se. Moreover, the compiled code has little to no knowledge of the logical entities in the source it was compiled from. For this reason the accessibility is ... |
69,715,892 | 69,716,691 | How to replace the value of a LPTSTR? | LPTSTR in;
// ...
std::wstring wstr(in);
boost::replace_all(wstr, "in", ",");
wcscpy(in, wstr.data());
There is any other way to replace the value of a LPTSTR?
In the code, LPTSTR is a wchar_t*
| If, and only if, the replacement string is smaller/equal in length to the search string, then you can modify the contents of the input string directly.
However, if the replacement string is larger in length than the search string, then you will have to allocate a new string of larger size and copy the characters you wa... |
69,716,141 | 69,716,569 | Removing non-prime numbers from a vector | I have a simple function that "primes a list" i.e. it returns the passed vector but without all non-primes. Essentially it removes non-primes from the vector and returns the updated vector. But my function just returns the vector without the numbers 0 and 1. Assume the vector is sorted in ascending order(0, 1, 2, 3, ..... |
const int p_limit = sqrt(foo.at(foo.size() - 1));
This will initialize the limit once, based on the last element in the list. You have to do that for each element being test for prime.
More importantly, limit_counter should be initialized for each i
Ignoring the problem with iterators, you can fix it with this pseudo... |
69,716,199 | 69,716,249 | DPAPI output buffer memory management | I'm using CryptProtectData() and CryptUnprotectData() APIs for data encryption and decryption in my App.
Reading the API documentation, it's not clear why LocalFree() needs to be called against the output buffer after usage. The example code on that page does not invoke LocalFree(), is that a miss?
What's also missing ... |
Reading the API documentation, it's not clear why LocalFree() needs to be called against the output buffer after usage.
Because CryptProtectData() dynamically allocates an output buffer and gives it to you, so you need to free it when you are done using it.
The example code on that page does not invoke LocalFree(), ... |
69,716,519 | 69,721,844 | C++ multiindex column csv load | Multi-index column csv is
Its size is (8, 8415).
This csv file was made from pandas multi-index dataframe (python).
Its columns are [codes X financial items].
codes are
financial items are
How can I use this csv file to use its year(2014, 2015, ....) as index and codesXfinancial items as multi columns?
| What kind of output you want is unclear. There are not many libraries to imitate pandas in C++. A very messy, convoluted and inelegant way of doing it is declaring a structure and then put it into a list. Something like,
struct dataframe{
double data;
int year;
int code;
char item[]; //or you can use ... |
69,716,528 | 69,728,838 | Dissapearing SDL Rects. How to update window with new additional shapes | I'm trying to update the window with a new additional rect upon key pressing, but it keeps disappearing due to SDL_RenderClear. Is it recommended to remove SDL_RenderClear?
while (!quit) {
while (SDL_PollEvent( & e) != 0) {
if (e.type == SDL_QUIT)
quit = true;
}
SDL_SetRenderDrawColor(gRenderer, 0xFF, 0... | SDL_RenderClear() is perfectly fine and in fact you should be using it. Your problem (aka the rect disappearing) is caused by the way you handle input. SDL_KEYDOWN is an event that only occurs on the frame that you press a key for, and while you're holding it down after a short delay. What you are doing is drawing the ... |
69,716,718 | 69,716,819 | how to emplace in map of(string and vector)..? | I'm not sure if it is possible to have a vector inside of a map container.
If yes, can I have the map with vector and vector?
INPUT
ONE 1 11 111 1111
TWO 22 2 2222
THREE 333 3333 3
map<string, vector<int>> mp;
How to emplace the input in the above container?
map<vector<int>, vector<int>> mp;
If this is possible to i... | Your first case is fairly easy to implement, eg:
#include <fstream>
#include <sstream>
#include <map>
#include <vector>
#include <string>
using namespace std;
void loadFile(const string &fileName, map<string, vector<int>> &mp)
{
ifstream file(fileName.c_str());
string line;
while (getline(file, line))
... |
69,717,385 | 69,725,330 | Creating DLL and using it from Excel | I have the following issue when trying to create a DLL in CPP and using it in Excel. When the argument reaches the CPP function, the value it holds changes (regardless of what it was in Excel). I am guessing somewhere it "drops", but I haven't been able to figure it out.
Here is the code:
Source.cpp
extern "C" double ... | Excel will struggle to use a function declared directly from a dll entry point as it doesn't know the types of the parameters (and other things, eg how to manage the memory of the return value). The OP's method from the tutorial may have worked in the past, but not any more it seems.
Creating a VBA user-defined functio... |
69,717,728 | 69,717,786 | In C++, how do you mutate objects in containers (vector, list, unordered_map)? | Context:
New to C++ here. I have a larger project where I have a classes A, B, and C.
Class A has a field with type unordered_map<int, B>.
Class B also has fields of class C which have fields of type set.
I want to mutate the B objects in the map because I don't want the overhead associated with immutability. I have ... | You returning a copy of your child with calling
vector<Person> getChildren() {
return this->children;
}
With this, your changes are done at the returned copy only. Not in the original stored inctance.
Use a reference to it and you get the
vector<Person>& getChildren() {
return this->children;
}
with this you ... |
69,717,841 | 69,720,238 | lldb - passing hex value as an input while debugging | I am learning lldb from security perspective. I am trying to perform a bufferoverflow in the below sample code.
#include<stdio.h>
void return_input(void) {
char array[30];
gets(array);
printf("%s\n", array);
}
int main(){
return_input();
return 0
}
gets function is the target here.
While inside lldb console, I need t... | You are trying to enter arbitrary bytes via gets() into your variable array and beyond. This is not straight-forward and partially impossible, as the standard input stream and gets() commonly does not take all codes and filter some codes.
For example, if you want the byte 0x0D (or 0x0A, depending on your terminal) in y... |
69,718,964 | 69,719,128 | What is the meaning of this command line | g++ -fsanitize=address -std=c++17 -Wall -Wextra -Wshadow -DONPC -O2 -o %< % && ./%< < inp
Especially last part with bizzare symbol sequence
Line was taken from some .vimrc file i wanted to copy
| Lets break it down:
g++ = Your compiler
-fsanitize=address = Compiler flags which adds address sanitizing. Increasing memory usage but also useful for debugging memory issues.
-std=c++17 = Your C++ standard
-Wall -Wextra -Wshadow = Your compiler error flags
-DONPC = A compilation define for ONPC
-O2 = A mild optimizati... |
69,719,155 | 69,719,280 | User defined type used in dynamic allocated 2d array | Let's assume that we have a simple struct
struct S {
int a;
int b;
int c;
}
Now we want to create an array of pointers (2d array 5x5):
S** arr = new S*[5];
for (int i = 0; i < 5; ++i)
arr[i] = new S[5];
My questions are:
Is it a correct way to dynamically allocate a memory for this array using new... |
Yes, this is correct way. No, there is no need to use sizeof(S)
Your code isn't correct. Generally you shouldn't use malloc if struct S have non-trivially-copiable members, but if S satisfy that, your code should look like this:
S** arr = (S**)malloc(5 * sizeof(S*));
for (int i = 0; i < 5; ++i)
arr[i] = (S*)mallo... |
69,719,273 | 69,721,555 | Address Sanitizer with Visual C++: ignore read buffer overflows while still catching write buffer overflows | Consider the following example:
int main()
{
char* p = new char[10];
srand(p[11]); // heap buffer overflow - read
p[11] = rand(); // heap buffer overflow - write
}
I want ASan not to flag heap buffer overflow - read for now, while still flagging heap buffer overflow - write.
The reason I want this is... | There are two directions to achieve this.
1. Continue after the error is triggered
To continue after an error, -fsanitize-recover=address option should be used. From FAQ:
Q: Can AddressSanitizer continue running after reporting first error?
A: Yes it can, AddressSanitizer has recently got continue-after-error mode. Th... |
69,719,363 | 69,722,850 | HTTPSConnectionPool error when trying to install gtest with conan | I'm trying to use conan to install gtest but when I do so I have the following error:
gtest/1.11.0: Not found in local cache, looking in remotes...
gtest/1.11.0: Trying with 'conancenter'...
ERROR: HTTPSConnectionPool(host='center.conan.io', port=443): Max retries exceeded with url: /v1/ping (Caused by SSLError(SSLErro... | This error is related to deprecated certificate.
It was discussed here: https://github.com/conan-io/conan/issues/9695
To summarize, you have 2 options:
Update your Conan client to >= 1.41.0 (Best solution):
pip install -U conan
Install a new certificate (Workaround):
conan config install https://github.com/conan-io/c... |
69,719,529 | 69,726,862 | C/C++ Validating Host and Peer with CURL for CloudFlare based websites | I`m working on an API behind CloudFlare and I would like to validate the connection fully for extended security. The platform I am using right now is Windows 10.
First I downloaded some CA's found on CloudFlare's website (Cloudflare_CA.pem, origin_ca_rsa_root.pem, origin_ca_ecc_root.pem) and then tried to contact the A... | As @David mentioned, it is correct that CloudFlare uses DigiCert Root CA (in general). However, as they state on their website this can change; which means if you hard code such check your software might break in future at any point.
Without further due the options are as following:
Option A
Buy an "Advanced" certifica... |
69,720,388 | 69,721,500 | Launching a bat file using CreateProcess windows API | I have written a bat file that works fine when launched from command prompt. Now I have written a small C++ program using `CreateProcess' to launch the bat file from a C++ program. The C++ program take 2 command line parameters. One is the path of the bat file to be executed and the otherone is a path to a file where ... | Using FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE for dwShareMode parameter of CreateFile API for file handles solves the problem
CreateFile(filehandlepate, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &secureAttr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
|
69,720,494 | 69,720,518 | Why using != to compare iterator in loop condition | In many examples regarding iterating over vectors, I noticed that often the not-equals operator is used to check whether the loop has reached the vector's end. Normally, I am using the lower-than operator in the loop condition. Hence, I am wondering, what is the rationale behind choosing !=?
Example:
std::vector<int> v... | Because not all iterators support ordering but all can be compared for equality in O(1).
For example associative (ordered) containers use bidirectional iterators, which are defined as (cppreference):
template<class I>
concept bidirectional_iterator =
std::forward_iterator<I> &&
std::derived_from</*ITER_CONCEP... |
69,720,667 | 69,721,174 | variadic template method to create object | I have a variadic template method inside a template class (of type T_) looking like this
template < typename T_ >
class MyContainer {
public:
...
template <typename ...A>
ulong add (A &&...args)
{
T_ t{args...};
// other stuff ...
vec.push_back(t);
// returning an ulong
}
}
So basicall... |
Is there any way to tell the method which parameters' type it is
supposed to take according to the template parameter T_ (which is
known when the object is created)?
In your case, you should use direct initialization(()) instead of list initialization({}) (to avoid unnecessary narrowing checks).
Consider the case whe... |
69,720,877 | 69,721,484 | Read data from file and store into RAM in C++ | I'm writing a code where I have to generate a key.bin file containing 10000 keys(1 key = 16 bytes random no.), read the Key file, and store it in the RAM. Can anyone tell me how I got about it? I'm relatively new to this, so any guidance would be great.
Thanks.
| As @heap-underrun has pointed out, it is unclear if you're talking about general RAM used in PCs or some special type of memory in some other device. I will just assume that you're talking about regular RAM in PC.
When you run a program, all the variables in the program are stored in the RAM until the program terminate... |
69,721,029 | 69,724,094 | How to improve the efficiency of QVector lookup? | For some reason, I need to traverse an image many times and I need to know which pixel points I have processed.
So I use a QVector to store the location of the pixel points I have processed each time so I can use it to determine the next time I iterate.
Examples are as follows。
QVector<int> passed;
for(int n = 0; n < 1... | Use this:
QVector<bool> passed(height * width, false);
for(int n = 0; n < 10; n++) { // Multiple traversals
for(int y = 0; y < height; y++) {
for(int x = 0; x < width; x++) {
if(......) { // Meeting certain conditions
int pos = y*width+x;
if(!passed.at(pos)) {
... |
69,721,754 | 69,722,395 | no matching function for call to ‘std::set<unsigned int>::insert(std::size_t&) | I am working on migrating my package from ros melodic to ros noetic. while doing it I got compilation error in PCL library during cmake. The package is too big I am giving some code where error happened. Any guidance would be helpfull.
This is myfile.cpp
std::vector<bool> ignore_labels;
ignore_labels.resize(2);
ignore... | I have looked into the source code for this library, here is the issue:
The type is a typedef:
The issue is that the object itself is a shared_ptr<const std::set<std::uint32_t>>
the code you have posted is allocating the object, but also calling std::set::insert on an instance of const std::set, which does not exist ... |
69,721,849 | 69,722,569 | return key doesn't work when i use regex in QT C++ | Hey guys I'm trying to use regex on line edit in QT but when I use my regex one function that do something when I enter the return key on keyboard doesn't work any more!
This is my regex on line edit:
QRegularExpression r("[0-9\\.\\+\\-\\=\\/\\*\n]{100}");
ui->lineEdit->setValidator(new QRegularExpressionValidator (r,t... | Your regex needs to support a pattern of length one, thus, {100} quantifier should be replaced with {1,100} or even {0,100}.
Besides, you may also add \r (carriage return) char to the character set, and remove unnecessary escapes:
QRegularExpression r("^[0-9.+=/*\n\r-]{1,100}$");
I added ^ and $ anchors to make sure t... |
69,722,222 | 69,722,442 | How to scan an integer array | I am new to C++. I am trying to define a binary converter function and return a pointer. Then U want to display generated binary in the main function:
#include <iostream>
using namespace std;
int* binary_con(int n)
{
int i;
int binary[100];
for (i = 0; n > 0; i++)
{
binary[i] = n % 2;
n... | you can't return an array from a function, the way is to pass that array as an argument to the functionm using this approach:
void binary_con(int n, int *binary)
now you have access to binary array inside your function, hence you can edit it and see the changes outside of the function without returning anything.
insid... |
69,723,008 | 69,823,599 | Error facing with range function in DPC++ | I'm new to Sycl/DPC++ language. I wrote a sample vector addition code using Unified shared memory (USM):
#include<CL/sycl.hpp>
#include<iostream>
#include<chrono>
using namespace sycl;
int main()
{
int n=100;
int i;
queue q{ };
range<1>(n);
int *a=malloc_shared<int>(n,q);
int *b=malloc_shared<in... |
error: redefinition of 'n' with a different type: 'range<1>' vs 'int'
Two variables with the same name within the same scope create confusion to the compiler, so it might be the reason for the error which you are getting. You can try defining the value of n globally say for eg: #define N 100 in this case, set
range<1... |
69,723,013 | 69,723,337 | Can different .dwo files be combined into a single one? | Background:
I have a need of the debugging information of the code in our project.
The following two approaches are available:
Compile using -g and afterwards use GNU binary utilities strip and objcopy to strip the debugging information into a separate file.
Compile using -gsplit-dwarf
Question
The second approach cr... | The tool you're looking for is called dwp. It collects your .dwo files into a .dwp file ("DWARF package"). .dwp files can themselves be combined into larger .dwp files if needed.
It should come with non-ancient binutils packages.
|
69,723,284 | 69,738,008 | How to resolve "C2660 'SWidget::Construct': function does not take 1 arguments"? | How can I resolve
C2660 'SWidget::Construct': function does not take 1 arguments
I am trying to put a widget that displays the controls of the game.
I am new to Unreal Engine.
Error
C2660 'SWidget::Construct': function does not take 1 arguments
C:\Program Files\Epic Games\UE_4.26\Engine\Source\Runtime\SlateCore\Publ... | Need to declare Construct function with an upper case 'C'.
Credit: splodginald
|
69,723,421 | 69,723,463 | Is std::vector allowed inside std::variant union? | I'm using std::variant as a safe-type union. On https://en.cppreference.com/w/cpp/utility/variant I've read that
A variant is not permitted to hold references, arrays, or the type void.
Does it mean that std::vector isn't allowed to be hold inside std::variant? - it is kind of array, yet I can hold std::string inside... |
Does it mean that std::vector isn't allowed to be hold inside std::variant?
It does not mean that. std::vector is none of references, arrays, or the type void. It is a (template for a) class type. std::variant is allowed to hold std::vector.
it is kind of array
The abstract data structure that std::vector models is... |
69,723,539 | 69,723,689 | Undefined symbols for architecture arm64 using g++ compiler | I'm trying to get some code to work but i keep getting the same error regardless of compiler. I'm trying to overload the operators but i get errors.
I have 3 files: main.cpp, vector2d.cpp and vector2d.h
This is the error i get with the g++ compiler:
Undefined symbols for architecture arm64:
"v2d::length()", referen... | My guess is that you have missed to add vector2d.cpp to your project. After adding that (with whatever build system you use) the errors should go away.
The errors indicate that the compiler tries to link the program without the symbols from that file present.
I cannot help with exactly how to add it since it is not spe... |
69,724,102 | 69,735,093 | Is there a difference between Apple Clang and OpenMP-enabled Clang from Homebrew? | I want to know if there are any advantages in Apple's provided Clang compiler compared to the Clang compiler that comes with OpenMP available from Homebrew?
Will there be any performance loss if switching to OpenMP Clang (regardless of the multi-threading ability)?
I also found this old question that has no good answer... |
Is there a difference?
As stated that answers itself. They're two different compilers and we don't know what Apple have done inside theirs. We do know that they don't provide OpenMP support, so that is at least one difference.
Will there be any performance loss if switching to OpenMP Clang
(regardless of the multi-t... |
69,724,298 | 69,724,588 | Removing code in Release mode using macros C++ | I have some code that is used for debugging and don't want then to be in the releases.
Can I use macros to comment them out?
For example:
#include <iostream>
#define p(OwO) std::cout << OwO
#define DEBUG 1 // <---- set this to -1 in release mode
#if DEBUG == 1
#define DBUGstart
#define DBUGend
// ^ is empty when i... | You are making this unnecessarily complicated.
Instead of conditionally inserting C-style comments if in Release, just only insert the code if in Debug. Visual Studio defines _DEBUG by default in Debug configurations, so you can use this like the following:
#include <iostream>
int main() {
std::cout << "hello the... |
69,724,441 | 69,726,345 | std::lock_guard and std::adopt_lock behaviour without locking the mutex | I have been learning about the usage of std::lock and std::lock_guard and most examples follow the pattern below:
std::lock(m1, m2);
std::lock_guard<std::mutex> guard1(m1, std::adopt_lock);
std::lock_guard<std::mutex> guard2(m2, std::adopt_lock);
//Do something here
Then I came across an example that utilized the same... | Your second example is undefined behavior; adopt_lock constructor presumes that the mutex is already held. This UB is triggered at construction, not at destruction or when an exception is thrown.
If you used unique_lock instead of scoped_lock, it has a:
unique_lock( mutex_type& m, std::defer_lock_t t ) noexcept;
con... |
69,724,800 | 69,724,989 | Time complexity with Big O notation for a called function | I read many resources about calculating time complexity O(n). I applied what I understand on my code.
Bellow is my code and my attempt to find time complexity.
my code:
float Euclidean_distance(int array_point_A[20], int array_point_B[20]) {
float sum = 0.0;
float w[20] = { 0.0847282, 0.0408621, 0.105036,... | Big-O notation only has meaning relative to one or more parameters, but you haven't described which values in your code are variable and which are constants.
As it is written, the function KNN_classifier is actually O(1) because 4344 is a fixed constand and 20 is a constant. If 20 is a constant and the size of X_train... |
69,724,884 | 69,727,729 | Access violation writing location while giving value to a struct | I am trying to give a value to a 2D struct in a loop but i keep getting Access violation writing location error
My code is :
typedef struct {
int prtcls[10],numb;
} intpos;
int main(int argc, char** argv)
{
particle_t* particles;
intpos** points = new intpos*[(int)SCALE];
for (int i = 0; i < (int)SCALE; i++) {
in... | What line? If you're using the GNU tools, gdb and a stack trace will tell you what line is crashing.
I suspect it's one of these lines:
particles[i].x =( (float)rand() / (float)RAND_MAX) * SCALE ;
points[fx][fy].numb += 1;
points[fx][fy].prtcls[curn] = i;
Are you absolutely sure all those array index values are in ran... |
69,724,991 | 69,725,074 | How to correctly define a template class return type of a template function? | What I'm trying to do is fairly simple. I have a template class PayloadResult<T> with a generic payload and in another class a template function which returns an object of such class.
class Result
{
public:
template<class TPayload>
PayloadResult<TPayload> success(TPayload payload) { return PayloadResult<TPayloa... | Below is the corrected example. You have to forward declare the class template PayloadResult<> for using it as the return type as you did in your example. Second you did not have the keyword typename or class infront of TPayload.
//forward declare the class template PayloadResult
template <typename TPayload> class Payl... |
69,725,529 | 69,725,885 | Does memory_order_relaxed respect data dependencies within the same thread? | Given:
std::atomic<uint64_t> x;
uint64_t f()
{
x.store(20, std::memory_order::memory_order_relaxed);
x.store(10, std::memory_order::memory_order_relaxed);
return x.load(std::memory_order::memory_order_relaxed);
}
Is it ever possible for f to return a value other than 10, assuming there is only one thread ... | The result of the load is always 10 (assuming there is only one thread). Even a relaxed atomic variable is "stronger" than a non-atomic variable:
as with a non-atomic variable, all threads must agree on a single order in which all modifications to that variable occur,
as with a non-atomic variable, that single order i... |
69,725,728 | 69,726,636 | g++ 10.3.0: False positive or an actual problem? | Compiling the following code with g++ 10.3 gives some fearsome warnings (see https://godbolt.org/z/excrEzjsd, too):
#include <iostream>
#include <memory>
#include <vector>
#include <cstring>
#include <boost/algorithm/clamp.hpp>
namespace demo {
template <typename T, size_t N> constexpr std::size_t array_size(T (&)[N])... | Thanks to @StoryTeller-UnslanderMonica for identifying this as a compiler bug. Adding the option -fno-peel-loops solves the problem.
|
69,725,754 | 69,725,833 | Error: no matching function for call to ‘foo::foo()’ | I have the following two files
foobar.h
#ifndef FOOBAR_H
#define FOOBAR_H
#include <cstring>
class Foo {
public:
int x;
Foo(int x);
};
class Bar {
public:
char* name;
Foo foo;
Bar(Foo foo);
};
#endif // FOOBAR_H
and foobar.cpp
#include "foobar.h"
Foo::Foo(int x) {
// Do something
}
Bar::Bar(Foo... | You are trying to default construct a Foo here:
Bar::Bar(Foo foo) {
// the member variable `foo` would have been default constructed here
// Do something
}
But Foo doesn't have a default constructor. One possible solution would be to initialize it in the member initializer list:
Bar::Bar(Foo foo) : foo(std::m... |
69,726,022 | 69,726,398 | Parse time format "DD/MM/YYYY at hh:mm:ss" & others using std::chrono::from_stream() | I'm currently trying to parse some info about the start time of an experiment as listed in a log file. After reading in the file important info, e.g column titles, start time, time between measurements, is parsed using <regex>.
I'm trying to use the std::chrono::from_stream(...) function to parse a string with the form... | ss.is_good() ?
Is that a type-o in your question or an extension in the Visual Studio std::lib?
I'm going to guess it is a type-o and that you meant ss.good()...
The good() member function checks if all state flags are off:
failbit
badbit
eofbit
eofbit in particular often does not mean "error". It simply means that ... |
69,726,776 | 69,737,342 | Conan: aggregate multiple packages to be used indepentendly | I am currently using Conan as an "helper tool" for my main project: I have created a conanfile.py that builds all my dependencies and imports them to the current folder. The goal in the end is to archive and redistribute this folder to our multiple machines and just tell CMake that everything is in there.
However, here... | This question has been answered by Conan's co-founder james here: https://github.com/conan-io/conan/issues/9874
Basically:
Use the CMakeDeps generator instead of cmake / cmake_find_package
Patch the resulting cmake config files at install time inside the generate() method from the main conanfile.py
Edit recipes accord... |
69,726,974 | 69,728,158 | how to create binary tree class? | how to correctly create a binary tree? i have an error in function AddNode. tree is not filled. root=NULL
i have class Tree with field root of type Node. then i call AddNode to recursively create nodes.
and desctructor don't work for Nodes.
#include <iostream>
#include <string>
class Node {
public:
Node() {
... | void Tree::AddNode(Node*& src, Node* parent, Node* n, bool left) {
if (src == NULL) {
src = n;
if (src->GetParent() == NULL && parent != NULL) {
src->SetParent(parent);
if (left) src->GetParent()->SetLeft(n);
else src->GetParent()->SetRight(n);
}
... |
69,727,030 | 69,795,515 | Is using std::atomic_thread_fence right before an atomic load/store with the same order always redundant? | Given:
std::atomic<uint64_t> b;
void f()
{
std::atomic_thread_fence(std::memory_order::memory_order_acquire);
uint64_t a = b.load(std::memory_order::memory_order_acquire);
// code using a...
}
Can removing the call to std::atomic_thread_fence have any effect? If so is there a succinct example? Keeping i... | Never redundant. atomic_thread_fence actually has stricter ordering requirements than a load with mo_acquire. It's poorly documented, but the acquire fence isn't one-way permiable for loads; it preserves Read-Read and Read-Write order between accesses on opposite sides of the fence.
Load-acquires on the other hand only... |
69,727,518 | 69,727,639 | how can i solve the Floating point error core dump in this code? | Hi i'm getting trouble to run this code, it's a project for school, i need to make an RSA key,but the time i compiled it,it fail. I have this type of error:
[1] 14790 floating point exception (core dumped) ./a.out
i don't use C++ since 2019 so i forgot some stuff
sorry for the confusion of the code i wrote, i'm just ... | This method:
int getE(int n_){
int e;
do{
e = rand() % 1000;
}while(e > 1 && e < n_ && e/n_ == 0);{
return e;
}
}
Can return zero, and the return value is used in a divide statement.
Also, I don't know what's with the extra brace indentation near the end.
int getE(int n_){
int e;
do{
e = rand()... |
69,727,766 | 69,729,343 | How can I resize a dynamic array of pointers without using a vector | If I wanted to resize this array:
int array[5];
I would do this:
int* temp = new int [n];
...
array = temp;
But, how would I do it if I have this array?
int *array[5];
Maybe like this?
int** temp = new int* [n];
| You CAN'T resize a fixed array, period. Its size is constant, determined at compile-time.
You CAN'T assign a new[]'ed pointer to a fixed array, either.
So, neither of your examples will work.
In your 1st example, you would need this instead:
int* array = new int [5];
And in your 2nd example, you would need this inste... |
69,727,800 | 69,727,850 | Do C++ compilers generate a def ctor if the class was not initialized? | I have written a utility class (acts as a helper class, I guess) that has only a few static member functions to be used in another class. It does not have any non-static members (variables or functions). So it also doesn't have any explicit ctors or dtor.
And the question is, does my compiler (GCC v11.2 and -std=c++20)... | (I'm slightly side-stepping your question in lieu of providing unsolicited advice) If you have a collection of static functions and your class does not require any state
class Example
{
public:
static void Foo();
static int Bar();
};
then you should likely not be using a class in the first place, rather these ... |
69,728,362 | 69,779,054 | Why casting a quoted string to "string &" causes a crash? | Please note that's just a curious question, I don't need a problem solution!
I have a method that takes in a string reference (string &some_string) and only reads from referenced string. Writing some code I forgot that it needs a reference and passed a quoted string (not a variable, just like "something") and IDE sugge... | A cast like this
(string)"a string literal"
constructs a new std::string by passing "a string literal" as an argument to its constructor. It is equivalent to static_cast<std::string>("a string literal"). It is completely valid, even though C-style casts in C++ are a bad idea in general.
On the other hand, a cast like ... |
69,728,564 | 69,732,805 | static link pthread on ubuntu causes uninitialised value jumps (valgrind) | When im statically linking the pthread library on ubuntu 20.04, using the gcc 11.1 compiler, during its runtime, my program works exactly as expected. However when i tried to run it in a debug mode and check with valgrind for any problems, i quickly discovered that linking the pthread library causes a lot of warnings ... |
If i don't link the library statically, there are no errors or warnings.
Linking libpthread or libc on Linux statically is almost always the wrong thing to do. Your executable may be broken in many subtle ways, if not now then in the future.
That said, the reason you get Valgrind errors is explained here.
|
69,728,662 | 69,729,131 | How do I have to describe an absolute path to a file in C++? | I want to do a program in C++ that, when is executed (from anywhere), modifies a text file in a very specific path (and always the same one). To do so, I've defined the following function in C++:
void ChangeCourse(string course)
{
ofstream active_course;
active_course.open("~/.universidad/curso_activo.txt");
... | In C++17 you can use the filesystem library and hard code the path, if this is what you really want to do.
#include <filesystem>
#include <fstream>
namespace fs=std::filesystem;
int main() {
fs::path p = "your-absolute-path-goes-here"; //
if(fs::exists(p)) {
std::ofstream file(p);
file << "Hello world!"... |
69,728,782 | 69,728,861 | Default Constructor Parameter Error - 'Autoturism::Autoturism(char *,unsigned int)': cannot convert argument 1 from 'const char [6]' to 'char *' | A solution is to convert "Rosie" to char* using (char*), I am curious if it is another one.
| First, note that your default parameter value (c = new char[1]()) is a memory leak, since the constructor doesn't take ownership of the new[]'ed memory to delete[] it later. There is never a good reason to use new[]'ed memory for a parameter's default value.
"Rosie" is a string literal. It has a type of const char[6],... |
69,729,033 | 69,729,264 | Is std::decay_t<T> decay_copy(T&&) equivalent to auto decay_copy(auto&&)? | http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3255.html defines decay_copy as follows:
template<typename T>
std::decay_t<T> decay_copy(T&& v)
{
return std::forward<T>(v);
}
I just wonder:
Is it equivalent to the following simpler one?
auto decay_copy(auto&& v)
{
return v;
}
| It wasn't in 2011, because:
We didn't have auto return type deduction for functions (that's a C++14 feature), and
We didn't have auto&& parameters for functions (that's a C++20 feature), and
Rvalue references were not implicitly moved from in return statements (that's also a C++20 feature)
But in C++20, yes, that is ... |
69,729,216 | 69,729,622 | Is it possible to use structured binding in the member initializer list of a constructor? | I would like to create a class with several const member variables. Unfortunately, the function I need to initialize those variables is from a very C-style external library. As a result, I have been employing the following "middle-man" of sorts:
struct Struct {
int foo, bar;
Struct(int baz, int qux) {
i... | Structured bindings declare variables (well, they're not "variables" per-se, but nevermind). You cannot use structured bindings to manipulate existing objects. This includes member objects.
|
69,729,273 | 69,729,501 | cppyy and std::is_same_v (C++17) | If I run the following test script in cppyy v1.6.2 on my Ubuntu 20.04 system:
#!/usr/bin/python3
import cppyy
cppyy.cppdef("""
struct Test {
void test() const {
std::cout << std::is_same<int,double>::value << std::endl; // works
std::cout << std::is_same_v<int,double> << std::endl; // doesn't work
}
};
"... | Why use cppyy 1.6.2? Latest release is 2.1.0. A big difference between the two is a much newer version underlying Clang in the latter (the latter also makes it possible to enable c++2a, even). That said, both 1.6.2 and 2.1.0 have no problem with the above code for me, so most likely it's an installation/build issue.
Fi... |
69,729,696 | 69,729,741 | why is there a "no instance of overloaded function matches the argument list" error when attempting vector push_back? | I am doing an assignment for a C++ class and I am getting an error when using push back with vector. I honestly cannot find any info on why this isnt working and giving me a "no instance of overloaded function" error
class StudentData {
class StudyModule {
private:
const int studyModuleCode;
c... | The function addModules() is declared like this:
void addModules(const StudyModule& module);
that is, its parameter is a reference to const object.
But the vector has a pointer to a non-const object as its template argument:
std::vector<StudyModule*> modules;
Thus, the compiler issues a message for this statement:
th... |
69,729,824 | 69,730,210 | Rules of injecting behavior to templated function using function overloading | When writing templated libraries, sometimes it is desirable to implement behavior later than the definition of a function template. For example, I'm thinking of a log function in a logger library that is implemented as
template< typename T >
void log(const T& t) {
std::cout << "[log] " << t << std::endl;
}
Later i... |
If the codes are illegal, what would be a good alternative to injecting library templates? (I'm thinking of passing functions/functors explicitly to my doFoo function, like what <algorithm> is doing.)
You can combine functors with a default trait type to get a "best of both worlds". That's essentially how the unorder... |
69,730,161 | 69,730,367 | C++ Program is not entering "for" loop | I am making a program that finds how many anagrams does a line contain for homework and I have a problem. My program is not entering a simple "for" loop. I've been reading whole evening and I cannot understand what is the problem. I've put 7 control cout-s to see where exactly does it enter and where not. Results are -... | Re:
It entered the loop and threw another exception
when i is 0, you are accessing v[-1]:
for(int i=0; i<sz; i++)
{
cout<<4<<endl;
if (isAnagram(v[i - 1], v[i]))
|
69,730,239 | 69,731,930 | C++ template return type for an abstract method (similar to java) | Let say I have a visitor in Java.
interface Visitor<T> {
T visitA(VisitableA a);
T visitB(VisitableB b);
}
abstract class Visitable {
abstract <T> T accept(Visitor<T> visitor);
}
class VisitableA extends Visitable {
@Override <T> T accept(Visitor<T> visitor) {
return visitor.visitA(this);
... | Do what Java does under the hood.
Replace T with std::any.
For Visitable make a base class that returns any to both methods. Then make a template class that implements the any returning as final, and creates a T returning Visit as pure for implementors to implement.
Visitable has two methods; a pure virtual private on... |
69,730,386 | 69,730,690 | C++ timedelta with strftime? | I want to do a function to get the current time with a certain format. C++ is not my main language but im trying to do this:
current_datetime(timezone='-03:00', offset=timedelta(seconds=120))
def current_datetime(fmt='%Y-%m-%dT%H:%M:%S', timezone='Z', offset=None):
offset = offset or timedelta(0)
return (dateti... | Just add the offset to the seconds since epoch.
std::time_t t = std::time(nullptr) + offset;
You would also make offset of type std::time_t, as it represents a distance in time in seconds.
|
69,730,892 | 69,731,101 | Typedef (anonymous) struct array of size 1 | So recently I've been poking around in the internals of GMP for a project I'm working on, and I've encountered a construct that makes very little sense to me: (taken from the header for version 6.2.1)
/* For reference, note that the name __mpz_struct gets into C++ mangled
function names, which means although the "__... | Given typedef __mpz_struct mpz_t[1];, you can declare an actual mpz_t object with mpz_t foo;. This will reserve memory for an mpz_t.
In contrast, if the type were typedef __mpz_struct *mpz_t;, then mpz_t foo; would only give you a pointer. There would be no space for an mpz_t. You would have to allocate it, and you wou... |
69,731,073 | 69,742,354 | Interpreting UTF-8 unicode strings in c++ | Currently coding in C++20 using WSL2 Ubuntu, G++.
If I had a .txt file consisting of utf-8 unicode characters:
▄ ▄ ▄▄▄ ▄ ▄ ▄▄▄▄ ▄▄ ▄ ▄ ▄▄▄
How can I get the length (number of unicode characters) of this unicode string?
How can I read the file content and print out the unicode string?
| Assumptions:
stdout supports UTF-8 (on Windows you can get by with chcp 65001 at the cmd prompt)
We're counting Unicode code points, not glyphs made up of multiple code points.
UTF-8 encoding consists of start bytes following the bit patterns:
0xxxxxxx (single byte encoding)
110xxxxx (two-byte encoding)
1110xxxx (th... |
69,731,086 | 69,731,107 | What does the "@" symbol mean in a makefile when after an -I flag such as -I @mathinc@? | I'm trying to understand the following line in a Makefile.in file:
CXXFLAGS += -O3 -DNDEBUG -std=c++11 -Wno-deprecated-declarations -Isrc -I @mathinc@
I know the -I flag adds a directory to the list of places where the compiler will search for included files but what does @mathinc@ mean?
| Note that the file is called Makefile.in -- this signifies that it is input to another file (or transformation).
In short, configure will run and determine, say, where the relevant include files are for @mathinc -- likely some math headers. After you run configure it will produce Makefile (no trailing .in) based on wha... |
69,731,174 | 69,731,242 | Compiling a .cpp file with c++ command instead of g++ (Linux) | Let's say we have a simple c++ file named hello.cpp which prints "Hello World!".
We generally create the executable using g++ hello.cpp. When I tried executing the command c++ hello.cpp it creates the executable successfully. Shouldn't it throw an error saying there is no c++ command available? and suggest us to use g+... |
Shouldn't it throw an error saying there is no c++ command available? and suggest us to use g++?
Weeelll, there are no regulations or standards that restrict or require c++ command to do anything, so there is no "should" or "shouldn't". However, it would be strongly expected that c++ is a working C++ compatible compi... |
69,732,120 | 69,819,318 | Simple OpenMP-enabled code does not compile: "clang: error: linker command failed with exit code 1" | I tried to test OpenMP on MacOS with the Apple Clang compiler that comes with Xcode.
Code:
#include <iostream>
#include <cmath>
#include </usr/local/opt/libomp/include/omp.h>
int main() {
std::cout << "Hello, World!" << std::endl;
#pragma omp parallel
{
printf("Hello World! \n");
}
return 0... | By using set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}") and using set in other places, you are replacing the flags that CMAKE puts. It is better to append in this case rather than replace. You can use add_compile_options(-Wall) here.
As mentioned by @Tsyvarev, it is perhaps better to use imported library. Her... |
69,732,129 | 69,732,422 | Errors in a custom sine function | I am prototyping a sine function for an extremely simple programing language (Namely, limitations being only signed int variable types, and only operations between variables). However, there seems to be an error every radian or so with a given value for "s" that is greater than or equal to 0.9. This error seems to be a... | Your a7 variable is overflowing.
In your code, the value of a7 gets as large as 2,431,570,725 and as small as -2,443,460,910. Your int range is probably almost, but not quite, that large. A typical value of INT_MAX is 2,147,483,647.
Change it to a long or long long or something like that.
|
69,732,251 | 69,732,408 | Got an error while compiling this code for K sorted array problem | i was doing this question where we need to sort k sorted arrays in a single array and compiler threw an error:
"prog.cpp:20:23: error: expected ) before & token
struct mycomp(triplet &t1 , triplet &t2){"
I am a begginner can someone help me understand whats the issue.
`` code ```
struct triplet{
int val; int apos; ... | There are many other errors/mistakes in your given program. The one you mentioned is because mycomp is a struct and so while writing its definition you can't pass parameters to it(since it is not a function definition). This particular error can be fixed by changing mycomp definition to:
//mycomp is a struct and not a... |
69,732,496 | 69,732,651 | how do I handle an Array for a 2D Vector in an Object of another class? | I need a little help with an appointment of mine.
My professor gave us this class (and a Color class that has RGB colors as float variables inside) now I have to implement the functions shown in the header.
#include "color.h"
#include <assert.h>
Color::Color()
{
R = 255;
G = 255;
B = 255;
}
Color::Color( ... | RGB data is usually stored in a one-dimensional array, as is the case for RGBImage. The pixels are packed line-by-line, starting either from the bottom left, or the top-left of the image. The orientation should not affect the functions accessing individual rows of pixels, but will affect how the calling application h... |
69,733,052 | 69,734,891 | Binary Search in C plus plus | the code when executes creates an infinite loop.
What is wrong with this code :-(
using namespace std;
int main(){
int arr[10]={1,20,30,75,90,189,253,302,304,455}, start=0, end=9, item, mid, i;
cin>>item;
mid=(start+end)/2;
while(arr[mid]!=item){
mid=(start+end)/2;
if(item>mid){
start=mid+1;
... | Answering your actual question: "What is wrong with this code?", see comments below:
using namespace std;
int main(){
int arr[10] = {1,20,30,75,90,189,253,302,304,455}, start=0, end=9, item, mid, i;
cin >> item;
mid = (start+end) / 2;
// You function loops indefinitely... The first place to look is ... |
69,733,736 | 69,733,931 | How can I eliminate garbage value in this output? | In this below program, I'm trying to marge 2 arrays into a single vector, but while returning the function I'm getting additional garbage values along with it.
Please anyone suggest me how to remove those!
#include <bits/stdc++.h>
#include <vector>
#include <string>
using namespace std;
vector <int> merge(int a[],int... | You want something like this:
include <iostream>
#include <vector>
#include <algorithm> // <<<< dont use #include <bits/stdc++.h>,
// but include the standard headers
using namespace std;
vector <int> mergeandsort(int a[], int lengtha, int b[], int lengthb) { // <<<< pass the lengths ... |
69,733,780 | 69,733,813 | How to add to std::map an object with constant field? | Suppose I have the following code:
#include <string>
#include <map>
struct A {
const int value;
A(int value) : value{value} {}
};
int main() {
A a{3};
std::map<std::string, A> myMap;
myMap["Hello"] = a; // Error: Copy assignment operator of 'A' is implicitly deleted because
... | Use map::emplace to construct A in-place:
myMap.emplace("Hello", 3);
Demo.
If the key doesn't exist in a map, then assignment means "add pair
[key, value] to the map". But if the key exists, then replace the
value.
As @Serge Ballesta commented, when the key already exists, you need to erase the node from the map and... |
69,734,062 | 69,734,161 | Why do we need object files? | Why do we need object files? I've tried linking multiple files by using the command g++ -o main.exe main.cpp (other files).cpp, and it works. However, from tutorials online, it needs the files to be turned into *.o files first by using the command g++ -c main.cpp (other files).cpp, and use g++ -o main.exe main.o (other... | TL;DR version:
You don’t need to create the object files. It’s fine to directly compile into an executable.
Long version:
You do not need to explicitly create the object files here. However, do note that the compiler does create these object files as intermediate files for each source file. Once, the compiler has all t... |
69,734,167 | 69,734,192 | What's the difference between (const_cast<char*> and without? | I'm having a hard time understanding the difference between those two commands
char name[0x36];
sprintf_s(name, "Some Text (%d%% Water) [%dm]", amount, dist);
Drawing::RenderText(const_cast<char*>(name), screen, cfg.visuals.ships.textCol);
and
char name[0x36];
sprintf_s(name, "S... |
What's the difference between (const_cast<char*> and without?
The difference is that in one case the conversion is implicit and in the other case the conversion is explicit. There is no other difference.
|
69,734,237 | 69,734,388 | Dynamic binding and virtual functions - Vector of base class objects, access the "correct" member function | I'm fairly new to c++, and I'm trying to understand as much as possible of the language and the underlying mechanics.
I am confused about a specific case where I can't seem to access the correct member function when I have two classes (Base and Derived) even though I define them as virtual.
class Base {
public:
vir... | Because of object slicing. When you create your vector you copy your objects into it.
std::vector<Base> v{ b, d };
The catch is that inside the std::vector you have only objects of type Base, NOT Base and Derived. If you want polymorphic behavior with containers in C++, you usually do it with pointers, as you can't ke... |
69,734,500 | 69,735,384 | Using macros with bazel build | I am using macro for enabling logging in my code. Also, I am using bazel build.
Currently i need to change my .cpp file to include #define to enable this macro. Is there a way that i can provide this alongwith bazel build command ?
| One option would be to control the #define directly with the --cxxopt flag.
Consider for example this code:
#include <iostream>
#ifndef _MY_MESSAGE_
#define _MY_MESSAGE_ "hello"
#endif
int main(int argc, char const *argv[]) {
std::cerr << "message: " _MY_MESSAGE_ "\n";
#ifdef _MY_IDENTIFIER_
std::cerr <... |
69,734,567 | 69,734,711 | Why to use _tcscpy_s instead of _tcscpy? | I am new to C++ programming. I am carrying out an SAST violations check for my code, and the scan throws a warning:
_tcscpy(destination_array,Source);
The dangerous function, _tcscpy, was found in use at line 58 in Source.cpp file. Such functions may expose information and allow an attacker to get full control over t... | The actual difference is that _s functions check the destination buffer before writing to it. If the buffer is too small then either the program is aborted, or an error value is reported, depending on the current error handler.
This prevents buffer overrun attacks, when malicious data is formed in some specific way to ... |
69,735,035 | 69,735,114 | When dose move constructor and default constructor called | I have this code
class MyString {
public:
MyString();
MyString(const char*);
MyString(const String&);
MyString(String&&) noexcept;
...
};
String::String()
{
std::cout << "default construct!" <<std::endl;
}
String::String(const char* cb)
{
std::cout << "construct wit... |
Why is that happening?
Since C++17: Because MyString("test") is a prvalue, and the language says that s1 is directly initialised from "test" in this case.
Before C++17: Because the side effects of move (and copy) constructor are not required/guaranteed to occur which allows the compiler to optimise by not creating th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.