Take the 2-minute tour ×

I have a string:

1,a,2,b,3,c etc

I want to convert it to a pair vector:

std::vector<std::pair<int, QString> > myVector;

With 1 being the int and a being the string, 2 being the next int and b being the next string etc.


share|improve this question
What have you tried yourself? –  Nawaz Dec 12 '12 at 17:50
StackOverflow: doing your homework so you don't have to ! –  Minion91 Dec 12 '12 at 17:53
@Minion91 StackOverflow - doing your homework since 2008. –  user529758 Dec 12 '12 at 18:13
add comment

1 Answer

up vote 0 down vote accepted
int main()
  QString foo = "1,a,2,b,3,c";
  QStringList splits = foo.split(',');
  assert(splits.size() % 2 == 0); // check if even
  qDebug() << splits;

  std::vector< std::pair<int, QString> > vs;
  for(QStringList::const_iterator it = splits.begin(); 
      it != splits.end(); ++it) { 
    bool ok;
    QStringList::const_iterator tmp = it;

    vs.push_back(std::make_pair(tmp->toInt(&ok, 10), *it));
    assert(ok); // check if conversion worked
  return 0;
share|improve this answer
assert' was not declared in this scope –  panthro Dec 12 '12 at 18:06
deleting that line and testing also causes app to crash –  panthro Dec 12 '12 at 18:08
@user1013512 Oops. Include the header cassert. Also, fixed the crash. –  pmr Dec 12 '12 at 18:11
If parsing external input, do not use assert() that it is correct. (and do not crash in release mode). –  Frank Osterfeld Dec 12 '12 at 20:19
@FrankOsterfeld Perfectly right. I just used that to show which invariants the code is assuming. –  pmr Dec 12 '12 at 23:00
add comment

Your Answer


