push_back 整数不适用于我的字符串向量

push_back of an integer doesn't work on my vector of strings

我试图并行推回 ​​3 个向量,当我到达 push_back() 到字符串向量时,我收到此错误:

no instance of overloaded function "std::vector<_Ty, _Alloc>::push_back [with _Ty=std::string, _Alloc=std::allocator<std::string>]" matches the argument listC/C++(304)
ask3.cpp(38, 8): argument types are: (int)
ask3.cpp(38, 8): object type is: std::vector<std::string, std::allocator<std::string>>

这是我所在的代码块:

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;

int main()
{
    int length, count = 0, moviecount = 0, spacecount = 0;
    ;
    vector<int> status, price;
    vector<string> movies;
    string FileName, text, line, dummy;

    FileName = "MovieList.txt";

    ifstream InFile;
    InFile.open(FileName);
    while (!InFile.eof()) {
        getline(InFile, line);
        text += line + "\n";
    }
    cout << text;

    length = text.length();
    for (int i = 0; i <= length; i++) {
        if (text[i] == ' ') {
            spacecount++;
        }
    }
    if (spacecount == 2) {
        moviecount = 1;
    }
    else if (spacecount > 2) {
        int temp = spacecount;
        temp = temp - 2;
        temp = temp / 3;
        moviecount = 1 + temp;
    }
    movies.push_back(moviecount); //<-- problem line
    status.push_back(moviecount);
    price.push_back(moviecount);
}

moviesstring的向量,所以不能直接pushint

如果您使用的是 C++11 或更高版本,您可以使用 std::to_string 将整数转换为字符串。

另一种将整数转换为字符串的方法是使用 std::stringstream,如下所示:

std::stringstream ss;
ss << moviecount;
movies.push_back(ss.str());

这是因为您正试图将 int 值推送到向量 movies 中,该向量已初始化为存储 string 值。

不确定你想从这段代码中得到什么,但是 您可以像这样将向量的类型更改为 int :vector<int> movies 或在 push_back() 之前使用 std::to_string() 将 int 转换为字符串,如下所示: movies.push_back(std::to_string(moviecount))