我正在尝试编译下一个代码,但我在指定的行上收到此错误
"数组下标的类型`int [int]'无效"
码:
template<typename T>
class Stack {
private:
static const int GROW_FACTOR = 2;
static const int START_LENGHT = 10;
T * data;
int max;
int used;
void allocateIfNeeded() {
if (used == max) {
T * aux = new T[max*GROW_FACTOR];
for (int i=0; i<max; i++) {
aux[i] = data[i];
}
max *= GROW_FACTOR;
delete[] data;
data = aux;
}
}
public:
Stack() {
max = START_LENGHT;
data = new T[max];
used = 0;
}
void push(T data) …Run Code Online (Sandbox Code Playgroud) 是否可以使泛型类中的方法对于特定类型的行为完全不同?
class MyClass<T> {
public void myMethod(T t) { // Do something }
// something for myMethod(int t) { // DO something special }
}
Run Code Online (Sandbox Code Playgroud)
以这样的方式,允许我调用(new MyClass<String>()).myMethod(myString)它会做一些事情,也可以调用(new MyClass<int>()).myMethod(myInt)它会做一些特殊的事情。
我们来看下面的代码:
public class Test {
class A {
public A() {}
private void testMethod() {
System.out.println("A");
}
}
class B extends A {
public B() { super(); }
private void testMethod() {
System.out.println("B");
}
}
public Test() { }
public A get() {
return new B();
}
public static void main(String[] args) {
new Test().get().testMethod();
}
}
Run Code Online (Sandbox Code Playgroud)
我希望代码写B.A是写的.
可能会觉得奇怪(至少对我来说)一个类可以调用它包含的内部类的私有方法这一事实(为什么它们会这样做?),但我真正无法理解的是为什么多态不会工作.
我的意思是,如果从Test.main()我们可以称之为A.testMethod()显而易见,我们也称之为呼叫B.testMethod().Java还可以确定对象的动态类型,那么为什么Java调用声明类型的方法而不是动态类型的方法呢?可以检查此行为:
public static void main(String[] args) {
B b = new …Run Code Online (Sandbox Code Playgroud) 都int和float在Java中都是32位的大小的值.是否可以编写一对函数
int toInt(float f);
float toFloat(int n);
Run Code Online (Sandbox Code Playgroud)
如果f1和f2是任意float 非NaN值,i1和i2是任意int值:
f1 < f2 当且仅当 toInt(f1) < toInt(f2)f1 > f2 当且仅当 toInt(f1) > toInt(f2)f1 == f2 当且仅当 toInt(f1) == toInt(f2)toInt(toFloat(i1) == i1toFloat(toInt(f1)) == f1编辑:我已经编辑了问题以排除浮动的NaN值,这要归功于解释这些问题的答案.
在C/C++中,我想知道哪个更快?
int a;
int b = a + a; // this
int b = 2 * a; // or this?
Run Code Online (Sandbox Code Playgroud)
另外,数据类型是重要的吗?怎么样long?我们加起来的次数怎么样?
(关于什么...)
long a;
long b = a + a + a +a;
long b = 4 *a;
Run Code Online (Sandbox Code Playgroud) 所以我想出了ProjectEuler问题29的这个解决方案(http://projecteuler.net/problem=29)
答案是对的.我希望这段代码运行得非常快,但运行速度非常慢.我不知道为什么.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef vector<pair<int,int>> factorized_int; // pairs of base, exponent
factorized_int primeFactors(int n) {
int primeFactors[100] = {0};
for (int i=2; i <= n; i++) {
if (n%i == 0) {
primeFactors[i]++;
n /= i;
i--;
}
}
vector<pair<int,int>> retValue;
for (int i=2; i<100; i++) {
if (primeFactors[i] != 0) {
retValue.push_back(pair<int,int>(i,primeFactors[i]));
}
}
return retValue;
}
factorized_int pow(factorized_int n, int exponent) {
factorized_int retValue = factorized_int(n);
for (size_t …Run Code Online (Sandbox Code Playgroud) c++ ×4
c ×2
java ×2
performance ×2
arrays ×1
c# ×1
casting ×1
generics ×1
inheritance ×1
int ×1
optimization ×1
subscript ×1
templates ×1