Questions tagged [c++-standard-library]
In the C++ programming language, the C++ Standard Library is a collection of classes and functions, which may or may not be written in the core language, and are part of C++
955
questions
0
votes
2
answers
95
views
Best way to copy members from vector<Class> to vector<Member_Type> [closed]
I have a vector of complicated structs (here std::pair<int, int>). I now want to copy a member (say std::pair::first) into a new vector. Is there a better (more idiomatic) way than
std::vector&...
0
votes
2
answers
55
views
Select all elements but one with given index from std::vector?
Given a std::vector, for example of ints
std::vector vec{10, 20, 30}
how to select all items except of with given index, for example int i=1 resulting
std::vector {10, 30}?
1
vote
0
answers
46
views
Does move construction/assignment of any C++ standard library type have preconditions on the argument?
While writing this answer I realized that it's a bit unclear to me how is a move-assignment from a moved-from value to a moved-from value specified in C++ standard library.
As mentioned in that answer,...
2
votes
0
answers
32
views
Is a seek/sync required to switch between reading & writing an fstream?
When using a std::fstream you can read and write to the file. I'm wondering if there is any part of the C++ standard stating the requirements for switching between read & write operations.
What I ...
-2
votes
1
answer
58
views
Possible pointer invalidation using std::vectors (corrupted size vs. prev_size)
I am building a C++ app that needs to create an array of structures that must point to raw memory addresses (void * + size_t). In order to keep the values (std::vector<uint8_t>) on the stack I ...
5
votes
3
answers
127
views
How do I print a vector of chars using fmt?
I have a const std::vector<char> - not null-terminated. I want to print it using the fmt library, without making a copy of the vector.
I would have hoped that specifying the precision would ...
0
votes
3
answers
65
views
std::map with custom key
I would like to use a standard map with the following custom key:
struct ParserKey{
ParserKey(uint16_t compno,
uint8_t resno,
uint64_t precinctIndex) : compno_(compno),
...
-1
votes
0
answers
34
views
Can I tell NVCC to not-include the CUDA C++ "standard" library?
I'm compiling a program with CUDA's NVCC compiler frontend, version 11.7. In my program, I do not indicate I want to use CUDA's C++ standard-like library; however, I do write code in the cuda:: ...
1
vote
2
answers
46
views
ADL conflicts with a function in the current namespace
I have a function in my namespace. Its name is destroy. std namespace also contains a function with this name. When I call my function within my namespace, the call is ambiguous, because std::destroy ...
1
vote
1
answer
74
views
Why is std::reverse_iterator slower than a direct iterator?
I noticed that std::reverse_iterator always decrements a copy of internal iterator before dereference:
_GLIBCXX17_CONSTEXPR reference
operator*() const
{
_Iterator __tmp = current;
return *--...
1
vote
0
answers
29
views
Does range constructor of std::vector reserve required capacity before filling? [duplicate]
Which of 2 implementation is more close to the specification?
#1
template <typename Iter>
vector::vector(Iter first, Iter last)
{
reserve(std::distance(first, last));
for (auto it = ...
1
vote
1
answer
123
views
Why no std::as_const overload for pointer types
I just came across std::as_const and I was surprised by the output of the last line in the following snippet:
#include <cstdio>
#include <utility>
struct S {
void foo() { std::puts(&...
2
votes
4
answers
87
views
Calling C++ standard header (cstdint) from C file
I have an external library written in C++ such as
external.h
#ifndef OUTPUT_FROM_CPP_H
#define OUTPUT_FROM_CPP_H
#include <cstdint>
extern "C" uint8_t myCppFunction(uint8_t n);
#...
2
votes
1
answer
68
views
Why does C++ allows assigning an map iterator to a iterator of a map with different comparator?
I am confused why the following code compiles.
#include <iostream>
#include <map>
int main()
{
std::map<int,int, std::less<int>> m {{1,10}, {2,20}};
std::map<int,...
0
votes
2
answers
52
views
How to store a specific object's member function of known signature in a variable in C++?
What is the recommended way to store a reference to a non-static member function of a specific signature on some object instance? In a way where the calling code needs not to know of the object's ...
1
vote
1
answer
96
views
How to design a RAII wrapper to be used as a base class?
I had the idea to use std::unique_ptr as a base class for another class that manages some kind of external resource.
Let's assume my program needs to manage resources provided by a C-like library via ...
0
votes
0
answers
45
views
How to add functionality to existing C++ standard library functions [duplicate]
Visual Studio 2022 - Community Edition
I would like versions of the C++ fstream, ifsteam, and ofstream classes that operate identically to the standard versions except that some of the functions they ...
2
votes
2
answers
69
views
How does std::map's emplace() avoid premature construction?
I am confused about std::maps's implementation of emplace(). emplace() is a variadic template function with the following declaration:
template <class Args...>
iterator emplace( Args&&......
9
votes
2
answers
124
views
Permutation with repetition 'not changing the order of repetition items' with/without using std::next_permutation
I used to implement permutation with repetition by using std::next_permutation.
But I found that it(std::next_permutation) changes location of item which is repeated.
e.g.
[0] 0 1 2 2'
[1] 2' 0 1 2
[2]...
1
vote
1
answer
109
views
What is the design purpose of iterator_traits?
The C++ standard library has both iterator and iterator_traits templates defined. It seemed that in general, the iterator_traits just extracts properties that defined explicitly in iterator. If a ...
0
votes
0
answers
47
views
Understanding the C++ runtime environment - where are the UCRT function implementations?
Coming from a CPython side into C++ to refresh my CS schooling days and challenge myself to more C++
In doing so, I quickly found myself not understanding the layers of the C++ environment, name the ...
1
vote
1
answer
88
views
Why are standard library types accessible inside `std` despite being nested in implementation-defined namespaces?
I was browsing the implementation of the <optional> header for GCC 11.2 (which can be found here), and I noticed something I'm struggling to understand. Here's the header with (hopefully) only ...
0
votes
1
answer
46
views
Inbuilt / pre-defined comparator in cpp
Recently I learnt about comparators in cpp from STL.
I came to know we can use greater<>() as third argument for sorting instead of writing own logic.
Just curious to know how many inbuilt ...
1
vote
1
answer
83
views
How should I use a queue with an unordered_set as the underlying container
I have a data structure containing a set of std::pair<int, int>. There are two important properties I require for this data structure:
I can check set membership fast.
FIFO
So as a C++ ...
6
votes
1
answer
77
views
Unqualified lookup of operators in standard library templates
namespace N {
struct A {};
template<typename T>
constexpr bool operator<(const T&, const T&) { return true; }
}
constexpr bool operator<(const N::A&, const N::...
0
votes
2
answers
128
views
Is there a standard algorithm to check if container A is a superset of container B?
I was looking for a standard algorithm that, given two containers A and B, both with no duplicates, returns true if all the elements of A compares to true with an element of B. I used std::all_of with ...
3
votes
1
answer
89
views
why does std::sort not require the user to specify the templated types?
If I understand correctly, in the Standard Library, there exists this definition of std::sort():
template< class RandomIt >
constexpr void sort( RandomIt first, RandomIt last );
Suppose I have ...
0
votes
0
answers
58
views
Why can function pointers or lambda expressions be used instead of hash functions in templates of unordered containers?
The following examples are mentioned in 11.4 of <<C + + primer 5th>>:
size_t hasher(const sales_data &sd)
{
return hash<string>(0)(sd.isbn());
}
bool eqOp(const sales_data &...
2
votes
0
answers
61
views
Process of how libraries are added to C++'s STL?
What kind of process or vetting do libraries go through in order to be added to the STL? Do they have to meet some sort of standard imposed by the IEEE?
0
votes
1
answer
68
views
Why unique_ptr's Deleter need an argument of type unique_ptr<T, Deleter>::pointer?
I see the describtion about unique_ptr on cppreference, it says Deleter must be FunctionObject or lvalue reference to a FunctionObject or lvalue reference to function, callable with an argument of ...
23
votes
4
answers
1k
views
Create a vector of pairs from a single vector in C++
I have a single even-sized vector that I want to transform into a vector of pairs where each pair contains always two elements. I know that I can do this using simple loops but I was wondering if ...
4
votes
3
answers
100
views
Why does "L.insert(it--, i);" behave differently from "L.insert(it, i); it--;"?
These are two pieces of code that I ran under the C++11 standard. I expected the post-decrement of the iterator to produce the same effect, but these two pieces of code produce completely different ...
2
votes
2
answers
89
views
std::set elements' reference and pointer invariance after insertion
I came across a paragraph on cppreference that I don't think I understand:
No iterators or references are invalidated. [If the insertion is successful, pointers and references to the element obtained ...
0
votes
0
answers
46
views
Why doesn't `std::set::find` accept arguments which might be accepted by `Compare` type? [duplicate]
Disclamer: I know, that using std::map solves this problem, but it is not very clean to initialize.
The problem:
Imagine you have an array of large PODs which are rather expencive copy:
struct ...
3
votes
4
answers
231
views
Should a boolean predicate for std::condition_variable be volatile in C++?
I've been hearing so many conflicting answers, and now I don't know what to think.
The agreed-upon knowledge is that for sharing memory in a thread safe manner in C++, it's required to use volatile ...
1
vote
1
answer
80
views
Clean-up a timed-out future
I need to run a function with a timeout. If it didn't return within the given timeout, I need to discard it and fallback to a different method.
Following is a (greatly) simplified sample code to ...
2
votes
0
answers
64
views
How partial_sort is the same as "top N" elements of a list?
Learning about C++, I'm reading the standard algorithms and the reference page says the following on partial_sort:
partial_sort: sorts the first N elements of a range
But when I click on the name of ...
1
vote
1
answer
63
views
Is there a type in the standard for storing the begin- and end-iterators of a container?
My question is really simple: Is there a type in the standard whose purpose is to store the begin-terator and the end-iterator for a container?
I want to return both iterators from a single function. ...
1
vote
1
answer
74
views
C++ Variadic Templates for a General-Purpose and Fast Data Storage Container Builder
template< typename ... Args>
auto build_array(Args&&... args) -> std::array<typename std::common_
type<Args...>::type, sizeof...(args)>
{
using commonType = typename ...
0
votes
1
answer
130
views
Why is shared_ptr implemented using control block and not a static map?
To me, it looks like an implementation of std::shared_ptr which stores a reference counter in a static std::unordered_map<void*, struct Counters> would be much more simpler and also allow us to ...
6
votes
1
answer
131
views
Data member pointers as associative container keys
I am trying to create an std::set of pointers to data members. However, I can't find a method to sort or hash such pointers.
They can't be compared with operator<, they don't seem to be supported ...
1
vote
1
answer
90
views
C++ custom-written strncpy without padding all characters to null is it safe?
#include <iostream>
using namespace std;
struct Packet {
int a;
char b[17];
int c;
};
// char* dest has form char dest[n], src has length <= n and is null-terminated
// After ...
7
votes
2
answers
114
views
A clarification on the named requirements for containers
I am trying to get to grips with the specifics of the (C++20) standards requirements for container classes with a view to writing some container classes that are compatible with the standard library. ...
0
votes
0
answers
28
views
Formal guarantee that empty packaged_task isn't optimized out?
Below is a simplified version of my scheduler. A single thread processes packaged_tasks in the order they were enqueued.
execute schedules and waits for the completion of a task
schedules enqueues a ...
-1
votes
1
answer
113
views
Is ++map[element] well defined? [duplicate]
The square bracket operator in associative containers (map, unordered map) will insert an element in the map if it doesn't exist. In case the mapped value is an integer, like
std::map<std::string, ...
-1
votes
2
answers
188
views
Which exception safety guarantee do we have when copying a C++ container?
When any allocation of the new container or copying of the elements fails with an exception, will the current contents of the target container remain intact?
1
vote
1
answer
51
views
Why does std::poisson_distribution hang when passed a very large mean?
For example, the following code hangs, using my setup with a recent version of g++ and GNU libraries:
#include <random>
#include <cstdio>
std::default_random_engine rng;
int main(){
...
-1
votes
1
answer
67
views
how to probe corruption of, or changing answer from C++ std::filesystem::exists function
First: I do not know how to create an MVCE of this problem. I realize that is a big no no for this site, but I frankly there is a lot of expertise here and I don't know a better place to ask this ...
0
votes
0
answers
108
views
Storing pointers inside C++ standard library containers
I am implementing a project, in an enviroment where I am required to create hundreds of millions of std::string objects. I am storing these strings in multiple containers, therefore the count (copying)...
0
votes
1
answer
57
views
Understanding code duplication in template specializations of std::complex<T>
I was looking at the <complex> implementations of the C++ Standard Library. I noticed for all of the current GNU, LLVM and MSVC implementations, there is a huge amount of code duplication for ...