Vector to array

Could somebody show me how to change this tidbit of vector code to a dynamic array?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    vector<char> storage;
    
    for (int i=0; i < pairVector.size(); i++)
    {
        //std::cout << std::get<0>(pairVector[i]) << " " << std::get<1>(pairVector[i])<< std::endl;
        
        for(int j=0; j < std::get<0>(pairVector[i]); j++)
        {
            storage.push_back(std::get<1>(pairVector[i]));
        }
    }
    
    
    cout << "The dynamic array contains ...:\n";
    cout << "Index    Value" << endl;
    cout << "-----    -----" << endl;
    
    for (int i=0; i < storage.size(); i++)
    {
        cout << i << setw(9) << storage[i] << std::endl;
    }
    
bump
std::vector<> is an optimised, resizeable dynamic array.
There is no good reason to change it, and there are a few good reasons for not changing it.

However, if you must change it to a dynamic array, use a smart pointer:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <vector>
#include <tuple>
#include <memory>
#include <iomanip>

int main()
{
    std::vector< std::pair<int,char> > pairVector { {0,'a'}, {1,'b'}, {2,'c'}, {3,'d'}, {4,'e'} };

    // http://en.cppreference.com/w/cpp/memory/unique_ptr
    // http://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique
    auto storage = std::make_unique< char[] >( pairVector.size() ) ; // C++14
    // std::unique_ptr< char[] > storage( new char( pairVector.size() ) ) ;

    for( std::size_t i=0; i < pairVector.size(); ++i ) storage[i] = std::get<1>( pairVector[i] ) ;
    // or: for( std::size_t i=0; i < pairVector.size(); ++i ) storage[i] = pairVector[i].second ;

    std::cout << "The dynamic array contains ...:\n";
    std::cout << "Index    Value\n" ; // << endl;
    std::cout << "-----    -----\n" ; // << endl;

    for( std::size_t i=0; i < pairVector.size(); ++i )
        std::cout << i << std::setw(9) << storage[i] << '\n' ;
}

http://coliru.stacked-crooked.com/a/c6ce1e4ef4a13768
Topic archived. No new replies allowed.