矢量及其大小和元素都在同一行

时间:2016-03-05 00:05:05

标签: c++ vector

设v是包含5个元素的向量:

8, 9, 100, 77, 90

我需要提供输出

5 8 9 100 77 90  

我如何在c ++中这样做?我无法想出如何控制打印尺寸的合适代码。

vector <int> v
v.push_back(8);
// all push back
for(int i=0;i<v.size();i++)
    cout<<v[i]<<" ";

3 个答案:

答案 0 :(得分:2)

#include <iostream>
#include <vector>

int main() {
    std::vector<int> v{8, 9, 100, 77, 90};

    // Print length of v:
    std::cout << v.size();

    // Print elements of v:
    for (auto value : v)
    {
        std::cout << ' ' << value;
    }

    // Print end-line and flush:
    std::cout << std::endl;
}

答案 1 :(得分:0)

这应该有效:

// Let v be a vector containing 5 elements as 8,9,100,77,90
std::vector <int> v{8,9,100,77,90};

// I need to give an output 5 ...
std::cout << v.size(); // print the size

// ... 8 9 100 77 90
for(auto item : v)
    std::cout << ' ' << item; // print the items

std::cout << std::endl;

Live Demo

答案 2 :(得分:0)

不会写一个额外的&#34; &#34;列表末尾的字符:

vector<int> v = { 8, 9, 100, 77, 90 };

cout << v.size();

for (auto i : v)
{
    cout << " " << i;
}

cout << endl;