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 |
|---|---|---|---|---|
71,520,028 | 71,520,082 | Segmentation Fault when refrencing vectors that changed size | So I initialize a vector within a main function, and pass that vector as a reference into a function where its size changes. Now, I would imagine that the initialized vector within the main would change in size, but its not. Am I just implementing this incorrectly?
#include <iostream>
#include <vector>
using std::vecto... | while(std::cin >> operation){
vector<vector<char> > myVector;
The very first thing that happens in this while loop is that a new myVector gets created. This is, literally, what this says in C++.
When the end of the loop gets reached, this myVector gets destroyed. That's how C++ works: if you declare an obj... |
71,520,512 | 71,521,598 | Enumeration conversion and undefined behavior | From cpprefernce/static_cast/8:
A value of integer or enumeration type can be converted to any
complete enumeration type.
If the underlying type is not fixed, the
behavior is undefined if the value of expression is out of range (the
range is all values possible for the smallest bit field large enough
to hold all enum... | I'm going to write this with a focus on how to read cppreference.com. (This might make it seem more like I am answering one question instead of going over the limit.)
How the underlying type of an enum cannot be fixed.
This is a question about the enumeration type. So if the answer is not on the current page, the nex... |
71,521,561 | 71,521,676 | Passing two parameters at c++ lambda expression | I wanted to get a subset of vector having the same keyword in the vector.
The code below works well, if I give the fixed keyword.
auto category_matched = [](Product &p) {
std::string str_return;
p.GetInfo(kINFO_CATEGORY, str_return);
return str_return == "keyword";
};
std::copy_if(list_.begin(), list_.end... | capture the keyword
std::string keyword = "froodle";
auto category_matched = [&keyword](Product &p) {
std::string str_return;
p.GetInfo(kINFO_CATEGORY, str_return);
return str_return == keyword;
};
|
71,521,750 | 71,521,798 | How can I get the data type for boost::any variable? | I am looking for a way to check boost::any data type.
If i assign an int to boost::any like:
boost::any num1 = 5;
And then use typeid(num1).name() , i want my output to be "int" so that i can use it in a if else statement in the future. However for some reason it keeps giving me this as the data type: N5boost3anyE
#in... | You need to use boost::any's member function type() which returns a const std::type_info& of the contained value
cout << "num1.type().name(): " << num1.type().name() << endl;
|
71,522,331 | 71,522,505 | C++20 [[no_unique_address]] not working with clang's win32-coff target | While working with clang-13 in C++20, I noticed that the x86_64-pc-win32-coff cross-compile target seems to outright reject the [[no_unique_address]] attribute. This attribute is otherwise supported for other targets that I tested with.
Consider this minimal example:
struct bar {};
struct foo {
[[no_unique_address... | no_unique_address is something whose primary support has to be handled at the ABI level. Both the Itanium ABI and Microsoft's de-facto ABI (aka: whatever MSVC does) support no_unique_address... kinda.
See, Microsoft is not at present willing to cause an ABI break. And since the attribute does nothing under a C++17 buil... |
71,522,403 | 71,565,047 | d3dx12.h identifier undefined | I'm learning DirectX 12. I want to use d3dx12.h header file but there are lots of error, most of them are "identifer 'something' undefined'.
So I searched about this problem and got some solutions.
This is "check Windows SDK version" and I updated VS2019. But that's not a good solution for me.
So I thought that DirectX... | The 'latest' version of D3DX12.H on the DirectX-Headers GitHub site is assuming you are using the Agility SDK 1.7 Preview which adds some new types like D3D12_GLOBAL_BARRIER.
You should use the D3DX12.H from the release or perhaps this copy.
|
71,522,473 | 71,524,290 | ZeroMemory a struct with std::string and assigning value to it has different behavior in VS2010 and VS2017 | We are upgrading an old MFC project from VS2010 to VS2017, and we discovered a different behavior when assigning data to an std::string inside a struct which was cleared using ZeroMemory.
I created a simple MFC program to replicate the issue.
std::string getStrData() {
std::string temp = "world";
return temp;
}... | The code has never been correct. Initializing an object by writing literal zero values into memory doesn't have and never had1 any well defined behavior. For trivially copyable types you often get away with it, in practice, but the behavior is still undefined. The code in question, however, cannot claim that gray area ... |
71,522,719 | 71,522,757 | Error: Object(char message []) not compiling with Object("Text") | I am having an issue with trying to send a ("msg") from main to a Object(char arr[]).
InputNum(char msg [])
{
cout << msg;
cin >> _num;
}
int main()
{
InputNum num ("Enter a Number");
}
The above throws an error from the g++ compiler:
ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-... | You are trying (unknowingly) to make a string literal writable. C++ doesnt like this at all.
You have to do
void InputNum(const char msg []) {
cout << msg;
}
this promises the compiler that you wont try to change the conents of 'msg'
|
71,522,737 | 71,546,426 | Error while loading shared object file: No such file or directory | I am trying to generate a usable binary for GCBM, a C++ carbon accounting tool. The binary has been generated from a GitHub Action workflow which is available as an artifact here: https://nightly.link/HarshCasper/moja.canada/actions/runs/1999997115/GCBM.zip
I downloaded the ZIP, unzipped it inside a gcbm directory, cd ... | Example, how to run GCBM/moja.cli with the ~40 internal shared libraries
mkdir GCBM && cd GCBM/
unzip GCBM.zip
chmod +x moja.cli
## create a script moja.sh to run moja.cli :
#!/bin/sh
export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
exec ./moja.cli
## make the script executable and run ./moja.sh
|
71,522,815 | 71,523,041 | Why does the xorshift random number generator always seem to use these specific shifts? | I was going through a book that explained the xorshift algorithm (I know, basic stuff). Then, while searching a little bit more on the Internet, I found that all the basic examples seem to shift the bits right/left the same "amount" (13, 17, 5).
For instance:
struct xorshift32_state {
uint32_t a;
};
uint32_t xorshif... | This is actually a lot more subtle and interesting than you might suspect!
The xorshift random number generator has an interesting theoretical backstory. The use of shifts and XORs corresponds to performing a matrix-vector product where both the matrix and the vector are made of 0s and 1s. The specific matrices in ques... |
71,522,834 | 71,523,040 | Which C++20 standard library containers have a .at member access function? | Which C++20 standard library containers have a .at function? For example, at least std::map, std::unordered_map and std::vector do. What others are there?
Is there some way to work this out without going through the 2000 page standard by hand?
| I ended up grepping libstdc++ include directory for \bat( and that has given me:
std::basic_string
std::basic_string_view
std::array
std::vector
std::vector<bool>
std::unordered_map
std::map
std::dequeue
I'm not sure if this is exhaustive.
There is also rope and vstring but I don't think these are standard.
|
71,522,961 | 71,523,022 | "undefined reference to `operator>>(std::istream&, Complex<int>&)" for template Complex<T> | My code:
#include <iostream>
using std::cin;
using std::cout;
using std::istream;
using std::ostream;
template<typename T>
class Complex
{
T real, img;
public:
Complex():real(0), img(0){}
friend istream& operator>>(istream& input, Complex& c1);
friend ostream& operator<<(ostream& output, Complex& c1);
... | Friend functions are not members so they aren't implicitly templates. Declaration there suggests existence of non-template operator for instantiated type Complex<int>.
You may use
template<typename U>
friend istream& operator>>(istream& input, Complex<U>& c1);
template<typename U>
friend ostream& operator<<(ostream&... |
71,523,003 | 71,523,079 | Iterating the creation of objects in C++ | I want to be able to create N skyscrapers. Using an inputdata string, I would like to give them coordinate values of their X and Y positions. My main function I used "i" to demonstrate that I am trying to create as many skyscrapers as I can using the input data. Essentially, I would like to create N/3 skyscrapers and a... | Jeff Atwood once said: use the best tools money can buy. And those aren't even expensive: Visual Studio community edition is free. Such a proper IDE will tell you that the skyscraper is unused except for the assignments.
Since you probably want to do something with those skyscrapers later, you should store them somewh... |
71,523,157 | 71,539,648 | Thrust is very slow for array reduction | I am trying to use thrust to reduce an array of 1M elements to a single value. My code is as follows:
#include<chrono>
#include<iostream>
#include<thrust/host_vector.h>
#include<thrust/device_vector.h>
#include<thrust/reduce.h>
int main()
{
int N,M;
N = 1000;
M = 1000;
thrust::device_vector<float> D(... |
Am I doing something wrong here?
I would not say you are doing anything wrong here. However that might be a matter of opinion. Let's unpack it a bit, using a profiler. I'm not using the exact same setup as you (I'm using a different GPU - Tesla V100, on Linux, CUDA 11.4). In my case the measurement spit out by th... |
71,523,366 | 71,524,341 | Aggregate values of same key in std::multimap and store in std::map | I essentially want to group the elements of the multimap by key, and obtain the new data structure as a map.
the multimap:
std::multimap<std::string,std::vector<int>> multiMap;
VecA VecB
ABC 10 30
ABC 10 30
DEF 20 20
the output required:
std::map<std::string,std::vector<int>> map;
VecA VecB
ABC 20 60
... | If you want use Arithmetic operators
Use valarray
Demo: https://wandbox.org/permlink/SAnHNKNZ0UufqZsN
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <valarray>
#include <numeric>
int main()
{
using key_type = std::valarray<int>;
key_type b = {10,20,30,40};
auto contai... |
71,523,835 | 71,523,872 | How can i read all files in directory in c++? | I want to read all files in specific directory.
for example
In directory a there are file1.text file2.txt a.txt c.txt
I want to know how many words are included in each file.
I made a code for a file.
But I don't know how to automatically move on next file at same directory.
int EBook::get_total_words()
{
ifstream ifs(... | With std::filesystem you can do this:
std::string path_to_dir = '/some/path/';
for( const auto & entry : std::filesystem::directory_iterator( path_to_dir ) ){
std::cout << entry.path( ) << std::endl;
}
|
71,523,854 | 71,523,971 | How to mmap Eigen into shared memory? | I want to use Eigen library as my shared memory data structure (by mmap).
here is my code:
producer.cpp:
#include<sys/mman.h>
#include<sys/types.h>
#include<fcntl.h>
#include<string.h>
#include<stdio.h>
#include<unistd.h>
#include <vector>
#include <iostream>
#include <string>
#include "eigen3/Eigen/Dense"
typedef Ei... | Dynamic Eigen matrices are like std::vector. They don't hold the actual data, they contain pointers to the data plus the size information. You mmapped the object, not the actual data.
Something like this should work:
Eigen::Index rows = 100, cols = 100;
const void* space = mmap(NULL, rows * cols * sizeof(double),
... |
71,523,997 | 71,524,353 | How to get a property name and offset in a class at compile time or runtime? | I have a class named SoftInfo.
class SoftInfo
{
public:
std::string m_strSoftName;
std::string m_strSoftVersion;
std::string m_strInstallLocation;
}
I want to export it to lua in a c++ program via sol3. I write something like this and I can use it in lua world. However, there are something unconvenien... | What you're asking for is called static reflection. Unfortunately, C++ doesn't have that. However, with boost describe, you may get quite close
#include<boost/describe.hpp>
BOOST_DESCRIBE_STRUCT(SoftInfo, (),
(m_strSoftName,
m_strSoftVersion,
m_strInstallLocation))
void Export(lua_state _state)
{
so... |
71,524,337 | 71,524,402 | what is the output of conditional operator with unary operator | I have the following code where behavior is not clear to me. Can some one please help how conditional operator evaluate the following code and output ans as 1
#include
int main() {
bool delayMessages=0;
bool Delay = false;
delayMessages += Delay ? 1 : -1;
std::cout << "Hello world!"<<delayMessages;
return 0;
}
Ans... | The expression on the right hand side is evaluated like an if-statement.
if (Delay == true)
return 1;
else
return -1;
The result is then used for the += assignment.
In the
C++20 draft standard that's
7.6.19 (6) (Assignment and compound assignment operators)
The behavior of an expression of the form E1 op= E2 is... |
71,524,565 | 71,524,831 | Can an iterator such as std::filesystem::directory_iterator be used outside of a loop? | I'm trying to understand how things like iterators can be used in c++, and would specifically like to understand std::filesystem::directory_iterator better.
I understand the straight forward examples like this:
#include <iostream>
#include <filesystem>
#include <string>
void doSomething(std::string filename)
{
std... | It is easily possible to manually increment iterators (since that is what the range based for loop does as well). However you need to adjust the other code accordingly, as there is no operator bool for std::string. One possible solution (only slightly modifying the original code, which still includes all its issues) co... |
71,524,636 | 71,529,455 | What am I missing in my custom std::ranges iterator? | I'd like to provide a view for a customer data structure, with it's own iterator. I wrote a small program to test it out, shown below. It I uncomment begin(), then it works. But if I use DummyIter, then I get a compile error.
In my full program, I've implemented a full iterator but for simplicity, I narrowed it down to... | The way to check this kind of thing for ranges is:
Verify that your iterator is an input_iterator.
Verify that your sentinel is a sentinel_for your iterator.
Those are the checks that will tell you what functionality you're missing.
In this case, that's:
using I = DummyIter<int>;
using S = std::vector<int>::const_ite... |
71,526,324 | 71,530,071 | Exception with OpenCv DnnSuperResImpl (C++) | I have a problem with the upsample function from the dnnsuperres pack of OpenCV.
I am transferring a bmp via a pipe from one application to another. The image resides in datamem, which is an unsigned char array. I use the pipe to transfer many other things, so I transfer the data in the most common datatype.
If I do th... | the DnnSuperResImpl will only accept 3 channel, BGR images, not your 4 channel bitmaps.
convert your image to 3 channels, while decoding it:
matImg = cv::imdecode(cv::Mat(1, SizeToRead, CV_8UC1, datamem), cv::IMREAD_COLOR);
sr.upsample(matImg, outputImage);
So far I found no documentation which says that it needs thr... |
71,527,216 | 71,527,678 | Class initialization fails with default constructor | I am learning about classes in C++ and I created a simple one that just creates an interval from int a to int b, using a dynamic int array. Here's the code:
Interval::Interval() {
a_ = 0;
b_ = 0;
interval = new int[2];
for (int i = 0; i <= 1; ++i) {
interval[i] = 0;
}
}
Interval::Interval(i... | Noting that your default constructor is equivalent to Interval(0,0), you can reuse the non-default constructor instead, by forwarding to it:
Interval::Interval() : Interval(0,0) {}
Interval::Interval(int a, int b)
: a_(a <= b ? a : 0),
b_(a <= b ? b : 0)
{
if (a_ == b_) {
interval = new int[2]... |
71,528,284 | 71,531,169 | std::variant constructed from uint32_t prefers to hold int32_t than std::optional<uint32_t> using GCC 8.2.0 | I've got the following code:
#include <variant>
#include <optional>
#include <cstdint>
#include <iostream>
#include <type_traits>
using DataType_t = std::variant<
int32_t,
std::optional<uint32_t>
>;
constexpr uint32_t DUMMY_DATA = 0;
struct Event
{
explicit Event(DataType_t data)
: data_(data)
{}
templa... | Here's a reduced version:
constexpr int f() {
return std::variant<int32_t, std::optional<uint32_t>>(0U).index();
}
For gcc 8.3, f() == 0 but for gcc 10.2, f() == 1. The reasoning here is ultimately that variant initialization is... complicated.
Originally, when C++17 shipped, the way that initializing a variant<T... |
71,528,539 | 71,529,023 | What happens to a reference when the object is deleted? | I did a bit of an experiment to try to understand references in C++:
#include <iostream>
#include <vector>
#include <set>
struct Description {
int a = 765;
};
class Resource {
public:
Resource(const Description &description) : mDescription(description) {}
const Description &mDescription;
};
void print_set(con... | The note is misleading, treating references as syntax sugar for pointers is fine as a mental model. In all the ways a pointer might dangle, a reference will also dangle. Accessing dangling pointers/references is undefined behaviour (UB).
int* p = new int{42};
int& i = *p;
delete p;
void f(int);
f(*p); // UB
f(i); // ... |
71,528,931 | 71,529,033 | c++ std::fstream. How do I read a number at the start of the line (a float or an int), and then skip to the next? Using named variables so no loop | I have a text file in the following format:
100 #gravity
5000 #power
30 #fulcrum
I want to assign these values to named variables, like so:
void Game::reloadAttributes()
{
float test1, test2, test3;
string line;
std::fstream file;
file.open("attribs.txt");
if (file.is_open()) { ... | An object of type istream (in this case cin) takes user input. So of course the program will wait for you to input a value and then store it inside test1, test2, and test3 respectively.
To fix your issue, just replace cin with file as such:
file >> test1;
file.ignore(50, '\n');
file >> test2;
file.ignore(50, '\n');
f... |
71,529,124 | 71,603,895 | SYCL program working using VS Debugger but not when running the .exe | I am trying to build and run a simple SYCL program from this book. Here it is:
#include <CL/sycl.hpp>
#include <iostream>
using namespace sycl;
const std::string secret {
"Ifmmp-!xpsme\"\012J(n!tpssz-!Ebwf/!"
"J(n!bgsbje!J!dbo(u!ep!uibu/!.!IBM\01"
};
const auto sz = secret.size();
int main(int argc, char* arg... | The answer has been brought by the Intel Developer Software Forums.
Although the compiler has been well installed on my machine, the oneAPI environment had not be configured yet. This is why it couldn't work when running the .exe in the Windows command prompt.
I had to run the batch file setvars.bat that was at the adr... |
71,529,364 | 71,544,923 | execve() is not executing the script when trying to run a script using it | I wanna run a script using execve(). in the following code, I am printing environment variables in c++ code then I pass the output of those to a script called "usrscript" to print them there but the execve() is not executing the script. `
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib... | The problem was solved by replacing #!usr/bin/bash with #!/bin/bash in the script.
|
71,529,704 | 71,529,705 | Compiler variance for overloading over array reference parameters | The following program is, as expected, accepted by both GCC, Clang and MSVC (for various compiler and language versions):
// #g.1: rvalue reference function parameter
constexpr bool g(int&&) { return true; }
// #g.2: const lvalue reference function parameter
constexpr bool g(int const&) { return false; }
stati... | GCC is wrong
Since the argument is an initializer list, special rules apply, as per [over.ics.list]/1:
When an argument is an initializer list ([dcl.init.list]), it is not an expression and special rules apply for converting it to a parameter type.
As the parameter type for both overloads are references types, [over.... |
71,529,777 | 71,532,505 | Displaying a C++ class via QML in QtQuick2 | I am working on a QtQuick 2 application (Qt version 6.2.3). I created one C++ class (let's call this class "Example") that contains the data that my application should deal with. This class can be instantiated several times, representing different datasets to be displayed.
class ExampleObject : public QObject {
Q_O... | You can optimize the binding textToDisplay such that you don't have to call the upate and reinitialize functions, which seems to be the question you are after:
property var exampleCppObject
property string textToDisplay : exampleCppObject ? exampleCppObject.property1 : ""
In case you need more complex logic in the fut... |
71,529,819 | 71,530,105 | Contradicting definition of references | I am learning about references in C++. In particular, i have learnt that references are not actual objects. Instead they refer to some other object. That is, reference are just alias for other objects.
Then i came across this which says:
Important note: Even though a reference is often implemented using an address in ... |
Important note: Even though a reference is often implemented using an address in the underlying assembly language, please do not think of a reference as a funny looking pointer to an object. A reference is the object, just with another name. ...
Notes are informal and usually should not to be interpreted as strict ... |
71,530,023 | 71,531,069 | Why images can be uploaded with char array but not with equal std::istringstream in C++? | Consider the code below for a second:
char buffer[4000];
size_t bytes = recv(fd, buffer, 4000, 0);
write(pipefd[1], buffer, bytes);
close(pipefd[1]);
wait(NULL);
Here I read fd, write data to the pipe and close the pipe. This allows to eventually upload tiny images that can be rendered. However, if... |
std::istringstream data(buffer);
This assumes buffer is a null-terminated string. Binary data typically contains 0x00 bytes, thus you would end up truncating the buffer contents.
Use this instead:
std::istringstream data(std::string(buffer, bytes), std::ios::binary);
|
71,530,163 | 71,533,834 | detect 16 bit checksum | hi guys recently im working on reverse engineering a device but now after several weeks hard working i got into checksum calculating problem !
the data is 8 of 16 bit data, the last one is 16bit checksum.
here is example of data :
0x0400 0x0000 0x0000 0x0001 0x0200 0x0000 0x0000 0x4000
0x0301 0x0000 0x0000 0x0001 0x... | Looks like CRC-16/MODBUS, at least the first three match:
https://crccalc.com/?crc=000d000000000100000200000000&method=CRC-16/MODBUS&datatype=hex&outtype=0
https://crccalc.com/?crc=010d000000000100000200000000&method=CRC-16/MODBUS&datatype=hex&outtype=0
https://crccalc.com/?crc=020d000000000100000200000000&method=CRC-... |
71,530,661 | 71,530,771 | Is there a way i could end a loop with a char in c++? | I am new to programming, and I am currently trying to figure my way around C++. I am working on a program that will display basic information about employees to the users, and I want the program to end when the users entered a char. However, while working through it, I encountered a problem. When I enter the char (x), ... | Yes, of course. In C/C++, char is a type that can be represented either by its character value ('A', for example) or its numeric value (65). However, a digit's numeric value does not equal to itself.
'1' == 49
120 is the ASCII value of lower case x and since you loop with an int, it is logical that it will end up work... |
71,530,932 | 71,531,100 | Best way to parallelize this for loop with multiple threads | I currently have a code block like this
UINT8* u = getResult();
for (UINT64 counter = 0; counter < MaxCount; counter++)
{
for (UINT64 index = 0; index < c_uOneMB; ++index)
{
*u++ = genValue();
}
}
Now in order to make this run faster. I am doing something like this. Basically splitting the inner th... | With little details you have provided I can give only this:
std::generate_n(std::execution::par, getResult(), MaxCount * c_uOneMB, genValue);
https://en.cppreference.com/w/cpp/algorithm/generate_n
https://en.cppreference.com/w/cpp/algorithm/execution_policy_tag
|
71,531,268 | 71,531,567 | code is Not returning the correct character in cpp | Question: First uppercase letter in a string ( Recursive)
Doubt: why this code is not returning the correct character even though it is entering in the if clause at correct time(when the letter is in uppercase). I have added these cout statements for debuging purpose only.
# include <bits/stdc++.h>
using namespace std... | I'm assuming this is an academic exercise. No one would actually implement this task using recursion (nor would they use magic numbers, the plague known as <bits/stdc++.h>, a dreadful practice common on junk "competitive" programming sites, etc.)
That said, a very common mistake made by students when learning recursion... |
71,531,333 | 71,547,653 | How set CMake to find a local package FFmpeg? | I am trying write CMakeLists with FFmpeg package, with compile on Windows and Linux.
First downloaded from FFmpeg-Builds shared releases
I imagine the structure of the project like this:
<project root>
deps/
ffmpeg/
win-x64/
incluve/
lib/
bin/
linux-x64/
incluve/
lib/
bin/
... | The following worked well for me on Linux with cmake.
You will have to find the equivalents for Windows.
I used ffmpeg on Windows, but without cmake (i.e. directly in a Visual Studio project).
Install pkg-config, nasm:
sudo apt-get install -y pkg-config
sudo apt-get install nasm
Download ffmpeg source cod... |
71,531,724 | 71,533,065 | msvc std::lower_bound requires const operator* | I am getting a
Error C2678 binary '*': no operator found which takes a left-hand operand of type 'const _InIt' (or there is no acceptable conversion)
it is thrown by this code in MSVC (2022, V17.1) <algorithm> header.
template <class _FwdIt, class _Ty, class _Pr>
_NODISCARD _CONSTEXPR20 _FwdIt lower_bound(_FwdIt _... | std::lower_bound takes a Cpp17ForwardIterator, which must also be a Cpp17InputIterator. The Cpp17InputIterator requirements include:
Expression
Return type
*a
reference, convertible to T
Here, a is a "value of type X or const X", so MSVC is justified in requiring a const-qualified unary indirection operato... |
71,532,341 | 71,547,147 | How to use MPI_BCast with dynamic array of own datatype objects | There was a problem with passing dynamic array of object pointers via MPI_BCast(...). When I try to send array that I got error ended prematurely and may have crashed. exit code 0xc0000005. If I use MPI_BCast(...) with one object (like this MPI_Bcast(myObjArray[0], dataTypeMyObject, 1, 0, MPI_COMM_WORLD);) it work corr... | MPI_Bcast() expects that the input elements are continuous in memory, i.e. that the 10 MyObject instances are located "behind each other" in memory. But in your case you pass in an array of pointers into MPI_Bcast(), but MPI_Bcast() will not dereference the individual pointers.
Instead, try
MyObject * myObjArray = new ... |
71,532,344 | 71,534,844 | Getting very big error trying compile hello world | MINGW | Something happened to my compiler, and now I can't even compile hello world.
Here's a link to error that I'm getting https://pastebin.com/HtyUdz6f , looks like my std libraries broken or something.
How I can fix this problem ?
#include <iostream>
using namespace std;
int main()
{
cout<<"Hello World";
return 0... | This code compiles and runs on other C++ compilers, therefore the problem is likely caused by the compiler, not by the program itself.
MinGW-w64 8.1.0 has not been updated since 2018, and will most likely stay without updates in the near future. Therefore, the software likely no longer works on modern software/operatin... |
71,532,567 | 71,532,910 | Writing a function to find largest number from array in a text file | I can write a program to find the largest and smallest value in main, but I do not know how to do this in a separate function and for the numbers to be gotten from a file.My task is to enter numbers in an array which will be stored in a file and then the largest of those numbers needs to be found. I can write separate ... | There are sooo many ways to do this. Here's one:
void Find_Largest(std::ostream& output_file)
{
int smallest = 0;
int largest = 0;
std::cout << "Please enter number 1:\n";
std::cin >> smallest;
largest = smallest;
output_file << smallest << "\n";
for (int i = 1; i < 5; ++i)
{
s... |
71,533,025 | 71,533,145 | What is the difference between *(pointer) and (*pointer)? | Please see the following block of code. Can you tell me the difference between *(sample) and (*sample)?
for(i = 0; i < num_samples ; i++ )
{
*(sample) &= 0xfff ;
if( (*sample) & 0x800 )
*(sample) |= 0xf000 ;
*(sample+1) &= 0xfff ;
if( *(sample+... | This is purely a question about operator precedence
*sample , *(sample) and (*sample) all do this same thing in isolation. They deference the 'sample' pointer
Things get more interesting when combined with other operators. You have an example
*(sample+1)
Lets take out the parens
*sample+1
This could mean two thi... |
71,533,672 | 71,533,988 | Bug in Clang-12? "case value is not a constant expression" | I stumbled upon a strange compile error in Clang-12. The code below compiles just fine in GCC 9. Is this a bug in the compiler or is there an actual problem with my code and GCC is just too forgiving?
#include<atomic>
enum X {
A
};
class U {
public:
std::atomic<X> x;
U() { x = A; }
};
... | Looks like a bug to me. Modifying case A to case nullptr gives the following error message (on the template definition):
error: no viable conversion from 'std::nullptr_t' to 'std::atomic<X>'
Making the class template into a class as suggested in the question then gives
error: value of type 'std::nullptr_t' is not impl... |
71,533,755 | 71,534,065 | c++ Bind wide string to sqlite3 prepared statement | I am trying to bind wide string to sqlite3 prepared statement. I was trying to follow this answer, but it didn't work
const auto sql_command = L"SELECT * FROM register_names WHERE name is ?VVV";
sqlite3_stmt *statement;
sqlite3_prepare16(db, sql_command, -1, &statement, NULL);
wstring p = ObjectAttribut... | In your SQL statement, change is to =, and change ?VVV to just ?.
More importantly, per the documentation, sqlite3_exec() is not the correct way to execute a sqlite3_stmt you have prepared. You need to use sqlite3_step() (and sqlite3_finalize()) instead.
Try this:
const auto sql_command = u"SELECT * FROM register_names... |
71,533,998 | 71,534,097 | If I use alignas on a class, is the first member or base class aligned? | If I declare my class struct alignas(16) C { int x; };, is x guaranteed to be aligned to 16 bytes or could the compiler pad it on the “left”? What about template <typename T, std::size_t Align> struct alignas(Align) Aligned : T { using T::T; };? Would the T of Aligned<T, N> be aligned to N? Is that the right way to mak... |
If I declare my class struct alignas(16) C { int x; };, is x guaranteed to be aligned to 16 bytes or could the compiler pad it on the “left”?
In this case, x has to be on the 16 byte boundary because you have a standard layout class. A standard layout class comes with a guarantee that the first member of the class s... |
71,534,829 | 71,534,915 | Why does char 0x0 becomes 0xFF (255) in QT C++ QByteArray? | Via the USB, I send the following to my QT C++ application. As you can see, we are sending total 5 bytes of data to my QT C++ application.
/* Create array of prescalers */
uint8_t send_data_array[5] = {0};
uint8_t index = 0;
/* Fill the array */
send_data_array[index++] = SEND_BACK_PWM_PRESCALERS_MESSAGE_TYPE;
send_da... | It is unspecified whether char is signed or unsigned.
usbDataRaw.at(byteIndex + 1) results in a char that intends stores the value 250. It looks like on your platform char is signed, so this value is actually -6.
Arithmetic operations on integer types smaller than int get promoted to int before the operation is perform... |
71,535,059 | 71,566,523 | Out of bounds index returns correct values from vector created in chibi scheme | I've embedded chibi scheme into my C++ application and am trying to create a float vector with a size of 3 in scheme, and then get the individual values of that vector back into my c++ program, however when I attempt to do so I only get the correct results if I use indexes beyond the size of the vector. As you can see ... | Figured out the issue. It's because sexp_vector_ref(vec, i) evaluates to
#define sexp_vector_ref(x,i) (sexp_vector_data(x)[sexp_unbox_fixnum(i)])
and sexp_unbox_fixnum(i) evaluates to
#define sexp_unbox_fixnum(n) (((sexp_sint_t)((sexp_uint_t)(n) & ~SEXP_FIXNUM_TAG))/(sexp_sint_t)((sexp_sint_t)1<<SEXP_FIXNUM_BITS))... |
71,535,416 | 71,539,580 | Why doesn't the default case run here? | I wrote these following lines of codes:
#include <sdl.h>
#include <iostream>
#include <stdio.h>
#include <string>
bool running = true;
enum KeyPressSurfaces {
KEY_PRESS_SURFACE_DEFAULT,
KEY_PRESS_SURFACE_UP,
KEY_PRESS_SURFACE_DOWN,
KEY_PRESS_SURFACE_LEFT,
KEY_PRESS_SURFACE_RIGHT,
//de dealloca... | I created a solution for you, and I have some notes to check from your end,
Check if the file path is correct
../pikachu/keypress_bmp/default.bmp.
When you want to trigger the default, you should press another key
e.i Enter, A, B, etc.
I have downloaded an SDL library I am not sure if you are using the
same, but mine ... |
71,535,569 | 71,537,317 | C++ question: I'm having problems writing array of doubles (single precision 32 bit) to a disc file as 4-byte IEEE754 format | I have an application I'm trying to write in which will take a table of numbers (generated by user) and write the table to a file on disc. This file will then later be transferred to an Arduino AVR device over USB to its EEPROM.
The format I wish to save this information in on disc is 4-byte Little Endian as just raw H... |
In a text stream, the new-line character is translated. Some operating systems translated to \r\n. A binary stream leaves it as it is.
Regardless of how you opened the stream – binary or text:
a. When you use the insertion/extraction operator the data is written as text. Assuming 0x01 is a one byte integer, ASCII 1 ... |
71,535,696 | 71,537,864 | Introduced intermediate variable in structured binding definition? | In [dcl.struct.bind] 9.6.4, there is definition of structured binding when initializer is a class type with std::tuple_size<E>::value properly defined:
... variables are introduced with unique names ri as follows:
S Ui ri = initializer ;
Each vi is the name of an lvalue of type Ti that refers to the object bound ... | The intent is to disallow redeclaring structured bindings as references. See CWG 2313.
|
71,535,879 | 71,535,920 | Using C wrapper of C++ code for ABI stability? | In his talk Jason Turner proposed to break the C++ ABI to keep the language moving forward. He also mentioned that if needed due to compatibility reasons, C++ ABI changes can be isolated by wrapping a C++ library into a C library.
A relevant screenshot at 27:30:
Here "BinaryLibrary" and "Old C++ stdlib" use an old ABI... | Can the C ABI change? Well, not easily. There have been occasional changes on some platforms, but so many systems and languages are built using the C ABI as a public interface that it has to be quite stable. Many languages have a C FFI which allows them to call C functions, and changing the C ABI would break those. ... |
71,535,946 | 71,536,230 | Using command line parameters outside of main function | I would like a program to read in a file entered by the user via the command line, which is then used in the main body of the code.
See example code below:
#include <iostream>
#include <fstream>
struct run_t {
std::string file;
};
run_t run;
const POINTER* ptr = toy(run.file, 0);
// Here hardcoded the FILENAME ... | Here is the code I have tested. Try this
#include <iostream>
#include <fstream>
#include <math.h>
struct run_t {
std::string file;
};
run_t run;
class POINTER{
public:
POINTER(std::string file , int num){std::cout << "POINTER::POINTER(std::string file , int num)file " << file << std::endl;};
double fun... |
71,535,955 | 71,536,130 | Why custom comparator for set in c++ requires extra 'const' keyword | I am solving a problem on leetcode OJ where i had to use a custom comparator for set in C++.
typedef pair<pair<int,int>,int> ppi;
class comp
{
public:
bool operator()(const ppi & p1, const ppi & p2)
{
if(p1.first.first == p2.first.first)
{
if(p1.first.second == p2.first.second) ... | By adding that const to the end of that member function you're making it a const member function, meaning that it cannot possibly modify any of your member variables. Because calling a non-const member function could modify the object, you can't call it if the object is const.
std::set's erase member function requires ... |
71,536,013 | 71,536,319 | How can I read all files in the same directory? | I made a code for counting words in a file.
But I want to adjust it to read all .txt files in the same directory. I found that I have to use <filesystem> but I dont know how to adjust it.
int EBook::get_total_num_words()
{
map <string, int> words;
int count = 0;
string ws;
ifstream file("inputs\\test.t... | You already know about directory_iterator. Simply move the ifstream inside the loop, constructing it with the path of the current entry, eg:
int EBook::get_total_num_words()
{
map <string, int> words;
string word;
std::string path = "\\inputs";
for (const auto& entry : std::filesystem::directory_i... |
71,536,199 | 71,541,182 | Prevent "microsoft visual c++ runtime library debug assertion failed" window from appearing upon program crash | I am wondering if there is a way to automatically terminate the program entirely when an exception is thrown, rather than having to choose between the "abort", "retry", and "ignore" buttons on the Visual C++ library window that appears?
.
(example image)
Is there any solution for this? (aside from the obvious -- fixing... | Yes, you can suppress the message box by passing _OUT_TO_STDERR to _set_error_mode().
In case you still get a message box telling you that abort() was called and you want to disable it, too, you additionally need to call _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG).
Full example:
#include <cassert>
#include <cstdl... |
71,536,610 | 71,537,391 | Why does c++ for each loops accept r-values but std::ranges do not? | A statement like this compiles without error:
for (int i : std::vector<int>({0, 1}))
std::cout << i;
But a statement like this does not:
std::vector<int>({0, 1}) |
std::views::filter([](int i) { return true; });
Why are r-values allowed in for each loops but not in std::range pipes? Is there a way I could get som... | The for-loop works fine because the vector<int> (rvalue) is valid while the loop is evaluated.
The second code snippet has 2 issues:
The predicate must return a bool
the vector<int> you are using in the views object is dangling by the time it is evaluated, so the compiler does not accept it.
If instead of a vector<in... |
71,536,672 | 71,539,260 | Does shared_ptr a = make_shared() create a copy of the shared_ptr before constructor is run? | This might be a stupid question.
Let's say we're in C++11 land and we use make_shared() to create a smart pointer. We then use this smart pointer to initialize a variable with like this:
std::shared_ptr<class> = make_shared(/* args to c'tor of class*/ );
Now I know two things:
Assignement is not initialization. In th... | There are two things to avoid the copy:
1 is the compiler's RVO (return value optimization);
2 is the move constructor/assignment.
for code auto foo = std::make_shared<Foo>();
RVO will create the object directly on the stack. and even we disable the RVO by -fno-elide-constructors, the move constructor will try used a... |
71,536,932 | 71,537,072 | What is happenning in this template header? | There is an amazingly useful answer on how to serialize eigen matrices using cereal:
Serializing Eigen::Matrix using Cereal library
I copied and verified this code works, but I am having a hard time understanding what is going on in the header:
template <class Archive, class _Scalar, int _Rows, int _Cols, int _Options,... | The template uses SFINAE (Substitution Failure Is Not An Error) to limit the template parameters this function takes.
Basically if the compiler considers the function signature of the template function to be erroneous, it simply ignores this function instead of producing a compiler error.
typename std::enable_if<traits... |
71,538,369 | 71,541,057 | Failure to select correct operator== with MSVC but not gcc/clang for templated class | The following example compiles fine using gcc and clang, but fails to compile in MSVC. I would like to know if I have unwittingly stumbled into non-standard territory? If not, which compiler is correct? And is there maybe a workaround?
Minimal example (https://godbolt.org/z/PG35hPGMW):
#include <iostream>
#include <typ... | I'm surprised that MSVC doesn't compile your code, that seems to me perfectly correct.
So... not sure... but I suppose that is a MSVC bug.
Anyway... given that you also ask for a workaround... I see that also for MSVC works SFINAE if you enable/disable the return type of the operators, so I propose that you rewrite you... |
71,538,502 | 71,541,820 | google mock unable to mock a method with a templated argument | I am not sure if what I am trying to do is possible, but I have a hard time with the compiler trying to mock a method which contains a templated reference parameter.
The interface (removed all irrelevant methods)
class iat_protocol
{
public:
virtual void get_available_operators(etl::vector<network_operator, 5>&) = ... | Well, this is strange, but simple using fixes your problem.
#include "gmock/gmock.h"
struct network_operator {};
namespace etl {
template <typename T, unsigned N>
struct vector {};
} // namespace etl
using vector_5 = etl::vector<network_operator, 5>;
class iat_protocol {
public:
virtual void get_available_o... |
71,538,730 | 71,538,790 | Argument list for class template `sgl::Bag` is missing | So I am currently working on a project to make a library with all of the different data structures in C++. Here I have declared a class Bag:
template<typename Type>
class Bag
{
// ...
inline static const char* print_seperator = "\n";
public:
// ...
inline static void set_seperator(const char* new_sepe... | You can use default template argument for the template type parameter Type as shown below:
//use default argument for template type parameter "Type"
template<typename Type = int>
class Bag
{
// ...
inline static const char* print_seperator = "\n";
public:
// ...
inline static void set_seperator(const ... |
71,538,925 | 71,540,857 | Insert at given position in link list , in code why we need (pos-2) | In the code given below we insert a node at a given position.
My question is: Why do we need to use pos-2 in the for condition?
insertNode(Node *head,int pos,int data)
{
Node *temp=new Node(data);
if(pos==1)
{
temp->next=head;
return temp;
}
Node * curr=head;
for(int i=1;i<=pos-2... | Some things to note:
We want curr to point to the node that precedes the position where the new node is to be inserted. This is because we will make the insertion happen with curr->next=temp, where temp is the new node.
Since the head node has no predecessor, it is a special case. This occurs when pos is 1.
When pos is... |
71,539,247 | 71,539,364 | glGenBuffer causes segmentation fault | when using glGenBuffers with almost any other gl function the program crashes in startup
#define GL_GLEXT_PROTOTYPES
#include </usr/include/GLFW/glfw3.h>
#include <iostream>
int main()
{
glfwInit();
GLFWwindow *wd = glfwCreateWindow(900, 800, "main window", NULL, NULL);
glfwMakeContextCurrent(wd);
GLui... | Change:
GLuint *buffer;
glGenBuffers(1, buffer);
glBindBuffer(GL_ARRAY_BUFFER, *buffer);
to:
GLuint buffer;
glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
The problem is: You are giving OpenGL the value of an uninitialized variable, which it will treat as a memory location to... |
71,539,371 | 71,539,450 | How to convert a string into a multidimensional array of chars | I have a std::string that contains a random phrase.
For example:
std::string str{ "Lorem ipsum" };
I'd like to take that string and convert it into a std::vector<std::vector<char>> (each sub-array would have all the characters for one word in the phrase, i.e. splitting on spaces).
For example after the conversion:
std... | #include <bits/stdc++.h>
using namespace std;
int main()
{
vector<vector<char>> v;
vector<char> c;
string s = "hello world this";
for(int i=0;i<s.size();i++)
{
if(s[i]==' ')
{
v.push_back(c);
c.clear();
}else{
c.push_back(s[i]);
... |
71,539,895 | 71,542,367 | Combining Qt with OpenGL: does not compile | I'm trying to create a project in Qt with an QOpenGLWidget and CMake as a building tool. The problem is that it does not compile and I don't know why.
[...]\include\ui_MainWindow.h:79: błąd: undefined reference to `__imp__ZN13QOpenGLWidgetC1EP7QWidget6QFlagsIN2Qt10WindowTypeEE'
That's my CMakeLists.txt file:
cmake_min... | In Qt6 QOpenGLWidget was moved to a new module named OpenGLWidgets.
To make your program work you need to add OpenGLWidgets to your find_package command and Qt6::OpenGLWidgets to your target_link_libraries command.
find_package(Qt6 COMPONENTS Widgets OpenGL OpenGLWidgets REQUIRED)
target_link_libraries(QtTest PRIVATE Q... |
71,540,234 | 71,542,027 | Is accessing elements on a 16 byte aligned contigous memory with paddings between elements faster than tightly packed elements in memory? | So imagine if we had a custom memory allocator that we initialize with a size of 64, and whenever we want to construct a new element inside it, the allocator aligns every element's starting address to be a 16-byte aligned address.
For example: If the allocator allocated a memory on heap that starts from address 0x00 to... | A 16-bit Processor
Let's say I have a processor that loves to make fetches of 16-bits.
When data is aligned on a 16-bit boundary, the processor only has to make one fetch:
+---+---+
4 | a | b |
+---+---+
In one fetch, the processor can get both a and b (which are 8-bit quantities).
If we have data that is no... |
71,540,246 | 71,540,512 | Is it possibile to embed python libraries in C++? | Is it possibile to use python libraries in C++ like selenium , django etc ....? If yes are there any docs that explain this well like fully embedding a python library in C++ not just some run script like PyRun_SimpleString() ???
| If you want to mix Python in a C++ project, a simple possibility is to include Boost in your project, and rely on the Boost.Python library which enables interoperability between Pyton and C++ (https://www.boost.org/doc/libs/1_78_0/libs/python/doc/html/index.html); This is basically a wrapper around the Python C API to ... |
71,540,463 | 71,540,812 | How to write native C++ in VS 2022, using Linux for build and test | I need a native C++ app to make from scratch. It has to run on linux (CentOS). I want to use VS2022 to write and test. I have Hyper-V VM with CentOS.
I tried to google a solution but there are only posts for using WSL.
Can someone please describe steps to connect VS to Linux VM instead of WSL so I can build and run the... | This article describes the process: https://devblogs.microsoft.com/cppblog/linux-development-with-c-in-visual-studio/
add workload to the VS using VS Installer (Linux and embedded..)
create project of correct type
add SSH credentials in the project Properties (also can be added/removed/edited in Tools-Options-Cross Pl... |
71,540,734 | 71,540,801 | How to deal with constness when the method result is cached? | I have a class with a method (getter) that performs some relatively expensive operation, so I want to cache its result. Calling the method does not change behavior of the object, but it needs to store its result in this, so it can't be const.
The problem is that I now have another method that is const and I need to inv... | This is one of the situations the mutable specifier fits particularly well. When a class member is mutable, that member can be changed even if the enclosing class is const.
So, if MyClass::cachedValue is a mutable Foo* instead of a Foo*, you can have const member functions in MyClass that make changes to cachedValue an... |
71,540,901 | 71,540,962 | I can't print out sentence with 'cout' in c++ | first I not a native English speaker so if you find errors in my English ignore them,
below my code
#include <iostream>
#include <string>
#include <vector>
using namespace std;
//Globle variables
int Counter = 0 ;
vector<string> tasksList;
string task;
//functions
int AddingTasks(){
cout<<"type your task... | Change AddingTasks by:
int AddingTasks()
{
cout << "type your task here: ";
cin >> task;
tasksList.push_back(task);
cout << tasksList[tasksList.size() - 1] << " added " << endl;
return 0;
}
What is happening is, you're trying to access an object that does not exist in the vector.
|
71,541,210 | 71,555,756 | Valgrind ClientCheck uninitialized string | I'm new to Valgrind, and I've had some trouble finding the source of some of it's warnings. I've been using the VALGRIND_CHECK_VALUE_IS_DEFINED macro from memcheck.h to try and locate the exact source of the error, which has led me to wonder if I am using the tool correctly.
Here is a sample program that I run with Val... | The reason for this is fairly straightforward. An std::string roughly consists of a pointer, length and allocated_capacity members. On 64bit Unix-like platforms they are all 8 bytes. The "SSO" [Small String Optimization] will recycle (and extend) the allocated capacity member via a union to store the string if it is sh... |
71,541,973 | 71,542,031 | What is the logic behind "<" and ">" string operators in c++? | I wanted to sort a vector of strings in terms of their ASCII order and my first try was using < > operators.I got some weird results and then I found compare function for strings in c++ and completed my task.
But after that when I was reading c++ reference, It was written that > < operators are using the exact compare ... | "ali" and string a = "ali"; are two ways to define a string value but have different types.
"ali" is a string literal, which the C++ standard defines as an array of n const char where n is the length of the string up to \0. This is commonly seen as const char[n]
string a = "ali"; type is explicitly defined with a type ... |
71,542,209 | 71,542,272 | I'm trying to print only uppercase letters from some input using for loop to iterate trough characters, but for some reason it doesn't work | I'm 100% sure from testing that for loop does iterate through characters how is it suposed to, but the other part of the program isn't working correctly.
Im trying with if statement to print only uppercase characters.
Here are some input/output samples to get a better pitcure what this program is about:
Input: Tim-Bern... | Your code will calculate compare name[i] == 'A' first and then take
the result to do OR operation with 'B', 'C', and so on..., which absolutely won't work.
You should do name[i] == 'A' || name[i] == 'B' || ... or just use std::isupper().
|
71,542,397 | 71,542,723 | Pascal triangle matrix using vectors in C++ | I need make Pascal Triangle matrix using vectors and then print it.
This algorithm would work with arrays, but somehow it doesn't work with matrix using vectors.
#include <iomanip>
#include <iostream>
#include <vector>
typedef std::vector<std::vector<int>> Matrix;
int NumberOfRows(Matrix m) { return m.size(); }
int N... | The main problem is that in PascalTriangle, you are starting out with an empty Matrix in both the number of rows and columns.
Since my comments mentioned push_back, here is the way to use it if you did not initialize the Matrix with the number of elements that are passed in.
The other issue is that NumberOfColumns shou... |
71,542,730 | 71,542,770 | I am getting the error that variable "count" is not being initialized. But it should be initializing after reading and verifying data from file. C++ | I am working on Login/Registration system. So far I am getting the error that the variable "count" is used without being initialized.
bool count;
string userId, password, id, pass;
system("cls");
cout << "\t\t\n Please enter the username and password\n\n";
cout << "Username:";
cin >> userId;
cout << "Password:";
cin >>... | Your C++ compiler is smart enough to figure out that if the file could not be opened or is empty, the while loop never executes even once, and count remains uninitialized until its value is checked after the loop. That's what your C++ compiler is telling you.
Just because the input file exist or is not empty, and its c... |
71,543,391 | 71,547,943 | Vertically flip text | I'm using Fontstash to load and render my text. However when I draw, the text is vertically flipped:
flipped text
I cannot change the origin so I think I have to rotate the texture here, however I'm not sure how to do it or if it's the proper way.
I set the matrices like this:
GLint viewport[4];
glGetIntegerv(GL_VIEWPO... | Wyck pointed out that I had face culling enabled, disabling it resolved the issue just fine when flipping the orthographic matrix.
|
71,543,491 | 71,544,653 | what does char() print out in C++ | I tried to find documentation on this but there doesn't seem to be any definite answers to this. I tried in an example program, and it seems to \0 but is this reliable behavior? What does char() initialize to and is this in the C++ standard.
int main()
{
std::cout<<char()<<std::endl;
return 0;
}
| The fact that char() returns \0 is normal, and it's reliable (integer variables are initialized to 0 with such a syntax, and pointers are initialized to nullptr). For example, unsigned short int() will also returns 0. For a char, it's obviously not the character "0", but the NUL character.
Then, when trying to print th... |
71,543,516 | 71,545,265 | The adc should be able to work well for this kind of applications? | I've been trying to process speech on a stm32f407ve development board for some time now, which makes me wonder if the ADC is really set up to precisely sample the values. CMSIS FFT Functions. But when I try to couple it with the ADC in continuous conversion to sample a sine signal, it doesn't seem to sample well period... | You are just calling the function to take a single reading over and over in a loop. There is no reason to think that each pass through this loop will take the same amount of time. You need to set the ADC to be triggered from a timer in order to have some kind of reproducible sample rate.
In general the internal ADC i... |
71,543,726 | 71,543,774 | GetLastError returns 998 when CreateWindow failed and returns 0 | In main.cpp:
#include "window.h"
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
Window main_window(hInstance, nCmdShow);
main_window.Intitialize(CS_HREDRAW, NULL, LoadCursor(NULL, IDC_ARROW), (HBRUSH)(COLOR_WINDOW), (WIDE_CHAR) "Application", (WIDE_CHAR) "Wind... | You are passing (WIDE_CHAR) "Application" and (WIDE_CHAR) "WindowName" to Intitialize.
As you defined
typedef wchar_t* WIDE_CHAR;
the parameters are NARROW characters cast to WIDE characters. When CreateWindowExW tries to access them, it goes out-of-bounds (because wide string is twice as long as narrow), resulting in... |
71,543,860 | 71,543,892 | Why sort function in Go and C++ is different? And I can't get the right results in Go | I want to sort a slice named nums while not disrupting the original order.
So I use inds to record the index of nums and sort inds:
vector<int> nums = {1,3,2,1,1,1};
vector<int> inds = {0,1,2,3,4,5};
sort(inds.begin(), inds.end(),
[nums](int i, int j) -> bool
{
return nums[i] > nums[j];
});
for(int i : inds... | The anonymous function arguments i and j are indices in inds, but the program uses the arguments as indices in nums.
Fix by using inds to translate the index values to nums:
sort.Slice(inds, func(i, j int) bool {
return nums[inds[i]] > nums[inds[j]]
})
|
71,543,991 | 71,544,098 | I got a error ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 | i am learning to implement a simple Stack base machine using Linklist with c++. There are constant.h, Stackframe.h, StackFrame,cpp, main.cpp. I code on MacOs 10.14.6 with Visual Studio Code.
I am getting some trouble when i run main.cpp file.
Here is error that i got:
cd "/Volumes/public/initial/" && g++ main.cpp -o ma... | You haven't told g++ to compile and link in StackFrame.cpp.
Where you have
$ g++ main.cpp -o main
you should have
$ g++ main.cpp StackFrame.cpp -o main -lstdc++
The addition of -lstdc++ might not be required with newer versions of g++.
|
71,544,120 | 71,544,149 | It is possible to assign an object to another with a different type | I'm working with a C++ project and I need to do some assignment code to assign one object to another with a different type like this:
MyClass1 o1;
MyClass2 o2;
o2 = o1;
Ofc, we can make this work with the help of a copy assignment operator of MyClass2: MyClass2& operator=(const MyClass1&).
But this gonna be a very hea... | yes, you can... but I is not recommended unless the two classes have an exact one to one correspondence and the exact same meaning in the domain of your problem.
Why is not recommended?
Because the operation needs to be manually implemented (the compiler cannot help with a = default declaration).
auto operator=(M... |
71,544,411 | 71,544,449 | Iterate over a vector and create another vector based on elements | Maybe a stupid/naive question, but if I have a vector of vectors like this:
std::vector<std::vector<Element> vec
what is the most efficient way to create another vector from this one which containes all the sizes of elements from the previous vector:
std::vector<std::size_t> newVector = {vec[0].size(), ..., vec[vec.siz... | There might be a 1-liner approach using something from <algorithm> or fancy accumlator/transform routine. But it's hard to beat the readability of this:
std::vector<std::size_t> newVector;
for (const auto& item : vec) {
newVector.push_back(item.size());
}
If you prefer the hip way to do it, which some people like... |
71,544,619 | 71,544,724 | Allocating memory to a list stl inside class through user | class Graph
{
int num;
public:
Graph(int n)
{
num = n;
}
list<int>* mylist = new list<int>[num];
int* arr = new int[num];
queue<pair < int, int >> pq;
void accept();
};
int main()
{
int n;
cout << "Enter the number of vertices=";
cin >> n;
Graph g=Graph(n);
... | You should learn about C++'s initialization, which is important and different from assignment.
In you example, initialization of mylist and arr happens before "initialization" of num (in fact, you are not initializing num, what you do is default-initialize it and then assign to it), hence the value of num is indetermin... |
71,544,912 | 71,544,964 | wrapping templated function call in another function call | Anyone know if it is possible to do something similar to the following:
void my_inner_func(int i, double d, ...) {
// do stuff here
}
template <typename Func, typename... Args>
void my_outer_func(Func&& f,Args&&... args){
// do other stuff here, put this inside loop, etc
f(std::forward<Args>(args)...);
}
... | It works if you make my_outer_func a function object rather than a function:
struct my_outer_func {
template <typename Func, typename... Args>
void operator()(Func&& f,Args&&... args) const {
// do other stuff here, put this inside loop, etc
f(std::forward<Args>(args)...);
}
};
Then:
func(m... |
71,545,204 | 71,545,266 | Accessing an std::set via a dereferenced iterator | Consider:
#include <stdio.h>
#include <set>
void printset(std::set<int>& Set) {
for (std::set<int>::iterator siter = Set.begin(); siter != Set.end(); ++siter) {
int val = *siter;
printf("%d ", val);
}
}
void printsetofset0(std::set<std::set<int>>& SetofSet) {
for (std::set<std::set<int>>::... | The elements, which the iterator points to, are constant. You can read it here in the Notes: Because both iterator and const_iterator are constant iterators (and may in fact be the same type), it is not possible to mutate the elements of the container through an iterator returned by any of these member functions.. But,... |
71,545,531 | 71,547,907 | Asio difference between work(), require() and make_work_guard() | Sorry to interrupt, I am a newbie in C++ and Asio...
I just come from here Asio difference between prefer, require and make_work_guard.
I am trying to make a "dummy work" for my io_context.
It is really confusing to a beginner who just wants to make a simple "UDP socket".
The ancient book from Packt and Youtube (https:... | As you state yourself, this is a full duplicate of the linked question.
The answer there answers every point you make here.
The ancient book from Packt and Youtube (https://www.youtube.com/watch?v=2hNdkYInj4g&t=2292s) tutorial tells me to use "work()"
I have bad experiences with Packt books on Asio¹. Regardless, ther... |
71,545,613 | 71,545,689 | sorting int from a text file in an ascending order | So i have a text file that looks like this:
5
4
9
-3
0
2
first int shows how many int their are that need to be ordered in ascending order so the output looks like this:
-3
0
2
4
9
Im trying to do it without any additional libraries and just use
#include <iostream>
#include <fstream>
So far my code reads the first i... | So, I tried your code and it worked after some minor changes, which only address the ability for compilation but not the actual approach to read the data. The code considers your restriction to only include iostream and fstream.
#include <iostream>
#include <fstream>
int main()
{
std::ifstream input("test.txt");
... |
71,545,705 | 71,554,084 | Find closest point from point outside polygon mesh to polygon mesh | I have a polygon mesh defining a valid inner region and a point outside of this polygon mesh. From this point i want to find the closest point on the surface on my polygon mesh.
I have no background in computational geometry and don't know the buzzwords. How can i achieve this using cgal or any other library in C++?
| You might have a look at the Location Functions in CGAL.
|
71,545,803 | 71,545,900 | Cryptographically hash multiple keys | How to hash using SHA1(or similar cryptogrphical functions) a class(or struct) which has multiple keys, e.g.,
struct Foo{
string name;
int age;
int score;
}
A naive approach is hash(has(name) + hash(age) + hash(score)), but hash collision is possible.
| Either hash the whole structure directly if it contains only POD (i.e. nothing allocated within and its sizeof is a constant): either you can use an union to get a proper byte array, or you use a cast to obtain a char* to provide to hash function.
If you have dynamic data inside your struct/class, you need to serialize... |
71,545,818 | 71,574,301 | Who is responsible for destructing the block scoped static Singleton instance? | I couldn't understand how the program below compiles successfully.
class SomeClass {
public: /** Singleton **/
static SomeClass &instance() {
static SomeClass singleInstance;
return singleInstance;
};
private:
SomeClass() = default;
SomeClass(const SomeClass&) = delete;
SomeClass ... | Shortly, during the construction, the compiler saves the destructor to a list of functions that will be called at the very end of the program. In the end, the list of functions, including the destructors, are called one by one and the safe destruction occurs.
Underlying Mechanism
The core of the mechanism is the exit(... |
71,545,978 | 71,546,170 | Fastest way for getting last index of item in vector in C++? | Let's say you have a vector of ints, unsorted and with multiple repeating items, like so:
vector<int> myVec{1, 0, 0, 0, 1, 1, 0, 1,0,0}
What is the fastest way to get the last index of 1 which is 8 for this example, other than looping through it from its end?
Would this be different if the vector would contain other i... | Use std::max_element and reverse iterators. And that is looping through the vector. If it is unsorted, there is no faster way.
|
71,546,411 | 71,546,466 | C++ compiler waring C26409 - avoid calling new and delete | Here is my code that I'm getting (Warning C26409 Avoid calling new and delete explicitly, use std::make_unique instead (r.11).) after doing a Visual Studio 2019 Code Analysis:
#include <windows.h>
#include <strsafe.h>
int main()
{
auto *sResult = new WCHAR[256];
StringCchPrintfW(sResult, 256, L"this is a %s", L... | The warning is somewhat confusing, because it assumes that you need some direct memory allocation. If fact, you don't:
#include <windows.h>
#include <strsafe.h>
#include <vector>
int main()
{
std::vector<WCHAR> sResult(256);
StringCchPrintfW(sResult.data(), sResult.size(), L"this is a %s", L"test");
}
or
int m... |
71,546,524 | 71,546,578 | double precision in C++, 308 digits or 15 digits? | If double can represent value up to 3.4E308 (308 zeros), then why do we say that double stores only 15 digits? What is point of saying "ten power of 308" ?
| We don't say that "double stores only 15 digits". We say that "double has 15 digits of precision". It means that the computed value of double, when printed as a base-10 sequence of digits, is accurate only up to those 15 digits.
double can represent 3.4E308. Yes, to print it you need more than 15 digits of precision. S... |
71,546,874 | 71,546,932 | How to print string in C++ using getline | Why this doesn't print the first word of sentence?
#include <iostream>
#include <string>
int main()
{
std::string sentence;
std::cout<<"Enter sentence: ";
std::cin>>sentence;
std::getline(std::cin,sentence);
std::cout<<sentence;
return 0;
}
If I enter
"This is text"
output would be
" is tex... | You dont need the first cin (std::cin>>sentence;), this will solve your problem
#include <iostream>
#include <string>
int main()
{
std::string sentence;
std::cout<<"Enter sentence: ";
std::getline(std::cin,sentence);
std::cout<<sentence;
return 0;
}
|
71,547,246 | 71,548,880 | Array of elements all end up with the same value despite being initialized with different values | #include<cstring>
#include<iostream>
using namespace std ;
class CSR
{
private:
char* csrName;
public:
void setName(char* n)//a setter for name
{
csrName = n;
}
char* getName()//a getter for employee’s name
{
return csrName;
}
};
int main()
{
CSR employees[7];
for(int... | What you are basically doing is that you are pointing your name variable towards the memory that is allocated to the parameter i.e (n) but the problem is that n gets destroyed every time the function stops its execution.
What you should do is point your name variable to a new memory location and run a loop so that it h... |
71,547,301 | 71,549,086 | How is date encoded/stored in MySQL? | I have to parse date from raw bytes I get from the database for my application on C++. I've found out that date in MySQL is 4 bytes and the last two are month and day respectively. But the first two bytes strangely encode the year, so if the date is 2002-08-30, the content will be 210, 15, 8, 31. If the date is 1996-12... | Based on what you provide, it seems to be N1 - 128 + N2 * 128.
|
71,547,513 | 71,547,645 | C++ vector data strucure, loop only half of elements | how to loop only half of the elements in C++ vector data structure using auto keyword
vector<string> InputFIle;
void iterateHalf(){
/* iterate only from begin to half of the size */
for (auto w = InputFIle.begin(); w != InputFIle.end(); w++) {
cout << *w << " : found " << endl;
... | You need to compute begin and end of your loop, i.e. first and last_exclusive.
#include <vector>
#include <numeric>
#include <iostream>
int main(){
std::vector<int> vec(16);
std::iota(vec.begin(), vec.end(), 0);
size_t first = 3;
size_t last_exclusive = 7;
//loop using indices
for(size_t i = ... |
71,547,561 | 71,547,694 | Incorrect timing in release mode | I'm trying to measure time of execution of the following code:
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <chrono>
uint64_t LCG(uint64_t LCG_state)
{
LCG_state = (LCG_state * 2862933555777941757 + 1422359891750319841);
return LCG_state;
}
int main()
{
auto begin = std::chrono::high_resol... | You can add an empty asm statement dependent on the variable w
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <chrono>
uint64_t LCG(uint64_t LCG_state)
{
LCG_state = (LCG_state * 2862933555777941757 + 1422359891750319841);
return LCG_state;
}
int main()
{
auto begin = std::chrono::high_resol... |
71,547,967 | 71,606,613 | HIP-Clang Inline Assembly | What is the Hip-Clang equivalent of this CUDA function?
__device__ __forceinline__ uint32_t add_cc(uint32_t a, uint32_t b)
{
uint32_t r;
asm volatile ("add.cc.u32 %0, %1, %2;" : "=r"(r) : "r"(a), "r"(b));
return r;
}
I'm porting a CUDA project to HIP-Clang that contains inline PTX assembly. The function is us... | It turns out the answer is hardware dependent. For my hardware for which the compiler defines __gfx1030__ the correct syntax is
asm volatile ("v_add_co_u32 %0, vcc_lo, %1, %2;" : "=v"(r) : "v"(a), "v"(b));
For earlier architechtures such as __gfx900__ replace vcc_lo with vcc
See the discussion on the Rocm Hip Github ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.