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,735,443 | 69,735,592 | How to understand auto deduce in for loop? | Initial value of i don't equal 5, output countless number.
int main() {
vector<int> nums = {1, 2, 1};
auto size = nums.size();
for(auto i = 2 * size - 1; i >= 0; i--) {
// do_stuff()
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
| Your issue stems from the fact that the type of i is unsigned, so i >= 0 is always true, rendering the loop infinite.
i is deduced to be of the same type as size, and size is deduced to be of type size_t because vector::size() returns size_t.
Because of above, and unsigned integer overflow, your loop is infinite. It pr... |
69,735,468 | 69,738,381 | How to parse date string which is formed by the CRT function? | I'm working on a Windows-driven C++ project now. And there is a function which composes a file names with date portion in them. It uses the wcsftime C runtime library function to format the date portion with the "%x" formating code. This code corresponds to the
%x Date representation for the locale
as the document... | One easy solution is to go forward : Generate a filename using the same pattern, but for a test date of 2001-02-03. The result will tell you the order of year,month and day.
|
69,735,621 | 69,736,404 | The best way to capture user input int with error handling loop | In my case, I have to make sure the user input is either 1 or 2, or 3.
Here's my code:
#include <iostream>
using namespace std;
void invalid_choice_prompt() {
string msg = "\nInvalid Command! Please try again.";
cout << msg << endl;
}
int ask_user_rps_check_input(int user_choice) {
if (user_choice == 1 |... | Reading from a stream using operator >> takes as many characters from the stream as the target type accepts; the rest will remain in the stream for subsequent reads. If the input has a format error (e.g. a leading alphabetical characters when an integer is expected), then an error-flag is set, too. This error-flag can ... |
69,735,729 | 69,770,526 | How to handle png generation with changing frame buffer size? | I am writing some unit tests for my drawing code. The steps include:
Setting up GLFW window and context
glfwMakeContextCurrent(window);
glfwGetWindowSize(window, &window_width, &window_height);
glfwGetFramebufferSize(window, &frame_buffer_width, &frame_buffer_height);
Perform drawings
beginFrame();
// perfo... | Relying on the default framebuffer for testing is wrong for multiple reasons. Other than the undetermined size, the bit-depth can change too, as well as some pixels may fail the pixel-ownership test.
Instead, for unit-testing purposes, refactor your rendering code so it can render to an off-screen FBO. Then you can cre... |
69,736,547 | 69,737,431 | Parse string and store it in struct c++ | we are given a txt file with :"6=3+3" and i want to parse the string in two like:"6=" and "3+3".
afterwards I want to save everything in a struct not array but struct. any idea?
| The below program shows how you can separate out the LHS(left hand side) and RHS(right hand side) and store it in a struct object.
#include <iostream>
#include <sstream>
#include<fstream>
struct Equation
{
std::string lhs, rhs;
};
int main() {
struct Equation equation1;//the lhs and rhs read from the file wi... |
69,736,764 | 69,745,754 | Strange uint8_t conversion with OpenCV | I have encountered a strange behavior from the Matrix class in OpenCV regarding the conversion float to uint8_t.
It seems that OpenCV with the Matrix class converts float to uint8_t by doing a ceil instead of just truncating the decimal.
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/imgcodecs.h... | The strange behavior is a result of cv::MatExpr and Lasy evaluation usage as described here.
The actual result equals:
round(round(121*0.5 + 105*0.25) + 82*0.25) = 108
The rounding is used because the element type is UINT8 (integer type).
The computation order is a result of the "Lasy evaluation" strategy.
Followin... |
69,737,101 | 69,737,611 | Dynamic array of Linear search funcion implementation | Need to implement a function
int* linearSearch(int* array, int num);
That gets a fixed size array of integers with a number and return an array with indices to the occurrences of the searched number.
For example array={3,4,5,3,6,8,7,8,3,5} & num=5 will return occArray={2,9}.
I've implemented it in c++ with a main func... | At very first I join in the std::vector recommendation in the question's comments (pass it as const reference to avoid unnecessary copy!), that solves all of your issues:
std::vector<size_t> linearSearch(std::vector<int> const& array, int value)
{
std::vector<size_t> occurrences;
// to prevent unnecessary re-al... |
69,737,159 | 69,737,301 | Stop visual studio 2019 from higlighting occurences of word under the cursor | Visual studio 2019 keeps on highlighting occurences of the word under my cursor in the current file:
Is there a way I can get rid of this?
| Tools -> Options -> Text Editor -> C/C++ -> Advanced -> References -> "Disable Reference Highlighting"
Set to true.
|
69,737,493 | 69,737,576 | Can I be sure a vector contains objects and not pointers to objects? | Can I be sure an std::vector (or, in general, any standard container) contains objects and not pointers to objects, no matter how complex the objects' class is, if it has constant size?
E.g.: in this simple case:
struct MyStruct { int a, b; };
std::vector<MyStruct> vs;
The resulting vector layout is:
[ ..., a1, b1, a2... | Since C++11 and onwards (C++03 nearly guarantees it), the data in a std::vector are contiguous with no gaps.
In particular if you have a pointer to an element in the std::vector, you can reach all other elements using pointer arithmetic.
Of course, pointer arithmetic works in sizeof units of your struct. And the struct... |
69,737,895 | 69,738,286 | Can std::stoi verify if the value of digit exceeds range of base? | I'm using std::stoi in following manner
int ConvertToInt( const std::string& aVal )
{
int lVal = std::stoi( aVal, nullptr, 0 );
return lVal;
}
Third argument in std::stoi was provided as 0 to convert automatically both DEC and HEX values.
I also use try-catch structure to catch std::invalid_argument, std::out_... | std::stoi parses the string until an invalid character is encountered, which is interpreted to be the end of the integer.
Is it possbile to catch digits, which are out of range and throw some exception ?
Yes. You can use the pos argument. After the conversion, the pointed integer will contain the index of the first u... |
69,737,959 | 69,738,663 | What should happen if one calls `std::exit` in a global object's destructor? | Consider the following code:
#include <cstdlib>
struct Foo {
~Foo() {
std::exit(0);
}
} foo;
int main() {
}
It compiles and terminates with zero successfully for me both on my Linux (GCC, Clang) and Windows (Visual Studio). However, when compiled with MSYS2's GCC on Windows (g++ (Rev2, Built by MSYS2 p... | [basic.start.main]/4:
If std::exit is called to end a program during the destruction of an object with static or thread storage duration, the program has undefined behavior.
|
69,738,294 | 69,738,711 | How to add all positive integers and get their average | Im a beginner at c++ and Im having a hard time, Im still a student, our professor ask us to input numbers(must input positive and negative) and print the sum of the positive integers and their average, example:
How many input? 5
input # 1 : 5
input # 2 : 3
input # 3 : -2
input # 4 : -4
input # 5 : 6
so the expected ou... | This is a fairly simple problem (almost everything isif one's basics are clear). The below program shows how you can do this. I have added some comments so that you can get an idea about what is happening.
#include <iostream>
#include <vector>
int main()
{
int numberOfInputs = 0;
std::cout<<"How many inputs?"<... |
69,738,619 | 69,738,735 | C++ static member function vs lambda overhead | I have some kind of templated base class
template<typename Derived>
class Base { };
and want to store derived instances of it in a list.
For that I use a using derived_handle = std::unique_ptr<void, void(*)(void*) alias.
When I now add a derived instance to the list i cound use a static member function as deleter
clas... | Time for a frame challenge!
You've made some bad decisions in that code. Most people who use unique_ptr, even in a polymorphic context, don't need custom deleters at all. The only reason you do, is because of your type erasure, and that's only there because Base<A> and Base<B> are unrelated types.
If you really need Ba... |
69,738,775 | 69,739,162 | What is a base class subobject? | I got that subobjects are member subobjects, base class subobjects and arrays.
I couldn't find anything that explicit explain the two first terms. In the following code for example:
struct A{int a;};
struct B{int b;};
struct C:public A,public B{};
I think that: int a is a member subobject of a possible, not yet instan... | Whenever a class inherits from another one it inherits, too, an instance of that class:
class A { };
class B : A { };
Then class B internally looks like:
class B
{
A a; // <- implicit base class sub-object, not visible to you
};
Note that in some cases there might be even be more than one A!
class A { };
class B ... |
69,738,996 | 69,739,049 | Assigning an array with std::fgetc() return | I am trying to store the first 4 chars of a .awv file using the std::fgetc function
This is what I have
FILE* WAVF = fopen(FName, "rb");
std::vector<std::string> ID;
ID[4];
for (int i = 0; i < 4; i++)
{
ID[i] = fgetc(WAVF);
}
I keep getting this error:
Exception thrown at 0x00007FF696431309 in ConsoleApplication3.... | Your program has undefined behavior!
Your vector ID is empty. By calling operator[] on an empty std::vector, invoking an undefined behavior. You got lucky that your program got crashed, saying "Access violation".
You need instead:
// create a vector of string and initialize 4 empty strings
std::vector<std::string> ID(4... |
69,739,017 | 69,752,035 | Label Text not changing on C++/CLR Windows Forms | I am working on a small C++/CLR Windows Forms Project on Visual Studios Community 2019 using .NET Framework 4.0 in which I have a Combo Box and a Label.
The code fragment below works fine:
private: System::Void comboBox1_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) {
label1->Text = "co... | I understand what you mean. To implement this function, you need to use a timer. You need to add a timer to your WinForm, and then set the Interval value to 1000 in the timer property. You need to use Start to start the timer, you could refer to my code.
this->timer1->Interval = 1000;
this->timer1->Tick += gcnew System... |
69,739,074 | 69,739,197 | Sorting structures inside vector by two criteria in alphabetical order | I have a following data structure (first string as "theme" of the school)
map<string, vector<School>> information;
And the school is:
struct School {
string name;
string location;
}
I have trouble printing my whole data structure out in alphabetical order (first theme, then location, then name). For an example.... | You can, you just need to add some condition in compare
bool compare(School const& lhs, School const& rhs)
{
if(lhs.location != rhs.location)
return lhs.location < rhs.location)
return lhs.name < rhs.name
}
Or you can overload the < operator like @ceorron did
|
69,739,319 | 69,740,163 | What is the difference between conanfile.py, conanfile.txt, conanprofile and settings.yml? | I have been trying to build Conan packages of my project for a week. I have been reading the documentation but there are many points that I'm still confused about.
There are 4 files that I think are very important:
conanfile.py
conanfile.txt
conan_profile
settings.yml
What is the purpose of each file? Where should ea... | The files are:
conanfile.py is a Conan "recipe". It declares dependencies, how to build a package from sources. The same recipe can be used to manage different configurations, like different platforms, compilers, build types, etc
conanfile.txt is a text simplification of conanfile.py, that can be used exclusively to c... |
69,739,846 | 69,740,040 | Sharing two strings of data between processes in C++ | I've come into a problem recently where I had two separate processes that need to share two strings. (A dynamic IP address and a key) I'm used to using ROS for this, where I would define a ROS msg with the two strings and send it from one to the other.
However we are trying to go as simple as possible with our applicat... | Shared memory should be fine (you even let Qt do all the hard work)
What you need is probably something like this, something that has a fixed size in your shared memory and still has enough space to hold your strings.
const std::size_t message_buf_size = 256;
struct data_t
{
char message[message_buf_size]; // copy ... |
69,739,930 | 69,741,150 | oat++ : put DTO in a list of DTOs | I'm trying to create a single big DTO from multiple DTOs, but I am having a lot of trouble to put my DTOs inside a list.
I have two DTOs :
class TypeDocDto : public oatpp::DTO
{
DTO_INIT(TypeDocDto, DTO)
DTO_FIELD(Int32, code);
DTO_FIELD(String, desciption);
};
class DocumentDto : public oatpp::DTO
{
D... | Found where the issue comes from.
It looks like oat++ is a bit finnicky when it comes about declaring the list object.
//*oatpp::List<oatpp::Object<TypeDocDto>> typeDocsList = {}* should become :
oatpp::List<oatpp::Object<TypeDocDto>> typeDocsList({});
That precise syntax seems to be required. After that, my code work... |
69,739,936 | 69,740,141 | C++: std::map and std::set aren't ordered if using custom class (not pointers) | This must be something incredibly stupid, yet I can't manage to make head or tail from it.
This is the testing code.
#include <iostream>
#include <vector>
#include <limits>
#include <random>
#include <map>
#include <set>
#include <stdlib.h>
class value_randomized
{
public:
double value;
long random;
value_r... | Your comparison function does not do strict weak ordering in accordance with the Compare requirement.
Fixing the existing code could be done like this:
inline bool operator<(const value_randomized& a, const value_randomized& b) {
if(a.value < b.value) return true;
if(b.value < a.value) return false;
return ... |
69,739,946 | 69,857,080 | C++ Best way to search/traverse/replace multiple tags with pugixml? | I have to replace in multiple template_xml multiple tags to build some web services requests. While with pugixml i can access a tag like this doc.child("tag1").child("tag2").etc i dont know if that is the best way since with multiple templates and multiple nested tags there would be multiple lines of code for each tag ... | Finally end up using this.
int get_tag_value(pugi::xml_document *xml_doc, std::string tag_name, std::string *tag_value)
{
std::string search_str = "//*/"; // xpath search for nested tags
search_str += tag_name;
pugi::xpath_node xpath_node = xml_doc->select_node(search_str.c_str()); // search node
if(... |
69,739,985 | 69,740,081 | What is the change I need to make to perform reverse of upper_bound? | I feel lower_bound in c++ stl is not the opposite of the upper_bound function. By default, in a non-decreasing array, if I use upper_bound and if the element is found and it is not the last element in the sorted array, then the next element > passed element is given and if the element is then last element or not found,... | std::lower_bound is what you want here. lower_bound returns the first element that is equal to or greater than the input provided. Knowing that, if you do
auto p = lower_bound(arr.begin (), arr.end (), 301);
then p will be at the 301, and subtracting 1 from it will give you element -550. So, you just need to check ... |
69,740,936 | 69,741,110 | How to get input and display 2 dimensional array in c++? | Code:-
#include <iostream>
using namespace std;
int main() {
int r,c,*p;
cout<<"Rows : ";
cin>>r;
cout<<"Columns : ";
cin>>c;
p=new int[r*c];
cout<<"\nEnter array elements :"<<endl;
int i,j,k;
for( i=0;i<r;i++){
... | The problem occurs at the end of your program, when you delete[] p. In the nested for-loop immediately preceding it, you are modifying p, thus, when attempting to delete[] p at the end, you get undefined behaviour.
Potential fixes include, when printing the array elements, access the pointer the same way you did in the... |
69,740,993 | 69,742,369 | Wrong handle while setting text to RichEdit control | I can set plain text to RichEdit control with SF_TEXT flag, but I cann't set RTF-text with SF_RTF flag.
Here is the creation of control:
LoadLibrary(TEXT("Riched20.dll"));
richEdit = CreateWindowEx(
0,
RICHEDIT_CLASS,
TEXT(""),
ES_MULTILINE | WS_VISIBLE | WS_CHILD | WS_BORDER | ... | RTF string should be "\\r \\p" etc. not "\r \p", or use raw string literal. The string should have compatible font. For example:
std::wstring wrtf = (LR"({\rtf1{\fonttbl\f0\fswiss Helvetica;}
Hello world Привет Ελληνικά 日本語 { \b bold \b } regular.\par})");
EM_STREAMIN/EM_STREAMOUT expect BYTE input/output.
When readi... |
69,741,034 | 69,741,492 | changing the declaration from char to int, made output different | In the code below, when I change the declaration of "isuit" from "char" to "int", the result differ.
I thought int and char is the same in the essense, so I cannot figure out why.
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int n, irank;
int cards[4][13] = {};
char isuit;... | Think of datatypes like icecream where you can choose size and flavor.
For flavors you have two choices, signed and unsigned.
For sizes, you have a range from 1 byte to 8 bytes. People refer to these as uint8_t, uint16_t, uint32_t.... etc.
So the difference between int and char is its 'size' and 'signed or unsignedness... |
69,741,268 | 69,741,314 | How do I initialize all elements of TrieNodes' children to null | I am trying to solve a Trie problem, for which I create a TrieNode class as below:
class TrieNode {
public:
bool isWord;
TrieNode* children[26];
TrieNode() {
isWord=false;
memset(children, NULL, sizeof(children)); //results in warning
};
};
This results in a warning:
warning: pa... | You might do:
class TrieNode
{
public:
bool isWord = false;
TrieNode* children[26]{};
TrieNode() = default;
};
|
69,741,940 | 69,742,342 | How do assign an overall variable for several inputs? | I am new to C++. I am facing a problem. I want to have 2 different dates (DD/MM/YYYY)
How do I assign an overall variable for the first chunk and another one for the 2nd chunk?
For example:
First Day of date: 2
First Month "" : 5
First year "" : 1985
-------
Second ""
second ""
second ""
--------
if both are the ... | The below program shows what you want:
#include <iostream>
struct Date
{
//always always initialize built in type in block/local scope
int date = 0, month = 0, year = 0; // by default public
//default constructor
Date() = default;
//lets overload operator= for comparing two Date ty... |
69,742,093 | 69,744,721 | Get the size of an std::array as r-value | Consider the following snippet of code:
#include<array>
#include<cstdint>
const std::array<int, 3> array{0, 1 , 2};
template<class string_type>
auto parse(string_type&& name) {
const auto s = std::uint8_t{array.size()};
return s;
}
While it compiles using gcc 9.3.0 (the default on Ubuntu 20.04), it f... | It appears to be a bug in:
gcc-10: https://godbolt.org/z/95TTv4z9P and
gcc-11: https://godbolt.org/z/KWMs4MMcK
It works fine in:
gcc-9: https://godbolt.org/z/YMqsMjr7x and
clang: https://godbolt.org/z/6Kq9nY7bo
To work around, you can do either this:
const auto s = static_cast<std::uint8_t>(array.size());
or this:... |
69,742,205 | 69,742,592 | Climbing Stairs DP Problem base case concept | Question:
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either jump 1 or 2 or 3 steps. In how many total number of ways can you jump to the top?
My Explanation:
Well I'm thinking of applying recursion because I can find the solution by solving similar subproblems and on that process... | because you request it to be 1 here (f(0) = 1)
for(int jumps=1;jumps<=k;jumps++){
if(n-jumps>=0){
total_num_of_ways += climbing_ladders_topDown(n-jumps,k,dp); // here
}
}
if you want f(0)=0, since recurse into f(0) doesn't really make sense anymore (there is no possible solution, just like f(-1))
the algo... |
69,742,326 | 69,742,744 | How can I merge three functions into one? | I have written next code but 3 functions must be replaced by 1 and I don't know how to.
The program creates 3 arrays but only 1 function must calculate negative numbers of each column and find the max element in each column. Here's the code:
#include <iostream>
#include <ctime>
#include <iomanip>
using namespace std;
i... | The parameters to calc() should be the number of rows and columns in the array. Then it should use these as the limits in the for loops.
Also, since you're calculating total negative and maximum for each column, you must reset these variables each time through the column loop.
#include <iostream>
#include <ctime>
#incl... |
69,742,511 | 69,742,634 | Pass-by-value and std::move vs forwarding reference | I encounter the pass by value and move idiom quite often:
struct Test
{
Test(std::string str_) : str{std::move(str_)} {}
std::string str;
};
But it seems to me that passing by either const reference or rvalue reference can save a copy in some situations. Something like:
struct Test1
{
Test1(std::string&& ... |
But it seems to me that passing by either const reference or rvalue reference can save a copy in some situations.
Indeed, but it requires more overloads (and even worst with several parameters).
Pass by value and move idiom has (at worst) one extra move. which is a good trade-off most of the time.
maybe using a forw... |
69,743,217 | 69,744,364 | What is a URI parameter for openLDAP that contains a schema, host, and port? | Specifically "the uri parameter may be a comma- or whitespace-separated list of URIs containing only the schema, the host, and the port fields" what does this mean?
Working with openLDAP in c.
| It is simple list of URIs. The list can be separated by whitespace or comma:
Example:
http://myhost.com:4567,http://myhost1.com:45,http://myhost2.com:34545
or
http://myhost.com:4567 http://myhost1.com:45 http://myhost2.com:34545
|
69,743,266 | 69,743,419 | Why does segmentation fault occur when pushing to pointer of vector | I am trying to learn c++ and wanted to write a simple program to explore the use of vectors and pointer. When I try to run a simple program that uses this function a segmentation fault occur. When I change
std::vector<string> *data;
to
std::vector<string> data;
and change the '->push_back()' to a '.push_back()' it ru... | Your code is generation a segmentation fault because you didn't allocate memory for your pointer.
int simple_tokenizer(string s)
{
std::stringstream ss(s);
std::vector<string> *data = new std::vector<string>();
string word;
//char delimiter = ',';
while(getline(ss,word, ',')) {
//cout << "ch... |
69,743,370 | 69,743,875 | Using Member Variable to set address.sin_port | I am currently sitting on a small C++ project, where I am trying to write a class that implements tcp sockets, when I came across the following:
ServerSocket::ServerSocket(uint16_t port_) {
struct sockaddr_in _address;
uint16_t _port = port_;
this->bindSocket();
}
int ServerSocket::bindSocket() {
_addr... | You have accidentally declared a variable, instead of initializing a member:
ServerSocket::ServerSocket(uint16_t port_) {
struct sockaddr_in _address; // This is redundant
uint16_t _port = port_; // <-- oopsie
this->bindSocket(); // redundant this
}
It should be:
ServerSocket::ServerSocket(uint16_t port_) ... |
69,743,601 | 69,743,621 | How to supress unused (void **arg) parameter? | In the function below I'm not using the parameter (void **arg). But since it's unused inside the function compiler gives me the error below:
error: unused parameter 'arg' [-Werror=unused-parameter]
bool decodeString(pb_istream_t *stream, const pb_field_t *field, void **arg)
I tried to suppress it by writing void(arg) ... | Use the parameter in an expression casted to void. Then the parameter is "used".
bool decodeString(pb_istream_t *stream, const pb_field_t *field, void **arg)
{
(void)arg;
...
}
|
69,743,701 | 69,745,287 | Undefined reference when compiling when using header and cpp file with templates in one of them | I've been trying to compile my project and I've encountered some problems when trying so. The error in particular that appears is:
[build] /usr/bin/ld: CMakeFiles/robot_control.dir/main.cpp.o:(.data.rel.ro._ZTVN4comm15cameraInterfaceE[_ZTVN4comm15cameraInterfaceE]+0x10): undefined reference to `comm::Interface<cv::Mat>... | You can't do this:
virtual void callbackMsg();
You have to actually provide the implementation for all template methods within the .h file.
|
69,744,386 | 69,744,525 | Single line lookup for nested std::map | Let’s say I have a std::map<int, std::map<int, std::string>>, is there a way to lookup directly for a string if you are given the two keys in a shorter statement?
Some syntax sugar for:
std::map<int, std::map<int, std::string>> nested_map;
nested_map[1][3] = "toto";
int key1 = 1;
int key2 = 3;
std::string val;
auto i... | Write a recursive variadic template function that would accept map by reference and keys as variadic template argument, and returnstd::optional of innermost value type. Or may return pointer with nullptr indication that it is not found.
|
69,744,680 | 69,744,788 | How to get type of template of class from its object in C++ | I have a custom class A and want to get the type of template from the code which initialized an object of A class to use it as a variable later. Is that possible?
#include <functional>
template<class T>
class A {
public:
A(){};
T data;
};
int main() {
A<int> a;
// How to get int as type?
// funct... | If you would like the template type to be discoverable by code, you can make a public using to expose it:
template<class T>
class A {
public:
using type = T; // <<<< add this (or something like it)
A(){};
T data;
};
Then in main
int main() { // side note: main() *must* return an int
using AI = A<int>... |
69,745,068 | 69,745,489 | Perform same operation on different class members without duplicate code | How do I perform the same operation on different class members without duplicating code?
I have a function which creates an object of type Farm, and then performs some kind of a calculation on its members (in this case, it prints the member variable, but the code I am currently working on is too complex to copy here in... | Perhaps a pointer-to-member is what you are looking for?
#include <iostream>
using namespace std;
class Farm
{
public:
int cows = 1;
int chickens = 2;
int mules = 3;
};
int Farm::* getMemberPtr(int whichMember)
{
switch (whichMember)
{
case 0: return &Farm::chickens;
case 1: return... |
69,745,132 | 69,745,168 | Why does my dynamic array work without being resized? | I'm working on dynamic arrays for my c++ course, but I'm confused about the behavior of my dynamic arrays. For example, if I run this code:
int* myDynamicArr = new int[3];
for (int i = 0; i < 10; i++)
{
myDynamicArr[i] = i + 1;
cout << myDynamicArr[i] << endl;
}
I would expect it to not work since I only dec... | C++ does not perform bounds checking on arrays. So when you read or write past the bounds of an array you trigger undefined behavior.
With undefined behavior, your program may crash, it may output strange results, or it may (as in your case) appear to work properly.
Just because it could crash doesn't mean it will.
|
69,745,393 | 69,745,684 | Using prefix with string literal split over multiple lines | I have a Unicode string literal, let's say like this.
const char8_t x[] = u8"aaa\nbbb©\nccc\n";
I would like to split it over multiple lines for readability.
Which of the notations below are correct and equivalent to the one above?
const char8_t x[] =
u8"aaa\n"
u8"bbb©\n"
u8"ccc\n";
const char... | From this cppreference page, it would appear that all your code snippets are equivalent and well-defined:
Concatenation
…
If one of the strings has an encoding prefix and the other doesn't, the one that doesn't will be considered to have the same encoding prefix as the other.
Or, from this Draft C++17 Standard:
5.13... |
69,745,880 | 69,746,358 | How can I multithread this code snippet in C++ with Eigen | I'm trying to implement a faster version of the following code fragment:
Eigen::VectorXd dTX = (( (XPSF.array() - x0).square() + (ZPSF.array() - z0).square() ).sqrt() + txShift)*fs/c + t0*fs;
Eigen::VectorXd Zsq = ZPSF.array().square();
Eigen::MatrixXd idxt(XPSF.size(),nc);
for (int i = 0; i < nc; i++) {
... | OpenMP
If your CPU has enough many cores and threads, usually a simple and quick first step is to invoke OpenMP by adding the pragma:
#pragma omp parallel for
for (int i = 0; i < nc; i++)
and compile with /openmp (cl) or -fopenmp (gcc) or just -ftree-parallelize-loops with gcc in order to auto unroll the loops.
This w... |
69,746,120 | 69,746,960 | How to make a variable in a struct variable that is not inputted but set based on previous variables' values | I am making a program which inputs fractions and puts them in order. I used struct to define a fraction type. I think I am making a type that initializing 2 variables(the numerator and the denominator of the fraction) and initializing the double type variable called value to a / b in this code:
struct fraction {
in... |
How can I make the variable without initializing it at the creation of the fraction?
One could just write a member function double value() calculating and returning the floating-point value of the fraction, but first there are some issues in the posted code that need to be addressed (and may actually solve OP's probl... |
69,746,186 | 69,746,265 | What is under the hood when a process receive a signal? | I am writing a program that needs to catch the ctrl-c event. And I learned that I can call signal function or sigaction function in signal.h to customize what to do when the process receives a SIGINT signal. But I am also curious what is the mechanism for such a signal listener. In other words, how can a process keep w... | The process doesn't "wait" for the signal. Calling sigaction() tells the operating system to force the process to take the specified action when the process receives the specified signal. When this happens, the process is interrupted and forced to call the registered handler.
|
69,746,542 | 70,724,996 | use of flow operators on objects | I have a problem using the operators for injecting input / output flows on objects (operator <<)
I was actually writing code to make "cout <<" run on my objects and display their values; this is the following code, specifically a function and a class method, located in the same class file:
-function code:
ostream &oper... | For this to work the function must be in the main file and not in the class file.
|
69,747,056 | 69,749,872 | how to have lua call a c++ function that returns multiple values to lua | my code (partial)
c++:
lua_register(L, "GetPosition", lua_GetPosition);
int lua_GetPosition(lua_State* L)
{
Entity e = static_cast<Entity>(lua_tointeger(L, 1));
TransformComponent* trans = TransformComponentPool.GetComponentByEntity(e);
if (trans != nullptr)
{
lua_pushnumber(L, trans->transform... | When Lua calls your function it will check its return value to find out how many values it should fetch from the stack. In your case that's 1. How else would Lua know how many of the pushed values you want to return?
From Lua 5.4 Reference Manual 4.6 Functions and Types:
In order to communicate properly with Lua, a C ... |
69,747,261 | 69,747,433 | Printing out specific length in vector array | I am trying to created a random password from the input text.
minimum length is 3. I found out that the first word which is The has size of 6 somehow.
Only the first word gives me weird size so far.
Eventually, I want to erase when words are less than 3 words.
I don't know why it returns size 6.
Please advise.
void se... | First, in your input text file, there is Byte Order Mark, so it affects the size of the word. Delete that.
In your setMinLength(std::vector<std::string> &words) function.
void setMinLength(std::vector<std::string> &words) {
for (int i = 0; i < words.size()-1; i++) {
if (words[i].size() == 6) {
... |
69,747,821 | 69,749,110 | Difference between returning a reference and modifying a class directly? | I have looked at the disassembly for the following code and found that the result is often the same (or very similar) for both test functions. I am wondering what the difference is between the two functions and if not, is there any history or reason for this existing?
struct test
{
int x;
test& testfuncti... | The functionality is almost the same, difference is the first enables the ability to chain methods. This design pattern is called fluent interface. It is supposed to provide an easy-readable, flowing interface, that often mimics a domain specific language. Using this pattern results in code that can be read nearly as h... |
69,747,956 | 69,748,200 | Error: there are no arguments to 'static_assert' that depend on a template parameter | When compiling this code, I get an error:
#include <cstdio>
template<size_t Index, typename T, size_t Length>
T& get(T (&arr)[Length]) {
static_assert(Index < Length, "Index out of bounds");
return arr[Index];
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int value = get<5>(arr);
printf("value = %d\... | This language feature became available in C++ only with C++11, see:
https://en.cppreference.com/w/cpp/language/static_assert
|
69,747,987 | 69,750,337 | gstreamer rtsp tee appsink can't emit signal new-sample | I am using gstreamer to play and slove the rtsp stream.
rtspsrc location=rtspt://admin:scut123456@192.168.1.64:554/Streaming/Channels/1 ! tee name=t ! queue ! decodebin ! videoconvert ! autovideosink t. ! queue ! rtph264depay ! h264parse ! appsink name=mysink
and i write in c++ code like this :
#include <gst/gst.h>
v... | By default appsink favors to use callbacks instead of signals for performance reasons (but I wouldn't consider your use case as a performance problem). For appsink to emit signals you will need to set the emit-signals property of the appsink to true. It defaults to false.
P.S. Apart from the above, I think you will nee... |
69,748,358 | 69,754,676 | Convert every column of an Eigen::Matrix to an std::vector? | Lets assume I have the following Eigen::Matrix:
Eigen::MatrixXf mat(3, 4);
mat << 1.1, 2, 3, 50,
2.2, 2, 3, 50,
3.1, 2, 3, 50;
Now how can I convert every column into an std::vector<float>
I tried an adaptation of this solution typecasting Eigen::VectorXd to std::vector:
std::vector<fl... | I think the most elegant Solution would be to use Eigen::Map. In your case you would do it like this:
Eigen::MatrixXf mat(3, 4);
mat << 1.1, 2, 3, 50,
2.2, 2, 3, 50,
3.1, 2, 3, 50;
std::vector<float> vec;
vec.resize(mat.rows());
for(int col=0; col<mat.cols(); col++){
Eigen::Map<... |
69,748,538 | 69,755,349 | cython use class wrapper pointer | I'm new to cython and maybe i'm missing some base info, so be patient. What i want to do is create a c++ object in python, modify it and return the object's pointer to a c++ function. Basically i have:
// headers.h
class A {
A();
void modifyA()
}
class B {
B();
void useA(A *a);
}
# headers.pxd
cdef ... | The "Cannot convert Python object to 'Something'" error in Cython generally means Cython is not detecting the type of an object/property, and thus believes it will be a Python object, only available at runtime.
That being said, you have to make sure Cython understands the type. In your particular case, you can choose b... |
69,748,653 | 69,748,721 | Two-Sum Problem using Binary Search Approach | The problem is as follows :-
Given an array of integers numbers and an integer target, return indices of the two numbers such that they add up to target.
Eg:-
Input: vec = [2,7,11,15], target = 9
Output: [0,1]
Output: Because vec[0] + vec[1] == 9, we return [0, 1].
I coded the problem using binary search approach and ... |
Why almost nobody has posted a binary search approach to this problem ?
To apply Binary Search algorithm, you need to sort the inputs, which would directly change the index of the array, that is no way convenient to use for this problem.
You may get correct result in your sample input cause your input array is sorted... |
69,748,663 | 69,748,806 | extract data using c++ and store in txt | I have a text file with the following data format
<create>
<way id="-200341" version="0" timestamp="1970-01-01T00:00:00Z">
<nd ref="-106862"/>
<nd ref="-106343"/>
<nd ref="-107240"/>
<nd ref="-107241"/>
<nd ref="-106863"/>
<nd ref="-106858"/>
<nd ref="-106866"/>
<nd ... | Use an xml parsing Library like plugixml, or you could build your own one.
There are many libraries which parses xml. Chose the one which fits your needs.
This may help you: What XML parser should I use in C++?
|
69,749,289 | 69,749,341 | Pass nested struct to a function | Hello I have the following code:
struct temperatures_t {
char lowTempSetting = 18;
char highTempSetting = 26;
char currentTemp = 23;
};
struct runningState_t {
struct temperatures_t temperatures;
};
struct runningState_t runningState;
void test(runningState_t *runningStateVar) {
runningStateVar->temperatur... | In test, the local argument variable runningState (not to be confused with the global variable of the same name) is a pointer to a structure object, so the arrow operator -> is the correct to use to access its members.
But runningState->temperatures is not a pointer, it's an actual structure object. Therefore you must ... |
69,749,405 | 69,783,912 | I want to know how to set normals with OBJ loader | Comment part of the presentation code ///// It is an internal code, but I do not know how to set the normal. I created an .obj loader with reference to the reference site, but the lighting is strange as shown in the reference image. What is the cause of this?
what I want to know
How to set the normal of obj file correc... | The cause was that I forgot how to specify the front and back of the polygon. The obj loader is correct.
https://imgur.com/a/6hTwnXP
add code
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
|
69,749,751 | 69,750,324 | cout permutation of three or more string | suppose I have been given strings "abc", "def" and "ghi", I want to generate all the possible combination of word generated by picking from these strings. for eg
for "abc", "def" and "ghi"
we should get
"adg","adh","adi","aeg","aeh","aei","afg","afh","afi",
"bdg","bdh","bdi","beg","beh","bei","bfg","bfh","bfi",
"cdg","... | This is one example where recursion allows simpler code: you just have to combine all characters from the first word with the permutations of the other ones.
In C++ it could be:
#include <vector>
#include <string>
using std::vector;
using std::string;
// using an array will allow to simply process the end of the arra... |
69,749,883 | 69,794,703 | Is an object a storage location or a value in C++? | In C++, is an object a storage location (container) or a value (content)?
With this sentence from [intro.object]/1, one can assume it is a value (bold emphasis mine):
An object occupies a region of storage in its period of construction ([class.cdtor]), throughout its lifetime, and in its period of destruction ([class.... | An object is an entity that has a type (a set of operations that can be performed on it) and occupies some allocated storage region with the proper size (given by the operator sizeof) and alignment (given by the operator alignof) for the type. The storage region has an address (given by the operator &) and holds a repr... |
69,749,928 | 69,838,774 | How to print a string from an object? | I tried the below code to write an object to a dat file:
#include<iostream>
#include<fstream>
#include<string>
#include<string.h>
using namespace std;
class Student
{ //data members
int adm;
string name;
public:
Student()
{
adm = 0;
name = "";
}
Student(int a,string n)
{
... | You cannot write complex data types to a file in binary mode. They have some additional variables and functions inside,which you do not know or see. Those data types have some internal state that or context dependent. So, you cannot store in binary and then reuse it somewhere else. That will never work.
The solution is... |
69,750,318 | 69,750,592 | How is it possible to unite multiple types in the operator function called by std::visit in C++? | I am using std::variant and std::visit to call operator functions. I have a lot of variants (which mostly inherit from one superclass), but most of the operator functions should return the same value. Is there a way to have one operator function, which is called everytime one of those child-classes is called (such as i... | Just use template operator():
template<class Node>
double operator()(Node* node) {
if constexpr (std::is_same_v<Node, addition_node>) {
// ...
} else if constexpr (std::is_same_v<Node, division_node>) {
// ...
}
}
|
69,750,787 | 69,750,993 | command to kill/stop the program if it runs more than a certain time limit | If I have a C++ code with an infinite loop inside i want a command that will kill the execution after certain time.
so i came up with something like this-
g++ -std=c++20 -DLOCAL_PROJECT solution.cpp -o solution.exe & solution.exe & timeout /t 0 & taskkill /im solution.exe /f
But the problem with this was that it would ... | Your main loop could exit after a certain time limit, if you're confident it is called regularly enough.
#include <chrono>
using namespace std::chrono_literals;
using Clock = std::chrono::system_clock;
int main()
{
auto timeLimit = Clock::now() + 1s;
while (Clock::now() < timeLimit) {
//...
}
}
A... |
69,751,041 | 69,754,246 | Is there a data structure like a C++ std set which also quickly returns the number of elements in a range? | In a C++ std::set (often implemented using red-black binary search trees), the elements are automatically sorted, and key lookups and deletions in arbitrary positions take time O(log n) [amortised, i.e. ignoring reallocations when the size gets too big for the current capacity].
In a sorted C++ std::vector, lookups are... | The data structure you're looking for is an Order Statistic Tree
It's typically implemented as a binary search tree in which each node additionally stores the size of its subtree.
Unfortunately, I'm pretty sure the STL doesn't provide one.
|
69,751,073 | 70,075,880 | PJSIP Received Remote Sip Header | Let's asssume we've two phone and Phone1 & Phone2 they're both has custom sip header
[Phone1] ----calling----> [Phone2] (This is onIncomingCallState for Phone2 and it can read header of Phone1)
[Phone1] <----answer---- [Phone2] (This is answer for Phone2 and it send it's header with it's CallOpParam)
[Phone1] <----OnCa... | Actually, it is already implemented in the pjsua2 level.
virtual void onCallState(OnCallStatePrm &prm){
..
prm.e.body.tsxState.src.rdata.wholeMsg //this is what i want exactly.
..
}
|
69,751,077 | 69,755,405 | UDP clients pool sending but not receiving | I am creating an udp client pool. The servers will be some other applications running in different computers, and they are suppoused to be alive from beginning. Using a configurable file (not important to problem in example so not included) one to several clients are created so they connect to those servers (1 to 1 rel... |
Q1: Where is the problem and how to fix it?
You don't really bind to any port, and then you have multiple sockets all receiving unbound udp packets. Likely they're simply competing and something gets lost in the confusion.
Q2: can std::vector be problematic
Yes. Use a std::deque (stable iterator/references as long ... |
69,751,176 | 69,751,233 | Why is copy assigment possible, if a class has only a (templated) move assignment operator? | I have stumbled over code today, that I don't understand. Please consider the following example:
#include <iostream>
#include <string>
class A
{
public:
template <class Type>
Type& operator=(Type&& theOther)
{
text = std::forward<Type>(theOther).text;
return *this;
}
private:
std:... |
Isn't the templated move assignment operator also a move assignment operator?
No, it's not considered as move assignment operator.
(emphasis mine)
A move assignment operator of class T is a non-template non-static member function with the name operator= that takes exactly one parameter of type T&&, const T&&, volati... |
69,752,007 | 69,752,436 | finding size of char array in C++ | I am getting the char array from user and trying to find the size of it and it is not working somehow.
My code looks like this:
int main()
{
char str[] ={}
cout << "Enter a characters ";
cin >> str;
int arrSize = sizeof(str);
cout << arrSize;
return 0;
}
When I define array like code below, it... | Arrays in C are static. After creating empty array of chars char str[] = {} you cannot fill it with arbitrary number of characters. Size of static C-style array is calculated in compile-time, as well as sizeof() operator. If you for some reason really have to use C-style string (array of chars), firstly allocate enough... |
69,752,545 | 69,752,802 | The fastest way to swap the two lowest bits in an unsigned int in C++ | Assume that I have:
unsigned int x = 883621;
which in binary is :
00000000000011010111101110100101
I need the fastest way to swap the two lowest bits:
00000000000011010111101110100110
Note: To clarify: If x is 7 (0b111), the output should be still 7.
| If you have few bytes of memory to spare, I would start with a lookup table:
constexpr unsigned int table[]={0b00,0b10,0b01,0b11};
unsigned int func(unsigned int x){
auto y = (x & (~0b11)) |( table[x&0b11]);
return y;
}
Quickbench -O3 of all the answers so far.
Quickbench -Ofast of all the answers so far.
(... |
69,753,109 | 69,753,221 | Why it is legal to compare scoped enumerations | Although scoped enumerations (enum class) cannot be implicitly converted to integral types, I still can compare them by < (on GCC 10.3).
#include <algorithm>
#include <iostream>
enum class Colours {
Red = 0,
Green = 1,
Blue = 2
};
int main() {
std::cout << (std::min(Colours::Blue, Colours::Red) < Colo... | This is described in comparison operators
Arithmetic comparison operators
If the operands have arithmetic or enumeration type (scoped or unscoped), usual arithmetic conversions are performed on both operands following the rules for arithmetic operators. The values are compared after conversions:
So in addition to ari... |
69,753,241 | 69,753,501 | Initialization of structs in C++ | I stumbled upon this weird struct implementation(from a big project) and I wanted to know the difference between this one and the normal one and why is it even implemented this way :
struct Sabc{
Sabc()
{
A = 0;
B = 0.0f;
}
int A;
float B;
}
Why not just :
struct Sabc{
Sabc()
{
... | Declare a struct with two members, explicitly overrides the default c'tor and initializes both members 0 and 0.0f:
struct Sabc{
Sabc()
{
A = 0;
B = 0.0f;
}
int A;
float B;
}
Declares a struct with no members, and explicitly override the default c'tor, within it declare two local variables,... |
69,754,300 | 69,754,571 | C++ read specific range of line from file | I have the following content in a file:
A(3#John Brook)
A(2#Allies Frank)
A(1#Lucas Feider)
I want to read the line piecemeal. First I want to read in order. For example, A than 3 than John Brook. Every thing is fine till 3 but how can I read John Brook without "#" and ")" as string.
I have a funciton and you can hav... | First organize your data into some structure.
struct Data {
char process;
char index;
std::string data;
};
Then implement function which is able to read single item. Read separators into temporary variables and then later check if they contain proper values.
Here is an example assuming each item is in sing... |
69,754,757 | 69,754,890 | Reduce number of template parameters | I would like to store some objects I know at compile-time in a class, and keep them constexpr, in order to proceed at compile-time. However, the way I'm storing these values in a struct seems unsatisfactory:
template <class T1, T1 _x1, class T2, T2 _x2>
struct A
{
constexpr static T1 x1 = _x1;
constexpr static T1... | In C++17 you can have the auto template parameters
template <auto _x1, auto _x2>
struct A
{
// Use _x1 and _x2 directly
}
|
69,754,776 | 69,755,215 | Do I always have to use a unique_ptr to express ownership? | Lets say I have a class A that owns an object of class B.
A is responsible for creating and deleting this object of B.
The ownership must not be transferred to another class.
The object of B will never be reinitialized after an object of A was created.
Normally, as far as I know, in modern C++ we would use a unique_p... | Ownership can be expressed in different ways.
Your B b of variant 2 is the simplest form of ownership. The instance of class A exclusively owns the object stored in b and the ownership cannot be transferred to another object or (member) variable.
std::unique_ptr<B> b expresses an unique - but transferable - ownership o... |
69,755,565 | 69,755,811 | What causes this vector subscript out of range Error? | I am currently mapping a Graph to a Minesweeper like grid, where every Block represents a node.
Here is my Graph class:
class Graph : public sf::Drawable
{
public:
Graph(uint32_t numNodesWidth, uint32_t numNodesHeight);
[[nodiscard]] std::vector<Node> & operator[](std::size_t i)... | There is no guarantee that bounds <= num_nodes * node_size. This is especially risky since there are integer divisions involved, which means that you are at the mercy of rounding.
You could shuffle code around until such a guarantee is present, but there's a better way.
If the checkGraphBounds() function operated on th... |
69,755,824 | 69,756,155 | Is there a way to have the same #define statement in different files that are included into the same file | So, I have a file structure like this:
FileA
FileB
FileC
FileA includes FileB and FileC
FileB has:
#define image(i, j, w) (image[ ((i)*(w)) + (j) ])
and FileC has:
#define image(i, j, h) (image[ ((j)*(h)) + (i) ])
on compilation i get:
warning: "image" redefined
note: this is the location of the previous def... |
Does this warning mean it changes the definition of the other file where it found it initially when compiling ?
The program is ill-formed. The language doesn't specify what happens in this case. If the compiler accepts an ill-formed program, then you must read the documentation of the compiler to find out what they d... |
69,756,133 | 69,756,601 | Why do I get integer output when I try to put "glfwSetErrorCallback" function in cout, which return non-integer value? | I'm learning GLFW 3.3, and, as it's said in functions description:
Returns the previously set callback, or NULL if no callback was set.
Source: [https://www.glfw.org/docs/3.3/group__init.html#gaff45816610d53f0b83656092a4034f40]
Now what I'm trying to do is to understand what kind of value it is. I tried to understand... | glfwSetErrorCallback returns a pointer wich is interpreted as an integer.
I think this post will help:How to print function pointers with cout?
|
69,756,347 | 69,756,499 | How the process of member look up occurs in C++? | I'm using the document number 4901, C++ Draft ISO 2021, specifically 6.5.2 (Member Name Lookup). I'm failing in understanding a lot of uses of the terms "member subobject" and "base class subobjects". I already asked about these terms in : What is a member sub object? and
What is a base class subobject
The Second quest... | From an ABI standpoint, there is very little distinction between B and C in the following:
struct A {
int x;
};
struct B : A {};
struct C {
A base;
};
Creating an object of type B or C both require creating an object of type A. In both cases, the instance of A belongs to the parent object. So in both cases they ... |
69,756,728 | 69,780,047 | Installing Azure SDK for C++ in a docker container | I would like to know how I may install azure c++ sdk in a docker container. I need it for a C++ services that downloads and processes files in Azure blob storage. Personally, I feel like the container will become too large and also the installation is kind of complex compare to the popular:
...
// Docker file
... | While researching, I came across this issue. Here, janbernloehr references to a library called azure-storage-cpplite which I searched and tried. Yes, it solves my problem!
First, it's easy to install locally or in a docker container. Dependencies: OpenSSL, libuuid and libcurl.
RUN git clone https://github.com/azure/azu... |
69,757,264 | 69,759,075 | Need help to setup RichEdit | I'm trying to set the following text in RichEdit (v2.0 I guess, as I use "Riched20.dll" library):
{\rtf1Привет!\par{ \i This } is super {\b text}.\par}
The first problem is wrong symbols instead of non-latin text Привет, the second problem is bold text section {\\b text}, which is rendered as non bold. Here is the sc... | Convert your text according the RTF format specification:
std::string rtf("{\\rtf1\\deff1{\\fonttbl{\\f0\\fcharset0 Times New Roman;}{\\f1\\fcharset0 Segoe UI;}}{\\lang1033{\\f1{\\ltrch\\u1055?\\u1088?\\u1080?\\u1074?\\u1077?\\u1090?!}\\li0\\ri0\\sa0\\sb0\\fi0\\ql\\par}{\\f1{\\i\\ltrch This }{\\ltrch is super }{\\b\\lt... |
69,757,433 | 69,757,619 | Trivial function gives unexpected return value | I have coded a function which receives a double matrix and looks backwards for a zero entry. If it finds one it changes the value of that entry to -2.0 and returns true. Otherwise it returns false.
Here's the code:
#include <iostream>
#include <vector>
bool remove1zero(std::vector<std::vector<double>> & matrix)
{
... | As mentioned in the comments, as size_t is an unsigned type, the j >= 0 and i >= 0 comparisons will always evaluate as "true" and, when either index reaches zero, the next value (after decrementing that zero value) will wrap around to the maximum value for the size_t type, causing undefined behaviour (out-of-bounds acc... |
69,757,457 | 69,759,109 | GDB: There is no member named "" | I'm writing some code that is calling some classes from a much larger project. Let's call the large project SampleProject. I have the static library of the SampleProject called libSampleProject.a. I cannot show the actual code, but I will provide some examples:
Let's say the SampleProject has a Class named SamplePointe... | Thanks to @G.M., for the suggestion. I believe the problem may have been that when I made the library, I compiled it without the debug flag, i.e the -g flag. I re-compiled the library, made the library out of the object files, and even changed the optimization level from -O3 to -O0 which will help with debugging.
I the... |
69,757,980 | 69,758,109 | C++ program behaviour different between optimizations | My question is in relation to this little code snippet:
typedef std::map<std::string, std::string> my_map_t;
std::string_view get_value_worse(const my_map_t& input_map, std::string_view value)
{
auto retrieved = input_map.find(value.data());
return retrieved != input_map.cend() ? retrieved->second : "";
}
std... | In the conditional expression, a temporary std::string object is constructed. Temporary object are usually constructed on the stack, although this is an implementation detail that is not important. The important thing is that the temporary object is destroyed at the end of the return statement, so the returned std::str... |
69,758,451 | 69,761,160 | Is it better to perform n additions of a floating-point number or one integer multiplication? | Consider the two cases below:
// Case 1
double val { initial_value };
for (int i { 0 }; i < n; ++i) {
val += step;
foo(val);
}
// Case 2
for (int i { 0 }; i < n; ++i) {
double val = initial_value + i * step;
foo(val);
}
where n is the number of steps, initial_value is some given value of type double, ... | Considering the comment by supercat (emphasis mine):
The point is that in many scenarios one might want a sequence of values that are uniformly spaced between specified start and end points. Using the second approach would yield values that are as uniformly spaced as possible between the start point and an end value t... |
69,759,030 | 70,057,958 | Why my trained model output is same for each random input? | I trained my model on the Python platform. after training, I faced up with same output for each random input. I solved this problem by deactivating BatchNorm layers with the model.eval() method. but when I tried to load my trained model in C++ with Pytorch C++ API, this problem showed up again, and model.eval() not hel... | I debugged multiple times my code and retry to save the model. Finally, I found the answer. I used a server to train my model, and for exporting the model to C++ I load my model weight in Python Shell into a model object. The problem is here, I should go to eval() before exporting the model for C++. C++ eval() does not... |
69,759,128 | 69,783,180 | How to resample audio? | What’s the best algorithm to change sample rate of PCM audio?
The input is often int16_t at 44.1 kHz but can also be 32kHz or other frequency. The output I need is 32-bit float at 48 kHz. I’m proficient in SIMD intrinsics and guaranteed to have either NEON or AVX, so an algorithm based on float math is OK.
Do I need to... | Yes, FFT is the requirement for good quality.
This web site has nice graphs of more than 100 pieces of software who are doing audio resampling. From a prior experience, I knew the professional software made by Steinberg is often doing the right things. The graphs on that web site agree, for Cubase 10 and Nuendo 11 thes... |
69,759,241 | 69,767,913 | Cmake adding a source folder to xcode without compiling the sources inside | I have a project that I am porting to cmake. The architecture of the sources is as follow:
src
|- FolderA
|-fileAa.cpp
|-fileAb.cpp
...
|- fileA.cpp
|-CMakeLists.txt
...
The file fileA.cpp is as follow:
#include <FolderA/fileAa.cpp>
#include <FolderA/fileAb.cpp>
//etc
My CMakeFiles.txt is as follo... | I solved my problem.
As mentioned here I need to use the files in a target for source_group to work. I used the trick that I mentionned of setting the sources of FolderA as header files and it worked perfectly:
file(GLOB COMPILED_SOURCES "*.cpp")
file(GLOB FOLDERA_SOURCES "FolderA/*.cpp")
set_source_files_properties($... |
69,760,485 | 69,760,651 | Problem compiling multithreading process regarding arguments | I'm trying to compile a program but it keeps coming up with errors; I have searched through the forum and I think it has to do with passing by reference, but I can't find where I went wrong.
Here is an extract of the code:
#include <iostream>
#include <thread>
using namespace std;
const int N = 512;
const int N_BUSC ... | The arguments you pass to coord do not match its signature.
void coord (VectInt v, bool& lectura, bool acabados[N_BUSC], int resultados[N_BUSC])
^^^^
It should be int if you want to pass an array of int to the function - or you should pass an array of bool to it instead:
bool acab... |
69,761,018 | 69,761,687 | Is clang wrongfully reporting ambiguity when mixing member and non-member binary operators? | Consider the following code, which mixes a member and a non-member operator|
template <typename T>
struct S
{
template <typename U>
void operator|(U)
{}
};
template <typename T>
void operator|(S<T>,int) {}
int main()
{
S<int>() | 42;
}
In Clang this code fails to compile stating that the call to ope... | I do believe clang is correct marking the call as ambiguous.
Converting the member to a free-standing function
First, the following snippet is NOT equal to the code you have posted w.r.t S<int>() | 42; call.
template <typename T>
struct S
{
};
template <typename T,typename U>
void operator|(S<T>,U)
{}
template <typen... |
69,761,806 | 69,761,905 | Listing permutations of two dice with one loop | As part of a coding challenge for myself, I've been trying to write code for simple problems in one line. Currently, I'm trying to print out all permutations possible for two dice. So far, I have a simple algorithm utilizing two for loops:
for(int i = 1; i <= 6; i++)
for(int j = i; j <= 6; j++)
printf("%d %... | The 2 loop version is the most readable. But since you asked, here are some 1 loop versions:
int main()
{
int n = 6;
for (int i = 1, j = 1; i < n; ++j)
{
if (j > n)
{
++i;
j = i;
}
std::cout << i << " " << j << '\n';
}
std::cout << std::flush... |
69,761,865 | 69,762,695 | How to pass an n-dim Eigen tensor to a function? | I'm looking to make a loss function that can take 2 tensors of any dimensions as parameters, but the dimensions of tensor 1 (t1) and tensor (t2) must match. Below are the templates that I tried to use to can pass the tensors into the function. I was thinking that T would be a type and N would model the number of indexe... | The error message is pointing out the type of the non-type template parameter is size_t, but in the declaration of t1 and t2 the value of that parameter is 3, which has type int. This mismatch makes the template argument deduction fail.
You can fix this by changing the type of the non-type template parameter to int
tem... |
69,762,069 | 69,762,093 | Understanding vector::assign example on cplusplus | I am confused about the following code and what it does:
first.assign (7,100); // 7 ints with a value of 100
std::vector<int>::iterator it;
it=first.begin()+1;
second.assign (it,first.end()-1); // the 5 central values of first
I don't understand the second.assign statement. I would assume it assigns 100 ... | In the example code
it = vec.begin()+1 meaning 2nd element
And
second.assign (it,first.end()-1);
^^^^^^^^^^
One past the last element.
it has skipped the first and last elements and hence you have 7-2=5 elements in the last assignment.
|
69,762,090 | 69,765,885 | CImg problem with color-interpolated 2D triangle | I feel like i'm missing something obvious here.
I am unable to get CImg's color-interpolated 2D triangle to work as expected.
To add to the confusion, it behaves differently on my system version of CImg (cimg_version 245) to the latest in Github (cimg_version 300).
If i draw a simple filled triangle, everything works a... | developer of CImg here.
It looks like a bug indeed. I'll try to fix it ASAP.
Thanks.
Do not hesitate to fill an issue on our github site (https://github.com/dtschump/CImg/issues) when you encounter such strange behaviors.
EDIT : This should be fixed now, with github.com/dtschump/CImg/issues/332. New pre-release have be... |
69,762,219 | 69,762,605 | Weird C++14 and C++17 difference in assignment operator | I have the following code:
#include <vector>
#include <iostream>
std::vector <int> a;
int append(){
a.emplace_back(0);
return 10;
}
int main(){
a = {0};
a[0] = append();
std::cout << a[0] << '\n';
return 0;
}
The function append() as a side effect increases the vector size by one. Because of how vectors... | This code is UB prior to C++17, as pointed out in comments, due to C++ evaluation order rules. The basic problem: Order of operations is not order of evaluation. Even something like x++ + x++ is UB.
In C++17, sequencing rules for assignments were changed:
In every simple assignment expression E1=E2 and every compound... |
69,762,366 | 69,763,590 | spdlog for C++; what(): Failed opening file ~/logs/log.txt for writing: No such file or directory | I am using spdlog to do some simple logging on a c++ program on a beaglebone, debian 10. I set up a rotating logger:
auto logger = spdlog::rotating_logger_mt("runtime_log", "~/logs/log.txt", max_size, max_files);
and this returns the error
terminate called after throwing an instance of spdlog::spdlog_ex'
what(): Fai... | ~ is special character in Bash shell, shorthand for home directory. The C++ program doesn't know about the ~. Usual way to get home directory would be to use std::getenv function like:
const char* home_dir = std::getenv("HOME");
auto log_path = std::string{home_dir} + "/logs/log.txt";
I suggest you also to make use of... |
69,762,931 | 69,765,372 | Can I take a reference of a pointer in C++? | I am passing in a reference to a pointer variable into a function. The function will do something and point the pointer variable to some object. Code:
int Foo(Obj* &ptr) {
// do something...
ptr = some_address;
return return_value;
}
int main() {
Obj* p = nullptr;
int ret = Foo(p);
// do something with ret... | I am not sure what your problem is, as the error code given does not match your code.
Your second example with int Foo(const Obj* &ptr) works exactly as intended, and compiles fine if you make DoSomethingconst.
To comment your three thoughts:
If you const things correctly, the error goes away.
I really, really dislike... |
69,762,937 | 69,762,998 | c++ function pointer assignment is safe? | Is this code thread safe?
static PFN_SOMEFUNC pfnSomeFunc = nullptr;
PFN_SOMEFUNC SomeFuncGetter();
void CalledFromManyThreads() {
if (pfnSomeFunc == nullptr)
pfnSomeFunc = SomeFuncGetter();
pfnSomeFunc();
}
This is not atomic pointer operation question. There are some special conditions.
SomeFuncG... | It doesn't look thread-safe, because the global variable can be modified by any thread without synchronization. Even an assignment is not guaranteed to be atomic.
What you could do is leverage a language feature that guarantees thread-safe atomic initialization by moving the static into your function (a very common so... |
69,763,620 | 69,763,816 | Do I need to offset a pointer when calling recv? | When using recv, I have always done something like this:
int len = 1000;
int n = 0;
char buf[1000];
while(n < len) {
n += recv(socket, buf + n, len - n, 0);
}
my logic being that if recv does not recieve the full data of len bytes, I should only receive the rest of the bytes (len - n) and should not overwrite the ... | Both of your examples are not accounting for the possibility of recv() failing. You need to check the return value for errors, eg:
char buf[1000];
int len = sizeof(buf);
int n = 0, ret;
while (n < len) {
ret = recv(socket, buf + n, len - n, 0);
if (ret <= 0) {
// error handling...
break;
}
n += ret;
}
... |
69,763,634 | 69,764,604 | Cython: How to import global variables from a module? | A module with global C variable:
# mymod.pyx (compiled to mymod.so)
cdef int myvar
How to access myvar from another file?
Scenario 1:
# myapp.pyx (import module only)
import mymod
print(mymod.myvar) # myvar is Python object, not int
Scenario 2:
# myapp.pyx (import variable directly)
from mymod import myvar # Error, n... | Turned out that cdef globals in a module must be in .pxd files.
For example:
# submod.pyx
some code...
# submod.pxd
cdef int myvar
# mod.pyx
cimport submod
print(submod.myvar)
# app.py
import mod
|
69,763,705 | 69,766,713 | How to render from world space into camera space? | I have 2 functions, the first function renders my objects in the world, while the second function was supposed to render my objects directly in the view frame of the camera like a UI ie. if the camera moves, the object appear to be stationary as it moves with the camera. However, my second function doesn't seem to work... | There are two approaches that I can think of. One is to directly pass the screen space coordinates to a vertex shader that does not apply a model, view or projection matrix to it. An example vertex shader would look like this:
#version ...
layout (location = 0) in vec3 aPos; // The vertex coords should be given in scr... |
69,764,971 | 69,769,941 | How can I compile lsqlite3 for Windows? | I have a C++ project developed in Ubuntu Linux. This C++ project is not written by me. Also, it runs under Ubuntu without any issues.
I am trying to compile the project under Windows 10 using GCC/G++ compiler and Visual Studio 2019 IDE. I am very close to success.
This project has the following lines in its CMakeList.t... | You are horribly mistaken. The linker flag -lsqlite3 means "link with libsqlite3.so. The correct library to compile is SQLite3. If you have trouble compiling it on Windows, there are quite a few questions about it on SO.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.