开发者

converting strings from a map to a 2d vector character-wise

开发者 https://www.devze.com 2023-03-14 10:08 出处:网络
I have an array of strings which need to be taken into a map. Since the array size is variable, I need a 2d vector to obtain the string character-wise. i need both formats of storage for operations i

I have an array of strings which need to be taken into a map. Since the array size is variable, I need a 2d vector to obtain the string character-wise. i need both formats of storage for operations i perform on them. Here's my attemp..gives errors in (EDIT:)run time.

#include "stdafx.h"
#include<iostream>
#include<string>
#include<fstream>
#include<map>
#include<vector>
#include<algorithm>
#include<iterator>

#define rep(i,a,b) for(int i=(a);i<=(b);i++)

using namespace std;
std::map<int,string>col;
std::map<int,string>row;
std::map<int,string>::iterator p;     
std::map<i开发者_Python百科nt,string>d1; 
std::map<int,string>d2;

int main()
{   
    int i=0,r=0;
    string s;

    ifstream ip; 
    ip.open("a.in"); 

    ofstream op; 
    op.open("a_out.in");

    ip>>s;

    const int c= s.length();
    ip.seekg(0,std::ios::beg);

    do { 
        ip>>s;row.insert(make_pair(r,s));
        r++;
    }while(s.length()==c);

    p=row.find(--r);
    row.erase(p);
    p = row.begin();

    while(p!=row.end())
    {
        cout<<(p->first)<<","<<(p->second)<<"\n";
        p++;
    }

    vector<vector<char>>matrix(r,vector<char>(c)); 

    rep(i,0,r){
        int k=0;rep(j,0,c)(p->second).copy(&matrix[i][j],1,k++);
    }

    rep(i,0,r)
        rep(j,0,c)
            cout<<matrix[i][j];
return 0;
}


It looks like the problem occurs after you print out the map, before you copy the strings into the vector. You need two things:

while(p!=row.end())
{
    cout<<(p->first)<<","<<(p->second)<<"\n";
    p++;
}
p = row.begin();   // Must reset iterator!

vector<vector<char>>matrix(r,vector<char>(c));
rep(i,0,r){
    int k=0;
    rep(j,0,c)(p->second).copy(&matrix[i][j],1,k++);
    ++p; // Must advance the iterator.
}

That should fix the map/set iterator not dereferencable, as in the doubly nested for loop you referenced an invalid iterator (p was set to row.end()).

Edit: Also, unless you can assume that all the strings are the same length, you might consider a different technique. When you use const int c = s.length(), you are telling the map<int,string> and vector<char> the length of EVERY string in your file are the exact same length. If the second string is shorter than the first, you will try to access characters in the string that don't exist! Note the

rep(j,0,c) (p->second).copy(&matrix[i][j],1,k++)

will fail since it thinks it has c characters, when it in fact will not.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号