Telegram Group & Telegram Channel
std::span — мощная альтернатива std::vector и std::array

Сегодня поговорим о std::span — контейнере, который делает работу с массивами и векторами в C++ более удобной и эффективной. 🚀

Проблема: Лишние копии данных
Представьте, что у нас есть функция, принимающая массив чисел:


void processArray(const std::vector<int>& arr) {
for (int num : arr) {
std::cout << num << " ";
}
std::cout << std::endl;
}


С одной стороны, передача const std::vector<int>& предотвращает копирование, но что, если у нас массив std::array или сырой int[]?
Придётся перегружать функцию или копировать данные в std::vector.

Решение: Используем std::span
std::span позволяет передавать любой диапазон (`std::vector`, std::array, сырые массивы) без копирования:


#include <iostream>
#include <span>
#include <vector>
#include <array>

void processArray(std::span<int> arr) {
for (int num : arr) {
std::cout << num << " ";
}
std::cout << std::endl;
}

int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
std::array<int, 5> arr = {6, 7, 8, 9, 10};
int rawArr[] = {11, 12, 13, 14, 15};

processArray(vec); // Работает
processArray(arr); // Работает
processArray(rawArr); // Работает
}


🚀 Преимущества std::span
Не копирует данные — передаётся как ссылка
Работает с любыми последовательностями
Гибкость — можно создавать срезы без копий

Пример использования .subspan(), чтобы передавать часть массива:


std::vector<int> vec = {1, 2, 3, 4, 5};
std::span<int> sp = vec;
processArray(sp.subspan(2)); // Выведет: 3 4 5


⚠️ Важно
- std::span не владеет данными. Убедитесь, что исходные данные живут дольше span.
- Не поддерживает автоматическое изменение размера, как std::vector.

📌 Итог
Если ваша функция принимает std::vector<int>&, std::array<int, N>&, int[] или даже std::initializer_list<int>, замените их на std::span<int>! Это сделает код более гибким и эффективным. 🔥

➡️ @cpp_geek



tg-me.com/cpp_geek/288
Create:
Last Update:

std::span — мощная альтернатива std::vector и std::array

Сегодня поговорим о std::span — контейнере, который делает работу с массивами и векторами в C++ более удобной и эффективной. 🚀

Проблема: Лишние копии данных
Представьте, что у нас есть функция, принимающая массив чисел:


void processArray(const std::vector<int>& arr) {
for (int num : arr) {
std::cout << num << " ";
}
std::cout << std::endl;
}


С одной стороны, передача const std::vector<int>& предотвращает копирование, но что, если у нас массив std::array или сырой int[]?
Придётся перегружать функцию или копировать данные в std::vector.

Решение: Используем std::span
std::span позволяет передавать любой диапазон (`std::vector`, std::array, сырые массивы) без копирования:


#include <iostream>
#include <span>
#include <vector>
#include <array>

void processArray(std::span<int> arr) {
for (int num : arr) {
std::cout << num << " ";
}
std::cout << std::endl;
}

int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
std::array<int, 5> arr = {6, 7, 8, 9, 10};
int rawArr[] = {11, 12, 13, 14, 15};

processArray(vec); // Работает
processArray(arr); // Работает
processArray(rawArr); // Работает
}


🚀 Преимущества std::span
Не копирует данные — передаётся как ссылка
Работает с любыми последовательностями
Гибкость — можно создавать срезы без копий

Пример использования .subspan(), чтобы передавать часть массива:


std::vector<int> vec = {1, 2, 3, 4, 5};
std::span<int> sp = vec;
processArray(sp.subspan(2)); // Выведет: 3 4 5


⚠️ Важно
- std::span не владеет данными. Убедитесь, что исходные данные живут дольше span.
- Не поддерживает автоматическое изменение размера, как std::vector.

📌 Итог
Если ваша функция принимает std::vector<int>&, std::array<int, N>&, int[] или даже std::initializer_list<int>, замените их на std::span<int>! Это сделает код более гибким и эффективным. 🔥

➡️ @cpp_geek

BY C++ geek


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/cpp_geek/288

View MORE
Open in Telegram


telegram Telegram | DID YOU KNOW?

Date: |

Export WhatsApp stickers to Telegram on iPhone

You can’t. What you can do, though, is use WhatsApp’s and Telegram’s web platforms to transfer stickers. It’s easy, but might take a while.Open WhatsApp in your browser, find a sticker you like in a chat, and right-click on it to save it as an image. The file won’t be a picture, though—it’s a webpage and will have a .webp extension. Don’t be scared, this is the way. Repeat this step to save as many stickers as you want.Then, open Telegram in your browser and go into your Saved messages chat. Just as you’d share a file with a friend, click the Share file button on the bottom left of the chat window (it looks like a dog-eared paper), and select the .webp files you downloaded. Click Open and you’ll see your stickers in your Saved messages chat. This is now your sticker depository. To use them, forward them as you would a message from one chat to the other: by clicking or long-pressing on the sticker, and then choosing Forward.

How to Invest in Bitcoin?

Like a stock, you can buy and hold Bitcoin as an investment. You can even now do so in special retirement accounts called Bitcoin IRAs. No matter where you choose to hold your Bitcoin, people’s philosophies on how to invest it vary: Some buy and hold long term, some buy and aim to sell after a price rally, and others bet on its price decreasing. Bitcoin’s price over time has experienced big price swings, going as low as $5,165 and as high as $28,990 in 2020 alone. “I think in some places, people might be using Bitcoin to pay for things, but the truth is that it’s an asset that looks like it’s going to be increasing in value relatively quickly for some time,” Marquez says. “So why would you sell something that’s going to be worth so much more next year than it is today? The majority of people that hold it are long-term investors.”

telegram from nl


Telegram C++ geek
FROM USA