-1

I need to get the 2nd split of a string, in the case below "two".

I tried running this code:

#include <boost/algorithm/string.hpp>
#include <iostream>
#include <list>
#include <string>

int main()
{
    std::string s = "one,two,three,four";
    std::list<std::string> results;

    boost::split(results, s, boost::is_any_of(","));

    std::cout << results[1] << "";
}

I get this error:

error: no match for 'operator[]'

How can I solve it?

asu
  • 1,875
  • 17
  • 27
newquest
  • 13
  • 6

2 Answers2

0

cout << results[1] << "";

This doesn't work because results is a std::list. std::list does not provide the [] operator. In your usecase, you should use a std::vector instead.

asu
  • 1,875
  • 17
  • 27
0

The other answers given shows the reason for the error in that you are using a std::list, which in turn does not provide an operator []. The easiest thing is to just use std::vector.

However, if you really wanted to use a std::list, the way you get to a certain position in the list is to advance to that position. Thus there is a std::advance function that does this, in addition to std::next, which is merely a wrapper for std::advance.

So here is a solution using std::list and std::advance.

#include <boost/algorithm/string.hpp>
#include <iostream>
#include <list>
#include <string>
#include <iterator>

int main()
{
    std::string s = "one,two,three,four";
    std::list<std::string> results;

    boost::split(results, s, boost::is_any_of(","));
    auto iter = results.begin();
    std::advance(iter, 1);
    std::cout << *iter << "";
}

Live Example


Now using std::next:

#include <boost/algorithm/string.hpp>
#include <iostream>
#include <list>
#include <string>
#include <iterator>

int main()
{
    std::string s = "one,two,three,four";
    std::list<std::string> results;

    boost::split(results, s, boost::is_any_of(","));
    auto iter = std::next(results.begin(), 1);
    std::cout << *iter << "";
}

Live Example

PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45