繁体   English   中英

integer 的 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的向量,因此您不能直接推送int

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM