3

How can I access elements of QStringList in a vector<string> type. push_back doesn't work. inserting too needs another vector type only.

#include <QtCore/QCoreApplication>
#include <QDebug>
#include <QStringList>
#include <vector>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
        QCoreApplication a(argc, argv);
        std::vector<string> vec;
        QString winter = "December, January, February";
        QString spring = "March, April, May";
        QString summer = "June, July, August";
        QString fall = "September, October, November";
        QStringList list;
        list << winter;
        list += spring;
        list.append(summer);
        list << fall;
        qDebug() << "The Spring months are: " << list[1] ;
        qDebug() << list.size();

        for(int i=0;i<list.size();i++)
        {
        //vec.push_back(list[i]);
        }
        exit(0);
        return a.exec();
}
user2754070
  • 489
  • 1
  • 7
  • 16

2 Answers2

3

I would do this:

foreach( QString str, list) {
  vec.push_back(str.toStdString());
}
drescherjm
  • 8,907
  • 5
  • 42
  • 60
2

QString isn't std::string. You can't add it directly to a vector of std::string. You have to convert it to a std::string first.

Also, a QString is a UTF-16 string, and is incompatable with a UTF-8 std::string, so can use std::wstring like this

for(int i=0;i<list.size();i++)
{
   vec.push_back(list[i].constData());
}

Or a std::string like this:

for(int i=0;i<list.size();i++)
{
   vec.push_back(list[i].toUtf8().constData());
}

Hope this works/helps

Source:

How to convert QString to std::string?

Community
  • 1
  • 1
Hughie Coles
  • 179
  • 1
  • 10