没有用于调用错误的匹配函数.将字符串推送到向量中

No matching function for call to error. Pushing a string into a vector

本文关键字:字符串 向量 函数 用于 调用 错误      更新时间:2023-10-16

获取错误:

proj08-struct.cpp: 在构造函数 'Image::Image(std::__cxx11::string('中:PROJ08-struct.cpp:41:45:错误:调用"std::vector>::p ush_back(__gnu_cxx::__alloc_traits,char>::value_type&("没有匹配函数v_.push_back(line[j](;//add row to vector

 Image::Image (string f_name){
   ifstream objfile(f_name);//creates object file
   string line;//each line/row in matrix 
   vector<vector<long>> v_;
   istringstream iss;
   long height_,width_,max_val_;
    int counter=0;
   do{
       getline(objfile,line);//goes through each line in objfile
   }//of do
       while(line[0]!='#'||line[0]!='P');//skip when the line starts with a # or P
            if(counter==0){
                iss>>height_>>width_;
                counter++;
            }//of if
            else if(counter==1){
                iss>>max_val_;
                counter++;
            }//of first else if
            else if(counter<1){
                for(int i=0; i<height_; i++){//goes to next row
                    for(int j=0; j<width_; j++){//goes through row
                        v_.push_back(line[j]);//adds row to vector
                    counter++;
                    }//of inside for 
                }//outside for
            }//of second else if
    //cout<<v_<<endl;
}//of Image contructor

这应该读取 PGM (https://en.wikipedia.org/wiki/Netpbm_format#PGM_example( 并跳过以 # 或 P 开头的行,并将这些行后面的行读取为高度和宽度。然后读取下一行并将其存储为最大值。然后读取其余行并将所有这些数字(在最大值之后(推入向量(v_(。

你的向量声明是错误的。您正在声明vector<vector<long>> v_并尝试将字符串插入v_

vector<vector<long>> v_这意味着v_是一个向量,它在v_的每个索引位置都有vector<long>类型。如果要将逐行读取的文本存储在矢量中每行的 vector 索引位置,则需要将v_声明更改为 vector<string> v_

我希望这有所帮助。

是的,您需要找到一种方法将行中的每个字符推送到表示一行上数据的向量,然后将该向量推送到另一个向量,表示整个文件中的数据。这可以像这样实现:

Image::Image (string f_name)
{
    ifstream objfile(f_name);
    string line;
    vector<vector<long>> v_;
    strstream iss;
    long height_, width_;
    int counter = 0;
    while( !objfile.eof() ) {
        string line;
        string junk;
        getline(objfile, line);
        if (line[0] != '#' && line[0] != 'P' && line[0]) {
            strstream iss;
            iss << line;
            if (counter == 0)
            {
                iss >> width_ >> height_;
            }
            else {
                vector<long> l;
                for (int i = 0; i < line.size(); i++)
                {
                    long temp = 0;
                    iss >> temp;    
                    l.push_back(temp);
                }
                v_.push_back(l);
            }
            counter++;
        }
    }
    for (int i = 0; i < height_; i++)
    {
        for (int j = 0; j < width_; j++)
        {
            std::cout << v_.at(i).at(j) << " ";
        }
        std::cout << std::endl;
    }
}