I am working on using parts of an array of chars in C++ and was trying to figure out the easiest way to do this. I know in Python you can simply do something like str[1:] which will give you the entire array except the first position and was wondering if C++ has any analogs to this or if not, what would be the easiest way to implement this.
            Asked
            
        
        
            Active
            
        
            Viewed 206 times
        
    1
            
            
        - 
                    3You can get something similar, though much more verbose, with iterators and ranges. For example the range `std::next(std::begin(str), 1)` to `std::end(str)` would be `str` except for the first element. – François Andrieux Sep 17 '18 at 15:25
- 
                    2In most languages that's expressed via named substring operations, names like `substr`, `left`, `mid`, `right`. The first from C++, the latter three from some Basic. For efficiency look up `std::string_view`. – Cheers and hth. - Alf Sep 17 '18 at 15:25
- 
                    You could use [`std::string::substr(1)`](https://en.cppreference.com/w/cpp/string/basic_string/substr). – Thomas Matthews Sep 17 '18 at 15:57
- 
                    in C++17 there is `std::strigng_view` (or boost `strigng_view` for older C++ versions). There is also something like `std::valarray` where `slice` functionality is very similar to pythons operator `[]`. – Marek R Sep 17 '18 at 15:59
- 
                    1Note: this feature in Python is called slicing. Just thought I'd give you this terminology so you can do more effective searches in the future. – Code-Apprentice Sep 17 '18 at 16:00
1 Answers
1
            
            
        For right now you can try using as header-only Boost.Range (sliced, etc.) library (+ there is a chapter about it at theboostcpplibraries.com).
Example from the library documentation:
#include <boost/range/adaptor/sliced.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <boost/assign.hpp>
#include <iterator>
#include <iostream>
#include <vector>
int main(int argc, const char* argv[])
{
    using namespace boost::adaptors;
    using namespace boost::assign;
    std::vector<int> input;
    input += 1,2,3,4,5,6,7,8,9;
    boost::copy(
        input | sliced(2, 5),
        std::ostream_iterator<int>(std::cout, ","));
    return 0;
}
In future there will probably be something called span<T> in the standard (discussion here).
 
    
    
        bobah
        
- 18,364
- 2
- 37
- 70
