你如何在c ++中使用向量?

时间:2016-08-18 00:10:12

标签: c++ vector

我是c ++的初学者,我正在努力理解向量。

我知道基本格式:

vector <dataType> vectorName;

人们告诉我,矢量就像数组。但是,我没有

理解,对于数组,你可以这样做:

array[] = {1, 2, 3}

但对于矢量,您似乎无法将其设置为列表。或者你有

继续使用.push_back()

另外,你可以使用vectorName[1]之类的东西吗?

任何人都可以向我解释这个吗?

感谢。

5 个答案:

答案 0 :(得分:5)

如果您使用C ++ 11或更高版本,则可以使用该样式。

#include <iostream>
#include <vector>

int main(void) {
    std::vector<int> vec = {1, 2, 3};
    std::cout << vec[1] << std::endl;
    return 0;
}

答案 1 :(得分:2)

向量的整个目的是“无限”,所以每次需要扩展它时都不需要重新定义它。

.filter()这样您就可以添加 / expand到数组而无需重新定义它;您仍然像普通数组一样访问和修改:

List()

你也可以初始化 old-school style (=是可选的):

items.get(filters[0].propToFilter)

答案 2 :(得分:1)

尝试使用C ++:

#include <iostream>
#include <vector>

int main(void) {
    std::vector<int> vec { 34,23 };
    return 0;
}

甚至:

#include <iostream>
#include <vector>

int main(void) {
    std::vector<int> v(2);
    v = { 34,23 };
    return 0;
}

答案 3 :(得分:1)

上面没有给出任何关于在创建矢量后处理矢量的提示,所以,假设你用很少的初始值创建它。

#include <iostream>
#include <vector>

int main(void) {
     std::vector<int> vec { 34,23 };
     // use push_back(some_value) if you have multiple values to put inside, say 1000. 
     // instead of using the index [] brackets, try .at() method 
     std::cout << vec.at(1) << std::endl;



     // use both the .size() or the new syntax to loop over it 
     for (unsigned i = 0 ; i < vec.size() ; i++){
       std::cout << vec.at(i) << std::endl;
     }
     // or the new syntax 
     for (auto & i : vec){
       std::cout << i << std::endl;
     }

     return 0;
}

玩得开心:)

答案 4 :(得分:0)

向量是可扩展的数组。与数组不同,您不限于使用它初始化它的大小。

向量的增长:无论何时溢出,向量都会使其大小翻倍。在引擎盖下面它仍然是一个阵列,但是可扩展的&#34;它的属性来自将前一个数组的内容复制到一个新的更大的数组中。

使用C ++中的向量可以做的事情很少

向量初始化

vector<Type> one (size, defaultValue);
vector<Type> two (one); // makes a new vector *two* with the contents of *one*
vector<int> three {1,2,3}; // using initializer list

访问元素

int temp = three[2]; //array like syntax
int temp = three.at(2);

您无法使用此语法增加矢量的大小,即您无法执行three[3]=4;

<强>扩展

three.pusk_back(4);

<强>收缩

three.pop_back();