C++ 定义全局的std::vector<int> 报错,加上 static const 就正常
时间: 2024-01-21 14:05:03 浏览: 23
这是因为 C++ 中定义全局变量的时候,会将其放在数据区中,如果没有加上 static 关键字,那么每个文件都会有一个该全局变量的实例,会导致链接时出现重复定义的错误。而加上 static 关键字可以限定该全局变量只在当前文件中可见,避免了重复定义的问题。
而对于 const 类型的全局变量,编译器会将其视为常量,放在代码段中,不会在数据区中分配内存,因此不会出现重复定义的问题。
因此,为了避免重复定义的错误,建议在定义全局变量时加上 static 关键字。如果全局变量是 const 类型的,加不加 static 关键字都可以。
相关问题
在std::vector<std::vector<int>>删除某些std::vector<int>
在std::vector<std::vector<int>>中删除某些std::vector<int>可以使用erase-remove idiom的方法。这个方法结合了erase和remove两个函数,可以高效地删除指定的元素。
以下是删除某些std::vector<int>的步骤:
1. 使用std::remove_if函数结合lambda表达式来标记要删除的std::vector<int>。lambda表达式可以根据特定的条件来判断是否需要删除。
2. 使用std::erase函数将被标记为删除的std::vector<int>从std::vector<std::vector<int>>中移除。
下面是示例代码:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<std::vector<int>> vecOfVec = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};
// 删除满足条件的std::vector<int>
vecOfVec.erase(std::remove_if(vecOfVec.begin(), vecOfVec.end(), [](const std::vector<int>& vec) {
// 根据特定条件判断是否需要删除
return vec.size() == 3; // 删除长度为3的std::vector<int>
}), vecOfVec.end());
// 输出结果
for (const auto& vec : vecOfVec) {
for (const auto& num : vec) {
std::cout << num << " ";
}
std::cout << std::endl;
}
return 0;
}
```
输出结果:
```
4 5 6
7 8 9
```
C++:如何std::vector<std::vector<int>>中的元素都是唯一的
可以使用类似于去重的方法,对于vector<vector<int>>这种类型的嵌套容器,我们需要自定义比较函数,来判断两个vector<int>是否相等。然后,我们可以将每个vector<int>排序,这样就可以保证每个vector<int>中的元素都是唯一的。最后,再通过类似于去重的方法,去除重复的vector<int>。示例代码如下:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
bool isEqual(const std::vector<int>& v1, const std::vector<int>& v2) {
if (v1.size() != v2.size()) {
return false;
}
for (size_t i = 0; i < v1.size(); ++i) {
if (v1[i] != v2[i]) {
return false;
}
}
return true;
}
bool isUnique(const std::vector<std::vector<int>>& v) {
// 将每个vector<int>排序
std::vector<std::vector<int>> sorted_v = v;
for (auto& inner_v : sorted_v) {
std::sort(inner_v.begin(), inner_v.end());
}
// 去除重复的vector<int>
auto new_end = std::unique(sorted_v.begin(), sorted_v.end(), isEqual);
sorted_v.erase(new_end, sorted_v.end());
// 判断是否全部唯一
return sorted_v.size() == v.size();
}
int main() {
std::vector<std::vector<int>> v1{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
std::cout << std::boolalpha << isUnique(v1) << std::endl; // true
std::vector<std::vector<int>> v2{
{1, 2, 3},
{4, 5, 6},
{1, 2, 3}
};
std::cout << std::boolalpha << isUnique(v2) << std::endl; // false
return 0;
}
```
输出结果为:
```
true
false
```
其中,isUnique函数用于判断vector<vector<int>>中的元素是否都是唯一的。首先,将每个vector<int>排序,然后再使用类似于去重的方法,去除重复的vector<int>。如果去重后的vector<vector<int>>中的元素个数与原始的vector<vector<int>>中的元素个数相等,就说明每个vector<int>都是唯一的。