Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/jsf/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在while循环中重新初始化向量?_C++_Algorithm_C++11_Initialization_Stdvector - Fatal编程技术网

C++ 如何在while循环中重新初始化向量?

C++ 如何在while循环中重新初始化向量?,c++,algorithm,c++11,initialization,stdvector,C++,Algorithm,C++11,Initialization,Stdvector,我正在教室里做一些练习。我正在尝试制作一个简单的游戏,需要用户连续输入向量 我试图重新初始化向量。我在while(1)循环中使用了clear()它 vector<int> user; // initialize vector while (1) { for (int guess; cin >> guess;)// looping {

我正在教室里做一些练习。我正在尝试制作一个简单的游戏,需要用户连续输入向量

我试图重新初始化向量。我在
while(1)
循环中使用了
clear()

vector<int> user;                 // initialize vector
while (1)
{                                 
    for (int guess; cin >> guess;)// looping
    {                             // user input
        user.push_back(guess);
    }
    if (user.size() != 4)         // check if user put exactly 4 numbers
    {         
        cerr << "Invalid input";
        return 1;
    }
    //...                        // doing some stuff with "int bulls"
    if (bulls == 4)
    {
        break;
    }
}    // now need to go back with emty vector, so that the user can input guesses again 
矢量用户;//初始化向量
而(1)
{                                 
for(int-guess;cin>>guess;)//循环
{//用户输入
用户。推回(猜测);
}
if(user.size()!=4)//检查用户是否恰好输入了4个数字
{         

cerr由于

for(int guess; cin >> guess;)
您将
推回到用户向量,直到
std::cin
失败

您可能希望有
4
用户输入。如果是这样,请尝试以下方法,在创建新的
循环时,不需要像在每个
循环中那样清除向量

while (true)
{   
    std::vector<int> user;
    user.reserve(4); // reserve memory which helps not to have unwanted reallocations
    int guess;
    while(cin >> guess &&  user.size() != 4)
        user.emplace_back(guess);

    // doing some stuff with "int bulls"
    if (bulls == 4) {
        break;
    }
}
while(true)
{   
std::矢量用户;
user.reserve(4);//保留内存,这有助于避免不必要的重新分配
智力猜测;
而(cin>>guess&&user.size()!=4)
用户。向后放置(猜测);
//用“int公牛”做一些事情
如果(多头==4){
打破
}
}

由于

for(int guess; cin >> guess;)
您将
推回到用户向量,直到
std::cin
失败

您可能希望有
4
用户输入。如果是这样,请尝试以下方法,在创建新的
循环时,不需要像在每个
循环中那样清除向量

while (true)
{   
    std::vector<int> user;
    user.reserve(4); // reserve memory which helps not to have unwanted reallocations
    int guess;
    while(cin >> guess &&  user.size() != 4)
        user.emplace_back(guess);

    // doing some stuff with "int bulls"
    if (bulls == 4) {
        break;
    }
}
while(true)
{   
std::矢量用户;
user.reserve(4);//保留内存,这有助于避免不必要的重新分配
智力猜测;
而(cin>>guess&&user.size()!=4)
用户。向后放置(猜测);
//用“int公牛”做一些事情
如果(多头==4){
打破
}
}

如果要在读取输入之前清除,请将清除置于while之后。如果要在读取输入之前清除,请将清除置于while之后。