繁体   English   中英

cin向量元素有多种方法吗?

[英]Is there multiple ways to cin vector elements?

我有一个程序可以在 1 个向量中添加多个向量。 我看到了一种方法 instead of.push_back 添加元素并使用了它,但我想知道为什么这有效,因为我认为 vector[] 表示索引,那么为什么 cin >> vector[] 将元素添加到 vector if square括号表示索引? 输入 - output 1 2; 5 4; 9 1 - 1 2; 5 4; 9 1

'''
    #include <vector>
    #include <iostream>
    using namespace std;
    int main()
    {
    int q = 3; //total number of q2 in q1
    vector<vector<int>> q1; //vector for q2's
        for(int a = 0; a < q; a++)
            {
            vector<int> q2(2); //making each q2 vector the size of 2 elements
            for(int b = 0; b < 2; b++){
                cin >> q2[b]; //adding elements to q2**how does this work instead of push_back?
                }
            q1.push_back(q2); //adding last q2 into q1
            }
    //printing q1
        for(int a = 0; a < q1.size(); a++){
            for(int b = 0; b < q1[a].size(); b++){
                cout << q1[a][b] << " ";
                }
            cout << endl;
            }
    }
'''

vector<int> q2(2)生成一个向量q2 ,其中包含 2 个默认构造的int元素。 您不需要push_back()元素,因为它在构造时会为您生成 2 个元素。

cin >> q2[b]仅编辑向量中已经存在的int元素。

#include<iostream>
#include<vector>
using namespace std;
double meannum(vector <double> &listnum);
int main()
{
    double dum {0.0};
    vector <double> listnum {};
    cout << "Enter the list of numbers to find the mean: press any non-integer key to stop"<<endl;
    while (cin >> dum) //enter any non-integer to end the loop!
    {
        listnum.push_back(dum);
    }
    cout << "List of numbers entered : "<< endl ;
    for(int i = 0;i < listnum.size();i++) {
         cout << listnum.at(i) << endl;
    }
    cout << " Finding the mean .....  " << endl;
    cout << "result: " << meannum(listnum);
}
double meannum(vector<double> &listnum)
{
    int len = listnum.size();
    double sum{ 0 };
    for (int i = 0; i < len; i++) {
        sum = sum + listnum.at(i);
    }
    double avg = sum / len;
    return avg;
}

暂无
暂无

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

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