user2754070
user2754070

Reputation: 507

PushBack (push_back()) elements of QStringList to vector<string>

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();
}

Upvotes: 4

Views: 9975

Answers (2)

drescherjm
drescherjm

Reputation: 10857

I would do this:

foreach( QString str, list) {
  vec.push_back(str.toStdString());
}

Upvotes: 4

Hughie Coles
Hughie Coles

Reputation: 179

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?

Upvotes: 2

Related Questions