0

我不知道如何像分配二维数组一样分配给二维向量。大批

MyArray[0][1] = "User";
MyArray[1][1] = "Pass";

对于向量,我不知道您是否需要使用推回或什么,但我需要能够将其分配给向量“[1][]”内的第二个点,但如果我没有,我会更喜欢调整向量的大小,然后在可能的情况下分配给它。

我的代码

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stdlib.h>

using namespace std;

vector<vector <string> > UserPass(2,vector <string> (1));
string User, Pass;
string lower(string var);
string resetInput;
string input;
int x;
int y;
void initUsers();
void prompt();
void password();
void login();
bool loginSuccess;


int main()
{
    initUsers();
    prompt();
    return 0;
}

void initUsers() {
    UserPass[0][0] = "admin";
    UserPass[1][0] = "admin";
}

void addUser(string User, string Pass) {
\\This is where I would add onto the vector
}

string lower(string var) {
    transform(var.begin(),var.end(),var.begin(), ::tolower);
    return var;
}

void login() 
{
    cout << "Please Enter your Username\n";
    cin >> User; 

    lower(User);
    cout << "Please Enter your Password\n";
    cin >> Pass;

    for (unsigned x = 0; x < 1; x++) {
        for (unsigned y = 0; y < UserPass.size(); y++) {
            if ((User == UserPass[x][y]) && (Pass == UserPass[x+1][y])) {
                loginSuccess = true;
                cout << "You have successfully logged in to your account." << endl;
                break;
            }
        }
    }
    if (loginSuccess == false) {
            cout << "Incorrect password or username.\n";
    }
}

void password()
{
    while(true) {
        cout << "Reset your Password to: \n";
        getline(cin, resetInput);

        UserPass[x+1][y] = resetInput;
        cout << UserPass[x+1][y] << " is now your new password\n";
        break;
    }
}

void prompt() 
{
    while(true){
        cout << ">";
        getline(cin,input);

        lower(input);
        if (input == "login" && loginSuccess == true) {
            cout << "You are already logged in as <" << User << ">" << endl;
        }
        if (input == "login" && loginSuccess == false) {
            login();
        }
        if ((input == "logout" && loginSuccess == false) or (input == "password" && loginSuccess == false)) {
            cout << "You have not logged in yet.\n";
       }
       if (input == "logout" && loginSuccess == true) {
           loginSuccess = false;
           cout << "You have successfully logged out.\n";
       }
       if (input == "password" && loginSuccess == true) {
           password();
       }
       if (input == "exit") {
           exit(EXIT_SUCCESS);
       }
       if (input == "clear"){
            system("cls");
      }
   }
}
4

2 回答 2

1

看来您应该使用地图而不是矢量。您的密钥可以是用户,关联的值可以是密码。这将避免通过所有用户的 O(N) 循环。如果您设置使用向量,因为您的顶级向量似乎只有两个值,您还可以使用每个结构(或对)的单个向量与用户并通过。

于 2015-04-05T21:02:13.470 回答
0

如果您想将用户及其密码添加到向量中,则该函数将如下所示

void addUser( const std::string &User, const std::string &Pass ) 
{
    UserPass.push_back( { User, Pass } );
}
于 2015-04-05T21:07:20.037 回答