Вопрос

I ve got a string which is white space seperated integer numbers and I want to convert it in array of vector of intergers. My string is like the:

6 9 17 5 3 4 10 12 7 3 5 10 6 5 0 10 10 10 13 3 6 10 2 11 33 9 14 7 0 8 7 6 38 2 23 8 4 52 7 3 19 12 2 22 3 6 3 1 2 1 5 17 13 5 1 6 0 12 6 9 15 2 22 0 27 2 3 4 7 2 8 2 8 6 11 22 4 9 4 1 1 2 2 16 8 3 1 8 0 4 4 2 1 10 24 15 8 2 6 9

How is it possible to convert it to array/vector??

Это было полезно?

Решение

Use std::istream_iterator. Example:

std::vector<int> vector(std::istream_iterator<int>(std::cin), std::istream_iterator<int>());

Or, with std::string:

std::string s = "6 9 17 5 3 4 10 12 7 3 5 10 6 5 0 10 10 10 13 3 6 10 2 11 33 9 14 7 0 8 7 6 38 2 23 8 4 52 7 3 19 12 2 22 3 6 3 1 2 1 5 17 13 5 1 6 0 12 6 9 15 2 22 0 27 2 3 4 7 2 8 2 8 6 11 22 4 9 4 1 1 2 2 16 8 3 1 8 0 4 4 2 1 10 24 15 8 2 6 9";
std::stringstream ss(s);
std::vector<int> vec((std::istream_iterator<int>(ss)), (std::istream_iterator<int>()));

Другие советы

This following code does what you need:

std::istringstream iss(my_string);
std::vector<int> v((std::istream_iterator<int>(iss)),
                   (std::istream_iterator<int>()));

Here is a ready to use example with all required headers

#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <iterator>

int main()
{
    std::string s = "6 9 17 5 3 4 10 12 7 3 5 10 6 5 0 10 10 10 13 3 6 10 2 11 33 9 14 7 0 8 7 6 38 2 23 8 4 52 ";
    std::istringstream is( s );

    std::vector<int> v;

    std::transform( std::istream_iterator<std::string>( is ),
                    std::istream_iterator<std::string>(),
                    std::back_inserter( v ),
                    []( const std::string &s ) { return ( std::stoi( s ) ); } );


    for ( int x : v ) std::cout << x << ' ';
    std::cout << std::endl;

    return 0;
}

Or indeed instead of algorithm std::transform you can use simply the constructor of class std::vector that accepts two iterators as for example

std::vector<int> v( ( std::istream_iterator<int>( is ) ),
                    std::istream_iterator<int>() );

Or

std::vector<int> v( { std::istream_iterator<int>( is ),
                      std::istream_iterator<int>() } );

I see some older and smarter way of doing that:

#include <stdlib.h>     /* strtol */

    char *numbers = "6 9 17 5 3 4 10 12 7 3 5 10 6 5 0 10 10 10 13 3 6 10 2 11 33 9 14 7 0 8 7 6 38 2 23 8 4 52 7 3 19 12 2 22 3 6 3 1 2 1 5 17 13 5 1 6 0 12 6 9 15 2 22 0 27 2 3 4 7 2 8 2 8 6 11 22 4 9 4 1 1 2 2 16 8 3 1 8 0 4 4 2 1 10 24 15 8 2 6 9"
    long table[512];
    char *pt;
    int i=0;

    pt = numbers;

    while(pt != NULL)
    table[i++] = strtol (pt,&pt,10);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top