简体   繁体   English

从C ++输入创建2D向量

[英]Create 2D vector from input in C++

quick question here. 在这里快速提问。 I'm wondering how to create a 2D vector from user input. 我想知道如何根据用户输入创建2D向量。 For a project, I am storing my "board" as a 2D vector, and the user will enter the height and width of it, as well as perhaps the starting configuration. 对于一个项目,我存储我的“板”作为2D向量,用户将进入高度和宽度它,以及可能的起始配置。

If my board is stored as: 如果我的板存储为:

vector<vector<int> > myBoard( width, vector<int> (height) ); 
//Not sure how to get width and height from input...

I will need to initialize it to the given parameters and (if the user supplies the information), fill in the board with pieces. 我将需要将其初始化为给定的参数,并且(如果用户提供了信息),请在板上填充各个部分。 The user will input all this information on 1 line, via 1 cin. 用户将通过1 cin在1行上输入所有这些信息。 So like this... 像这样

Please type the board config: 3 3

or 要么

Please type the board config: 3 3 . . . . . . X . O

or 要么

Please type the board config: 3 3 ABFDFL($%$

With the last one being an example of bad input. 最后一个是输入错误的示例。 The first example would create a 2D vector, 3 by 3. The second would create a 2D vector, 3 by 3, and fill in the board with the position given. 第一个示例将创建3 * 3的2D矢量。第二个示例将创建3 * 3的2D矢量,并使用给定位置填充木板。 In this case, "." 在这种情况下, ”。” is a 0, "X" is a 1, and "O" will be a -1. 是0,“ X”是1,“ O”是-1。 That's the part I'm having the most trouble with. 那是我最麻烦的部分。 I could store it to a string, but it seems that going through and parsing it would be a pain in the butt... 我可以将其存储到字符串中,但是似乎要经历并解析它的过程会很麻烦……

I would try to infer the dimensions from the user input. 我会尝试从用户输入推断尺寸。

An example session: 会话示例:

A board consists of characters ., X or O.
An example board:
.XO
...
X..

Enter the board, end with two Returns:
.....
..XO.
.XXX.
OOOOO
.....

Then you would scan the first row to find the width, check each row for valid characters and the same width, and count the rows to find the height. 然后,您将扫描第一行以找到宽度,检查每行中是否有有效字符和相同宽度,然后对行进行计数以找到高度。

You could use a map where the key is a std::pair of the board coordinates read from cin as integers. 您可以使用键为std :: pair且从cin读取为整数的板坐标的映射。 The value representation could then be a int or char and is easily accessible. 值表示形式可以是int或char,并且可以轻松访问。 Then you could do things like... 然后您可以做...

if(board[std::pair(x,y)] == '.')
  //do something;

Parse it already, for heaven's sake! 为了天堂的缘故,已经解析了! If all you allow is '.', 'X', and 'O', then basically all you have to do is skip whitespace. 如果您只允许'。','X'和'O',那么基本上您要做的就是跳过空格。 (If you love your users, you might consider allowing lower-case letters too.) (如果您喜欢用户,则可以考虑允许使用小写字母。)

I could store it to a string, but it seems that going through and parsing it would be a pain in the butt... 我可以将其存储到字符串中,但是似乎要经历并解析它的过程会很麻烦……

Why? 为什么? It's a single if / else chain or switch . 它是单个if / else chain或switch

And sooner or later you'll get tired of managing vectors of vectors. 迟早您会厌倦管理向量的向量的。 I would put the whole board in a single vector and address it y * width + x . 我将整个电路板放在一个向量中,并处理为y * width + x It might even become a class of its own in the future: 将来它甚至可能成为自己的一类:

Piece board::getPieceAt(int x, int y) const
{
    ...
}

Pseudocode that probably leads to a square wheel. 伪代码可能导致方轮。

getline( cin, board );  

find location of first space: board.find( ' ' );  
assign this to size_t height  
extract the digit(s) to a sting (or vector?): board.substr( 0, height )  
atoi this string for the height  
cut this from the string: board = board.substr( height )  
repeat for width  
initialize the realBoard vector with width and height  

if board still has chars, start filling the board  
initialize two ints for the vector coordinates  
initialize another for putting numbers onto the board  

until you get to the end of board  
send board[ i ] to a switch  
as you said, o/O = -1; x/X = 1; ./default = 0  
(unless you want bad input to interrupt execution)  
put the value into realBoard[ h ][ w ]  
add one to w;  
if it is above width, make it 0, add one to h  
if h > height, stop this function  

Here is a method using cin and its mechanisms: 这是使用cin及其机制的方法:

#include <stdio.h>
#include <iostream>
#include <vector>
#include <limits>
#include <ctype.h>


using namespace std;


int main(){
    int x;
    int y;
    bool done = false;

    vector< int > inputs;
    char holdValue;


    while ( !done )
    {
        inputs.clear();
        cout << "Enter Data:" << endl; //something more descriptive then then this
        cin >> x >> y;
        if(cin.fail())
        {
            cin.clear();
            cin.ignore( std::numeric_limits<std::streamsize>::max(),'\n' );
            cout << "Error with your input" << endl;
            continue;
        }

        int i = 0;
        bool error = false;
        for ( ;  i < ( x * y ) && error != true ; ++i )
        {
            cin >> holdValue;
            if(cin.fail())
            {
                cin.clear();
                cin.ignore( std::numeric_limits<std::streamsize>::max(),'\n' );
                cout << "Error with your input" << endl;
                error = true;
            }
            switch( toupper( holdValue ) )
            {
                case 'X':
                    inputs.push_back( 1 );
                    break;

                case 'O':
                    inputs.push_back( -1 );
                    break;

                case '.':
                    inputs.push_back( 0 );
                    break;

                default:
                    cin.ignore( std::numeric_limits<std::streamsize>::max(),'\n' );
                    cout << "Error with your input" << endl;
                    error = true;
                    break;
            }
        }

        if( i >= ( x * y )  && error != true )
        {
            done = true;
        }
    }

    //At this piont you have a vector to do with as you please

}

But fot that amount of effort you might as well read it into a std::string and write a parser and get it over with. 但是,经过如此多的努力,您最好将其读入std :: string并编写一个解析器,然后再使用它。 If will be faster and allot easier to do what you want if you get wrong input. 如果输入错误,可以更快,更轻松地进行所需的操作。

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

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